From 5a49d4a5bafb319df620eb70e098765fdab1529e Mon Sep 17 00:00:00 2001 From: Guillaume Nodet Date: Mon, 15 Jul 2024 18:07:50 +0200 Subject: [PATCH] Port effective-pom, effective-settings, evaluate and system mojos --- pom.xml | 184 ++++------ .../pom.xml | 2 +- .../test.properties | 2 +- .../test.properties | 2 +- src/it/projects/evaluate/test.properties | 2 +- .../active-profiles/invoker.properties | 0 .../active-profiles/pom.xml | 0 .../active-profiles/verify.groovy | 0 .../invoker.properties | 0 .../module/pom.xml | 0 .../active-profiles_multimodule/pom.xml | 0 .../active-profiles_multimodule/verify.groovy | 0 .../all-profiles-parent-pom/child/pom.xml | 0 .../invoker.properties | 0 .../all-profiles-parent-pom/pom.xml | 0 .../all-profiles-parent-pom/verify.groovy | 0 .../all-profiles/invoker.properties | 0 .../all-profiles/pom.xml | 0 .../all-profiles/verify.groovy | 0 .../describe-cmd-invalid/invoker.properties | 0 .../describe-cmd-invalid/pom.xml | 0 .../describe-cmd-invalid/test.properties | 0 .../invoker.properties | 0 .../describe-cmd-with-goal-invalid/pom.xml | 0 .../test.properties | 0 .../invoker.properties | 0 .../describe-cmd-with-goal-report/pom.xml | 0 .../verify.groovy | 0 .../describe-cmd-with-goal/invoker.properties | 0 .../describe-cmd-with-goal/pom.xml | 0 .../describe-cmd-with-goal/test.properties | 0 .../describe-cmd-with-goal/verify.groovy | 0 .../describe-cmd/invoker.properties | 0 .../describe-cmd/pom.xml | 0 .../describe-cmd/test-deploy.properties | 0 .../describe-cmd/test-site.properties | 0 .../describe-cmd/verify.groovy | 0 .../describe-ga/invoker.properties | 0 .../describe-ga/pom.xml | 0 .../describe-ga/test.properties | 0 .../describe-gav/invoker.properties | 0 .../describe-gav/pom.xml | 0 .../describe-gav/test.properties | 0 .../invoker.properties | 0 .../pom.xml | 0 .../test.properties | 0 .../verify.groovy | 0 .../invoker.properties | 0 .../describe-plugin-without-name/pom.xml | 0 .../test.properties | 0 .../verify.groovy | 0 .../invoker.properties | 0 .../describe-prefix-and-invalid-mojo/pom.xml | 0 .../test.properties | 0 .../verify.groovy | 0 .../invoker.properties | 0 .../describe-prefix-and-mojo/pom.xml | 0 .../describe-prefix-and-mojo/test.properties | 0 .../describe-prefix/invoker.properties | 0 .../describe-prefix/pom.xml | 0 .../describe-prefix/test.properties | 0 .../plugins/help/AbstractEffectiveMojo.java | 53 +-- .../maven/plugins/help/AbstractHelpMojo.java | 146 ++++---- .../maven/plugins/help/EffectivePomMojo.java | 126 +++---- .../plugins/help/EffectiveSettingsMojo.java | 190 ++++------- .../maven/plugins/help/EvaluateMojo.java | 319 ++++++------------ .../apache/maven/plugins/help/SystemMojo.java | 205 +++++++++-- .../ActiveProfilesMojo.java | 23 +- .../help => to-migrate}/AllProfilesMojo.java | 30 +- .../help => to-migrate}/DescribeMojo.java | 199 +++++------ .../plugins/help/EffectivePomMojoTest.java | 118 +++++++ .../maven/plugins/help/EvaluateMojoTest.java | 237 ++++++------- .../help/stubs/DefaultMavenProjectStub.java | 55 --- .../plugin-config.xml} | 3 +- .../evaluate/plugin-config-quiet-stdout.xml | 39 --- .../ActiveProfilesMojoTest.java | 0 .../AllProfilesMojoTest.java | 0 .../help => to-migrate}/DescribeMojoTest.java | 0 78 files changed, 910 insertions(+), 1025 deletions(-) rename src/it/{projects => to-migrate}/active-profiles/invoker.properties (100%) rename src/it/{projects => to-migrate}/active-profiles/pom.xml (100%) rename src/it/{projects => to-migrate}/active-profiles/verify.groovy (100%) rename src/it/{projects => to-migrate}/active-profiles_multimodule/invoker.properties (100%) rename src/it/{projects => to-migrate}/active-profiles_multimodule/module/pom.xml (100%) rename src/it/{projects => to-migrate}/active-profiles_multimodule/pom.xml (100%) rename src/it/{projects => to-migrate}/active-profiles_multimodule/verify.groovy (100%) rename src/it/{projects => to-migrate}/all-profiles-parent-pom/child/pom.xml (100%) rename src/it/{projects => to-migrate}/all-profiles-parent-pom/invoker.properties (100%) rename src/it/{projects => to-migrate}/all-profiles-parent-pom/pom.xml (100%) rename src/it/{projects => to-migrate}/all-profiles-parent-pom/verify.groovy (100%) rename src/it/{projects => to-migrate}/all-profiles/invoker.properties (100%) rename src/it/{projects => to-migrate}/all-profiles/pom.xml (100%) rename src/it/{projects => to-migrate}/all-profiles/verify.groovy (100%) rename src/it/{projects => to-migrate}/describe-cmd-invalid/invoker.properties (100%) rename src/it/{projects => to-migrate}/describe-cmd-invalid/pom.xml (100%) rename src/it/{projects => to-migrate}/describe-cmd-invalid/test.properties (100%) rename src/it/{projects => to-migrate}/describe-cmd-with-goal-invalid/invoker.properties (100%) rename src/it/{projects => to-migrate}/describe-cmd-with-goal-invalid/pom.xml (100%) rename src/it/{projects => to-migrate}/describe-cmd-with-goal-invalid/test.properties (100%) rename src/it/{projects => to-migrate}/describe-cmd-with-goal-report/invoker.properties (100%) rename src/it/{projects => to-migrate}/describe-cmd-with-goal-report/pom.xml (100%) rename src/it/{projects => to-migrate}/describe-cmd-with-goal-report/verify.groovy (100%) rename src/it/{projects => to-migrate}/describe-cmd-with-goal/invoker.properties (100%) rename src/it/{projects => to-migrate}/describe-cmd-with-goal/pom.xml (100%) rename src/it/{projects => to-migrate}/describe-cmd-with-goal/test.properties (100%) rename src/it/{projects => to-migrate}/describe-cmd-with-goal/verify.groovy (100%) rename src/it/{projects => to-migrate}/describe-cmd/invoker.properties (100%) rename src/it/{projects => to-migrate}/describe-cmd/pom.xml (100%) rename src/it/{projects => to-migrate}/describe-cmd/test-deploy.properties (100%) rename src/it/{projects => to-migrate}/describe-cmd/test-site.properties (100%) rename src/it/{projects => to-migrate}/describe-cmd/verify.groovy (100%) rename src/it/{projects => to-migrate}/describe-ga/invoker.properties (100%) rename src/it/{projects => to-migrate}/describe-ga/pom.xml (100%) rename src/it/{projects => to-migrate}/describe-ga/test.properties (100%) rename src/it/{projects => to-migrate}/describe-gav/invoker.properties (100%) rename src/it/{projects => to-migrate}/describe-gav/pom.xml (100%) rename src/it/{projects => to-migrate}/describe-gav/test.properties (100%) rename src/it/{projects => to-migrate}/describe-plugin-in-plugin-management/invoker.properties (100%) rename src/it/{projects => to-migrate}/describe-plugin-in-plugin-management/pom.xml (100%) rename src/it/{projects => to-migrate}/describe-plugin-in-plugin-management/test.properties (100%) rename src/it/{projects => to-migrate}/describe-plugin-in-plugin-management/verify.groovy (100%) rename src/it/{projects => to-migrate}/describe-plugin-without-name/invoker.properties (100%) rename src/it/{projects => to-migrate}/describe-plugin-without-name/pom.xml (100%) rename src/it/{projects => to-migrate}/describe-plugin-without-name/test.properties (100%) rename src/it/{projects => to-migrate}/describe-plugin-without-name/verify.groovy (100%) rename src/it/{projects => to-migrate}/describe-prefix-and-invalid-mojo/invoker.properties (100%) rename src/it/{projects => to-migrate}/describe-prefix-and-invalid-mojo/pom.xml (100%) rename src/it/{projects => to-migrate}/describe-prefix-and-invalid-mojo/test.properties (100%) rename src/it/{projects => to-migrate}/describe-prefix-and-invalid-mojo/verify.groovy (100%) rename src/it/{projects => to-migrate}/describe-prefix-and-mojo/invoker.properties (100%) rename src/it/{projects => to-migrate}/describe-prefix-and-mojo/pom.xml (100%) rename src/it/{projects => to-migrate}/describe-prefix-and-mojo/test.properties (100%) rename src/it/{projects => to-migrate}/describe-prefix/invoker.properties (100%) rename src/it/{projects => to-migrate}/describe-prefix/pom.xml (100%) rename src/it/{projects => to-migrate}/describe-prefix/test.properties (100%) rename src/main/{java/org/apache/maven/plugins/help => to-migrate}/ActiveProfilesMojo.java (83%) rename src/main/{java/org/apache/maven/plugins/help => to-migrate}/AllProfilesMojo.java (84%) rename src/main/{java/org/apache/maven/plugins/help => to-migrate}/DescribeMojo.java (82%) create mode 100644 src/test/java/org/apache/maven/plugins/help/EffectivePomMojoTest.java delete mode 100644 src/test/java/org/apache/maven/plugins/help/stubs/DefaultMavenProjectStub.java rename src/test/resources/unit/{evaluate/plugin-config-output.xml => effective-pom/plugin-config.xml} (94%) delete mode 100644 src/test/resources/unit/evaluate/plugin-config-quiet-stdout.xml rename src/test/{java/org/apache/maven/plugins/help => to-migrate}/ActiveProfilesMojoTest.java (100%) rename src/test/{java/org/apache/maven/plugins/help => to-migrate}/AllProfilesMojoTest.java (100%) rename src/test/{java/org/apache/maven/plugins/help => to-migrate}/DescribeMojoTest.java (100%) diff --git a/pom.xml b/pom.xml index e5e60d9c..a672a717 100644 --- a/pom.xml +++ b/pom.xml @@ -23,12 +23,12 @@ org.apache.maven.plugins maven-plugins - 42 + 43 maven-help-plugin - 3.4.2-SNAPSHOT + 4.0.0-SNAPSHOT maven-plugin Apache Maven Help Plugin @@ -64,9 +64,13 @@ - 8 - 3.6.3 - 1.4.1 + 17 + 4.0.0-beta-3 + + 6.0.0 + 0.9.0.M2 + 4.0.3 + 4.0.0-beta-1 2024-06-02T15:17:10Z @@ -74,122 +78,64 @@ org.apache.maven - maven-artifact - ${mavenVersion} - provided - - - org.apache.maven - maven-core + maven-api-core ${mavenVersion} provided org.apache.maven - maven-model + maven-api-model ${mavenVersion} provided org.apache.maven - maven-model-builder + maven-api-settings ${mavenVersion} provided org.apache.maven - maven-plugin-api + maven-api-impl ${mavenVersion} - provided org.apache.maven - maven-settings + maven-core ${mavenVersion} - provided - - - org.apache.maven.resolver - maven-resolver-api - ${resolverVersion} - provided - - - - - org.apache.maven.plugin-tools - maven-plugin-tools-generators - ${version.maven-plugin-tools} - - - - org.apache.maven - * - - - org.apache.maven.plugin-tools - * - - - org.apache.maven.reporting - * - - - org.apache.velocity - * - - - net.sf.jtidy - * - - - org.codehaus.plexus - * - - - org.ow2.asm - * - - - - - - org.apache.maven.plugin-tools - maven-plugin-annotations - provided - - org.apache.maven.shared - maven-shared-utils - 3.4.2 - - - commons-io - commons-io - - - + + + + + + + + + + + - - org.apache.maven.reporting - maven-reporting-api - 3.1.1 - - - - * - * - - - + + + + + + + + + + + + - - org.codehaus.plexus - plexus-interactivity-api - 1.3 - + + + + + org.codehaus.plexus plexus-utils @@ -199,6 +145,17 @@ plexus-xml + + org.codehaus.woodstox + stax2-api + 4.2.2 + + + com.fasterxml.woodstox + woodstox-core + 7.0.0 + + org.jdom @@ -218,34 +175,33 @@ - junit - junit - 4.13.2 + org.junit.jupiter + junit-jupiter-api + test + + + org.mockito + mockito-core + + 4.11.0 test org.apache.maven.plugin-testing maven-plugin-testing-harness - 3.3.0 + 4.0.0-beta-1 test - - - org.codehaus.plexus - plexus-container-default - - - org.apache.maven - maven-compat - ${mavenVersion} - test + org.eclipse.sisu + org.eclipse.sisu.plexus + ${sisuVersion} + provided - org.mockito - mockito-core - - 4.11.0 + com.google.inject + guice + ${guiceVersion} test diff --git a/src/it/projects/evaluate-artifact-with-expression-with-output/pom.xml b/src/it/projects/evaluate-artifact-with-expression-with-output/pom.xml index 7176ee40..70e947f4 100644 --- a/src/it/projects/evaluate-artifact-with-expression-with-output/pom.xml +++ b/src/it/projects/evaluate-artifact-with-expression-with-output/pom.xml @@ -47,7 +47,7 @@ under the License. org.apache.maven.plugins maven-enforcer-plugin - 1.4.1 + 3.5.0 enforce-currentproject diff --git a/src/it/projects/evaluate-artifact-with-expression-with-output/test.properties b/src/it/projects/evaluate-artifact-with-expression-with-output/test.properties index 632b331f..10abccc4 100644 --- a/src/it/projects/evaluate-artifact-with-expression-with-output/test.properties +++ b/src/it/projects/evaluate-artifact-with-expression-with-output/test.properties @@ -15,6 +15,6 @@ # specific language governing permissions and limitations # under the License. -expression = project.name +expression = project.model.name output = result.txt artifact = org.apache.maven.plugins:maven-help-plugin diff --git a/src/it/projects/evaluate-with-expression-with-output/test.properties b/src/it/projects/evaluate-with-expression-with-output/test.properties index 5f9820fd..b8e431b2 100644 --- a/src/it/projects/evaluate-with-expression-with-output/test.properties +++ b/src/it/projects/evaluate-with-expression-with-output/test.properties @@ -15,5 +15,5 @@ # specific language governing permissions and limitations # under the License. -expression = project.name +expression = project.model.name output = result.txt diff --git a/src/it/projects/evaluate/test.properties b/src/it/projects/evaluate/test.properties index 0d5498b2..4b8f6c27 100644 --- a/src/it/projects/evaluate/test.properties +++ b/src/it/projects/evaluate/test.properties @@ -15,4 +15,4 @@ # specific language governing permissions and limitations # under the License. -expression = project.description +expression = project.model.description diff --git a/src/it/projects/active-profiles/invoker.properties b/src/it/to-migrate/active-profiles/invoker.properties similarity index 100% rename from src/it/projects/active-profiles/invoker.properties rename to src/it/to-migrate/active-profiles/invoker.properties diff --git a/src/it/projects/active-profiles/pom.xml b/src/it/to-migrate/active-profiles/pom.xml similarity index 100% rename from src/it/projects/active-profiles/pom.xml rename to src/it/to-migrate/active-profiles/pom.xml diff --git a/src/it/projects/active-profiles/verify.groovy b/src/it/to-migrate/active-profiles/verify.groovy similarity index 100% rename from src/it/projects/active-profiles/verify.groovy rename to src/it/to-migrate/active-profiles/verify.groovy diff --git a/src/it/projects/active-profiles_multimodule/invoker.properties b/src/it/to-migrate/active-profiles_multimodule/invoker.properties similarity index 100% rename from src/it/projects/active-profiles_multimodule/invoker.properties rename to src/it/to-migrate/active-profiles_multimodule/invoker.properties diff --git a/src/it/projects/active-profiles_multimodule/module/pom.xml b/src/it/to-migrate/active-profiles_multimodule/module/pom.xml similarity index 100% rename from src/it/projects/active-profiles_multimodule/module/pom.xml rename to src/it/to-migrate/active-profiles_multimodule/module/pom.xml diff --git a/src/it/projects/active-profiles_multimodule/pom.xml b/src/it/to-migrate/active-profiles_multimodule/pom.xml similarity index 100% rename from src/it/projects/active-profiles_multimodule/pom.xml rename to src/it/to-migrate/active-profiles_multimodule/pom.xml diff --git a/src/it/projects/active-profiles_multimodule/verify.groovy b/src/it/to-migrate/active-profiles_multimodule/verify.groovy similarity index 100% rename from src/it/projects/active-profiles_multimodule/verify.groovy rename to src/it/to-migrate/active-profiles_multimodule/verify.groovy diff --git a/src/it/projects/all-profiles-parent-pom/child/pom.xml b/src/it/to-migrate/all-profiles-parent-pom/child/pom.xml similarity index 100% rename from src/it/projects/all-profiles-parent-pom/child/pom.xml rename to src/it/to-migrate/all-profiles-parent-pom/child/pom.xml diff --git a/src/it/projects/all-profiles-parent-pom/invoker.properties b/src/it/to-migrate/all-profiles-parent-pom/invoker.properties similarity index 100% rename from src/it/projects/all-profiles-parent-pom/invoker.properties rename to src/it/to-migrate/all-profiles-parent-pom/invoker.properties diff --git a/src/it/projects/all-profiles-parent-pom/pom.xml b/src/it/to-migrate/all-profiles-parent-pom/pom.xml similarity index 100% rename from src/it/projects/all-profiles-parent-pom/pom.xml rename to src/it/to-migrate/all-profiles-parent-pom/pom.xml diff --git a/src/it/projects/all-profiles-parent-pom/verify.groovy b/src/it/to-migrate/all-profiles-parent-pom/verify.groovy similarity index 100% rename from src/it/projects/all-profiles-parent-pom/verify.groovy rename to src/it/to-migrate/all-profiles-parent-pom/verify.groovy diff --git a/src/it/projects/all-profiles/invoker.properties b/src/it/to-migrate/all-profiles/invoker.properties similarity index 100% rename from src/it/projects/all-profiles/invoker.properties rename to src/it/to-migrate/all-profiles/invoker.properties diff --git a/src/it/projects/all-profiles/pom.xml b/src/it/to-migrate/all-profiles/pom.xml similarity index 100% rename from src/it/projects/all-profiles/pom.xml rename to src/it/to-migrate/all-profiles/pom.xml diff --git a/src/it/projects/all-profiles/verify.groovy b/src/it/to-migrate/all-profiles/verify.groovy similarity index 100% rename from src/it/projects/all-profiles/verify.groovy rename to src/it/to-migrate/all-profiles/verify.groovy diff --git a/src/it/projects/describe-cmd-invalid/invoker.properties b/src/it/to-migrate/describe-cmd-invalid/invoker.properties similarity index 100% rename from src/it/projects/describe-cmd-invalid/invoker.properties rename to src/it/to-migrate/describe-cmd-invalid/invoker.properties diff --git a/src/it/projects/describe-cmd-invalid/pom.xml b/src/it/to-migrate/describe-cmd-invalid/pom.xml similarity index 100% rename from src/it/projects/describe-cmd-invalid/pom.xml rename to src/it/to-migrate/describe-cmd-invalid/pom.xml diff --git a/src/it/projects/describe-cmd-invalid/test.properties b/src/it/to-migrate/describe-cmd-invalid/test.properties similarity index 100% rename from src/it/projects/describe-cmd-invalid/test.properties rename to src/it/to-migrate/describe-cmd-invalid/test.properties diff --git a/src/it/projects/describe-cmd-with-goal-invalid/invoker.properties b/src/it/to-migrate/describe-cmd-with-goal-invalid/invoker.properties similarity index 100% rename from src/it/projects/describe-cmd-with-goal-invalid/invoker.properties rename to src/it/to-migrate/describe-cmd-with-goal-invalid/invoker.properties diff --git a/src/it/projects/describe-cmd-with-goal-invalid/pom.xml b/src/it/to-migrate/describe-cmd-with-goal-invalid/pom.xml similarity index 100% rename from src/it/projects/describe-cmd-with-goal-invalid/pom.xml rename to src/it/to-migrate/describe-cmd-with-goal-invalid/pom.xml diff --git a/src/it/projects/describe-cmd-with-goal-invalid/test.properties b/src/it/to-migrate/describe-cmd-with-goal-invalid/test.properties similarity index 100% rename from src/it/projects/describe-cmd-with-goal-invalid/test.properties rename to src/it/to-migrate/describe-cmd-with-goal-invalid/test.properties diff --git a/src/it/projects/describe-cmd-with-goal-report/invoker.properties b/src/it/to-migrate/describe-cmd-with-goal-report/invoker.properties similarity index 100% rename from src/it/projects/describe-cmd-with-goal-report/invoker.properties rename to src/it/to-migrate/describe-cmd-with-goal-report/invoker.properties diff --git a/src/it/projects/describe-cmd-with-goal-report/pom.xml b/src/it/to-migrate/describe-cmd-with-goal-report/pom.xml similarity index 100% rename from src/it/projects/describe-cmd-with-goal-report/pom.xml rename to src/it/to-migrate/describe-cmd-with-goal-report/pom.xml diff --git a/src/it/projects/describe-cmd-with-goal-report/verify.groovy b/src/it/to-migrate/describe-cmd-with-goal-report/verify.groovy similarity index 100% rename from src/it/projects/describe-cmd-with-goal-report/verify.groovy rename to src/it/to-migrate/describe-cmd-with-goal-report/verify.groovy diff --git a/src/it/projects/describe-cmd-with-goal/invoker.properties b/src/it/to-migrate/describe-cmd-with-goal/invoker.properties similarity index 100% rename from src/it/projects/describe-cmd-with-goal/invoker.properties rename to src/it/to-migrate/describe-cmd-with-goal/invoker.properties diff --git a/src/it/projects/describe-cmd-with-goal/pom.xml b/src/it/to-migrate/describe-cmd-with-goal/pom.xml similarity index 100% rename from src/it/projects/describe-cmd-with-goal/pom.xml rename to src/it/to-migrate/describe-cmd-with-goal/pom.xml diff --git a/src/it/projects/describe-cmd-with-goal/test.properties b/src/it/to-migrate/describe-cmd-with-goal/test.properties similarity index 100% rename from src/it/projects/describe-cmd-with-goal/test.properties rename to src/it/to-migrate/describe-cmd-with-goal/test.properties diff --git a/src/it/projects/describe-cmd-with-goal/verify.groovy b/src/it/to-migrate/describe-cmd-with-goal/verify.groovy similarity index 100% rename from src/it/projects/describe-cmd-with-goal/verify.groovy rename to src/it/to-migrate/describe-cmd-with-goal/verify.groovy diff --git a/src/it/projects/describe-cmd/invoker.properties b/src/it/to-migrate/describe-cmd/invoker.properties similarity index 100% rename from src/it/projects/describe-cmd/invoker.properties rename to src/it/to-migrate/describe-cmd/invoker.properties diff --git a/src/it/projects/describe-cmd/pom.xml b/src/it/to-migrate/describe-cmd/pom.xml similarity index 100% rename from src/it/projects/describe-cmd/pom.xml rename to src/it/to-migrate/describe-cmd/pom.xml diff --git a/src/it/projects/describe-cmd/test-deploy.properties b/src/it/to-migrate/describe-cmd/test-deploy.properties similarity index 100% rename from src/it/projects/describe-cmd/test-deploy.properties rename to src/it/to-migrate/describe-cmd/test-deploy.properties diff --git a/src/it/projects/describe-cmd/test-site.properties b/src/it/to-migrate/describe-cmd/test-site.properties similarity index 100% rename from src/it/projects/describe-cmd/test-site.properties rename to src/it/to-migrate/describe-cmd/test-site.properties diff --git a/src/it/projects/describe-cmd/verify.groovy b/src/it/to-migrate/describe-cmd/verify.groovy similarity index 100% rename from src/it/projects/describe-cmd/verify.groovy rename to src/it/to-migrate/describe-cmd/verify.groovy diff --git a/src/it/projects/describe-ga/invoker.properties b/src/it/to-migrate/describe-ga/invoker.properties similarity index 100% rename from src/it/projects/describe-ga/invoker.properties rename to src/it/to-migrate/describe-ga/invoker.properties diff --git a/src/it/projects/describe-ga/pom.xml b/src/it/to-migrate/describe-ga/pom.xml similarity index 100% rename from src/it/projects/describe-ga/pom.xml rename to src/it/to-migrate/describe-ga/pom.xml diff --git a/src/it/projects/describe-ga/test.properties b/src/it/to-migrate/describe-ga/test.properties similarity index 100% rename from src/it/projects/describe-ga/test.properties rename to src/it/to-migrate/describe-ga/test.properties diff --git a/src/it/projects/describe-gav/invoker.properties b/src/it/to-migrate/describe-gav/invoker.properties similarity index 100% rename from src/it/projects/describe-gav/invoker.properties rename to src/it/to-migrate/describe-gav/invoker.properties diff --git a/src/it/projects/describe-gav/pom.xml b/src/it/to-migrate/describe-gav/pom.xml similarity index 100% rename from src/it/projects/describe-gav/pom.xml rename to src/it/to-migrate/describe-gav/pom.xml diff --git a/src/it/projects/describe-gav/test.properties b/src/it/to-migrate/describe-gav/test.properties similarity index 100% rename from src/it/projects/describe-gav/test.properties rename to src/it/to-migrate/describe-gav/test.properties diff --git a/src/it/projects/describe-plugin-in-plugin-management/invoker.properties b/src/it/to-migrate/describe-plugin-in-plugin-management/invoker.properties similarity index 100% rename from src/it/projects/describe-plugin-in-plugin-management/invoker.properties rename to src/it/to-migrate/describe-plugin-in-plugin-management/invoker.properties diff --git a/src/it/projects/describe-plugin-in-plugin-management/pom.xml b/src/it/to-migrate/describe-plugin-in-plugin-management/pom.xml similarity index 100% rename from src/it/projects/describe-plugin-in-plugin-management/pom.xml rename to src/it/to-migrate/describe-plugin-in-plugin-management/pom.xml diff --git a/src/it/projects/describe-plugin-in-plugin-management/test.properties b/src/it/to-migrate/describe-plugin-in-plugin-management/test.properties similarity index 100% rename from src/it/projects/describe-plugin-in-plugin-management/test.properties rename to src/it/to-migrate/describe-plugin-in-plugin-management/test.properties diff --git a/src/it/projects/describe-plugin-in-plugin-management/verify.groovy b/src/it/to-migrate/describe-plugin-in-plugin-management/verify.groovy similarity index 100% rename from src/it/projects/describe-plugin-in-plugin-management/verify.groovy rename to src/it/to-migrate/describe-plugin-in-plugin-management/verify.groovy diff --git a/src/it/projects/describe-plugin-without-name/invoker.properties b/src/it/to-migrate/describe-plugin-without-name/invoker.properties similarity index 100% rename from src/it/projects/describe-plugin-without-name/invoker.properties rename to src/it/to-migrate/describe-plugin-without-name/invoker.properties diff --git a/src/it/projects/describe-plugin-without-name/pom.xml b/src/it/to-migrate/describe-plugin-without-name/pom.xml similarity index 100% rename from src/it/projects/describe-plugin-without-name/pom.xml rename to src/it/to-migrate/describe-plugin-without-name/pom.xml diff --git a/src/it/projects/describe-plugin-without-name/test.properties b/src/it/to-migrate/describe-plugin-without-name/test.properties similarity index 100% rename from src/it/projects/describe-plugin-without-name/test.properties rename to src/it/to-migrate/describe-plugin-without-name/test.properties diff --git a/src/it/projects/describe-plugin-without-name/verify.groovy b/src/it/to-migrate/describe-plugin-without-name/verify.groovy similarity index 100% rename from src/it/projects/describe-plugin-without-name/verify.groovy rename to src/it/to-migrate/describe-plugin-without-name/verify.groovy diff --git a/src/it/projects/describe-prefix-and-invalid-mojo/invoker.properties b/src/it/to-migrate/describe-prefix-and-invalid-mojo/invoker.properties similarity index 100% rename from src/it/projects/describe-prefix-and-invalid-mojo/invoker.properties rename to src/it/to-migrate/describe-prefix-and-invalid-mojo/invoker.properties diff --git a/src/it/projects/describe-prefix-and-invalid-mojo/pom.xml b/src/it/to-migrate/describe-prefix-and-invalid-mojo/pom.xml similarity index 100% rename from src/it/projects/describe-prefix-and-invalid-mojo/pom.xml rename to src/it/to-migrate/describe-prefix-and-invalid-mojo/pom.xml diff --git a/src/it/projects/describe-prefix-and-invalid-mojo/test.properties b/src/it/to-migrate/describe-prefix-and-invalid-mojo/test.properties similarity index 100% rename from src/it/projects/describe-prefix-and-invalid-mojo/test.properties rename to src/it/to-migrate/describe-prefix-and-invalid-mojo/test.properties diff --git a/src/it/projects/describe-prefix-and-invalid-mojo/verify.groovy b/src/it/to-migrate/describe-prefix-and-invalid-mojo/verify.groovy similarity index 100% rename from src/it/projects/describe-prefix-and-invalid-mojo/verify.groovy rename to src/it/to-migrate/describe-prefix-and-invalid-mojo/verify.groovy diff --git a/src/it/projects/describe-prefix-and-mojo/invoker.properties b/src/it/to-migrate/describe-prefix-and-mojo/invoker.properties similarity index 100% rename from src/it/projects/describe-prefix-and-mojo/invoker.properties rename to src/it/to-migrate/describe-prefix-and-mojo/invoker.properties diff --git a/src/it/projects/describe-prefix-and-mojo/pom.xml b/src/it/to-migrate/describe-prefix-and-mojo/pom.xml similarity index 100% rename from src/it/projects/describe-prefix-and-mojo/pom.xml rename to src/it/to-migrate/describe-prefix-and-mojo/pom.xml diff --git a/src/it/projects/describe-prefix-and-mojo/test.properties b/src/it/to-migrate/describe-prefix-and-mojo/test.properties similarity index 100% rename from src/it/projects/describe-prefix-and-mojo/test.properties rename to src/it/to-migrate/describe-prefix-and-mojo/test.properties diff --git a/src/it/projects/describe-prefix/invoker.properties b/src/it/to-migrate/describe-prefix/invoker.properties similarity index 100% rename from src/it/projects/describe-prefix/invoker.properties rename to src/it/to-migrate/describe-prefix/invoker.properties diff --git a/src/it/projects/describe-prefix/pom.xml b/src/it/to-migrate/describe-prefix/pom.xml similarity index 100% rename from src/it/projects/describe-prefix/pom.xml rename to src/it/to-migrate/describe-prefix/pom.xml diff --git a/src/it/projects/describe-prefix/test.properties b/src/it/to-migrate/describe-prefix/test.properties similarity index 100% rename from src/it/projects/describe-prefix/test.properties rename to src/it/to-migrate/describe-prefix/test.properties diff --git a/src/main/java/org/apache/maven/plugins/help/AbstractEffectiveMojo.java b/src/main/java/org/apache/maven/plugins/help/AbstractEffectiveMojo.java index fab3e6b9..89c07c9d 100644 --- a/src/main/java/org/apache/maven/plugins/help/AbstractEffectiveMojo.java +++ b/src/main/java/org/apache/maven/plugins/help/AbstractEffectiveMojo.java @@ -20,19 +20,13 @@ import javax.xml.XMLConstants; -import java.io.File; import java.io.IOException; import java.io.StringReader; import java.io.StringWriter; -import java.io.Writer; -import java.util.ArrayList; -import java.util.Collections; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Properties; -import java.util.Set; -import org.codehaus.plexus.util.WriterFactory; +import org.apache.maven.api.Session; +import org.apache.maven.api.di.Inject; +import org.apache.maven.api.plugin.annotations.Parameter; import org.codehaus.plexus.util.xml.XMLWriter; import org.codehaus.plexus.util.xml.XmlWriterUtil; import org.jdom2.Document; @@ -48,24 +42,18 @@ * @since 2.1 */ public abstract class AbstractEffectiveMojo extends AbstractHelpMojo { + /** - * Utility method to write an XML content in a given file. + * This options gives the option to output information in cases where the output has been suppressed by using + * -q (quiet option) in Maven. * - * @param output is the wanted output file. - * @param content contains the XML content to be written to the file. - * @throws IOException if any - * @see AbstractHelpMojo#writeFile(File, String) if encoding is null. + * @since 4.0.0 */ - protected static void writeXmlFile(File output, String content) throws IOException { - if (output == null) { - return; - } + @Parameter(property = "forceStdout", defaultValue = "false") + protected boolean forceStdout; - output.getParentFile().mkdirs(); - try (Writer out = WriterFactory.newXmlWriter(output)) { - out.write(content); - } - } + @Inject + protected Session session; /** * Write comments in the Effective POM/settings header. @@ -124,23 +112,4 @@ protected static String prettyFormat(String effectiveModel, String encoding, boo return effectiveModel; } } - - /** - * Properties which provides a sorted keySet(). - */ - protected static class SortedProperties extends Properties { - /** serialVersionUID */ - static final long serialVersionUID = -8985316072702233744L; - - /** {@inheritDoc} */ - @SuppressWarnings({"rawtypes", "unchecked"}) - @Override - public Set keySet() { - Set keynames = super.keySet(); - List list = new ArrayList(keynames); - Collections.sort(list); - - return new LinkedHashSet<>(list); - } - } } diff --git a/src/main/java/org/apache/maven/plugins/help/AbstractHelpMojo.java b/src/main/java/org/apache/maven/plugins/help/AbstractHelpMojo.java index 0439b836..ba4fc3a7 100644 --- a/src/main/java/org/apache/maven/plugins/help/AbstractHelpMojo.java +++ b/src/main/java/org/apache/maven/plugins/help/AbstractHelpMojo.java @@ -18,29 +18,27 @@ */ package org.apache.maven.plugins.help; -import java.io.File; import java.io.IOException; import java.io.Writer; - -import org.apache.maven.artifact.Artifact; -import org.apache.maven.execution.MavenSession; -import org.apache.maven.model.building.ModelBuildingRequest; -import org.apache.maven.plugin.AbstractMojo; -import org.apache.maven.plugin.MojoExecutionException; -import org.apache.maven.plugins.annotations.Component; -import org.apache.maven.plugins.annotations.Parameter; -import org.apache.maven.project.DefaultProjectBuildingRequest; -import org.apache.maven.project.MavenProject; -import org.apache.maven.project.ProjectBuilder; -import org.apache.maven.project.ProjectBuildingRequest; -import org.codehaus.plexus.util.WriterFactory; -import org.eclipse.aether.RepositoryException; -import org.eclipse.aether.RepositorySystem; -import org.eclipse.aether.RepositorySystemSession; -import org.eclipse.aether.artifact.DefaultArtifact; -import org.eclipse.aether.resolution.ArtifactDescriptorRequest; -import org.eclipse.aether.resolution.ArtifactDescriptorResult; -import org.eclipse.aether.resolution.ArtifactRequest; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Map; + +import org.apache.maven.api.Artifact; +import org.apache.maven.api.ArtifactCoordinate; +import org.apache.maven.api.Project; +import org.apache.maven.api.Session; +import org.apache.maven.api.di.Inject; +import org.apache.maven.api.plugin.Log; +import org.apache.maven.api.plugin.Mojo; +import org.apache.maven.api.plugin.MojoException; +import org.apache.maven.api.plugin.annotations.Parameter; +import org.apache.maven.api.services.ArtifactResolverException; +import org.apache.maven.api.services.ProjectBuilder; +import org.apache.maven.api.services.ProjectBuilderRequest; +import org.apache.maven.api.services.ProjectManager; +import org.codehaus.plexus.util.io.CachingWriter; /** * Base class with some Help Mojo functionalities. @@ -48,37 +46,35 @@ * @author Vincent Siveton * @since 2.1 */ -public abstract class AbstractHelpMojo extends AbstractMojo { +public abstract class AbstractHelpMojo implements Mojo { /** The maximum length of a display line. */ protected static final int LINE_LENGTH = 79; /** The line separator for the current OS. */ - protected static final String LS = System.getProperty("line.separator"); + protected static final String LS = System.lineSeparator(); /** - * Maven Project Builder component. + * Current Maven project. */ - @Component - protected ProjectBuilder projectBuilder; + @Inject + protected Project project; /** - * Component used to resolve artifacts and download their files from remote repositories. + * The current build session instance. */ - @Component - protected RepositorySystem repositorySystem; + @Inject + protected Session session; - /** - * Current Maven project. - */ - @Parameter(defaultValue = "${project}", readonly = true, required = true) - protected MavenProject project; + @Inject + protected Log log; - /** - * The current build session instance. This is used for - * plugin manager API calls. - */ - @Parameter(defaultValue = "${session}", readonly = true, required = true) - protected MavenSession session; + public Log getLog() { + return log; + } + + public void setLog(Log log) { + this.log = log; + } /** * Optional parameter to write the output of this help in a given file, instead of writing to the console. @@ -86,7 +82,7 @@ public abstract class AbstractHelpMojo extends AbstractMojo { * Note: Could be a relative path. */ @Parameter(property = "output") - protected File output; + protected Path output; /** * Utility method to write a content in a given file. @@ -94,9 +90,9 @@ public abstract class AbstractHelpMojo extends AbstractMojo { * @param output is the wanted output file. * @param content contains the content to be written to the file. * @throws IOException if any - * @see #writeFile(File, String) + * @see #writeFile(Path, String) */ - protected static void writeFile(File output, StringBuilder content) throws IOException { + protected static void writeFile(Path output, StringBuilder content) throws IOException { writeFile(output, content.toString()); } @@ -107,13 +103,12 @@ protected static void writeFile(File output, StringBuilder content) throws IOExc * @param content contains the content to be written to the file. * @throws IOException if any */ - protected static void writeFile(File output, String content) throws IOException { + protected static void writeFile(Path output, String content) throws IOException { if (output == null) { return; } - - output.getParentFile().mkdirs(); - try (Writer out = WriterFactory.newPlatformWriter(output)) { + Files.createDirectories(output.getParent()); + try (Writer out = new CachingWriter(output, StandardCharsets.UTF_8)) { out.write(content); } } @@ -124,10 +119,9 @@ protected static void writeFile(File output, String content) throws IOException * @param artifactString should respect the format groupId:artifactId[:version] * @param type The extension for the artifact, must not be null. * @return the Artifact object for the artifactString parameter. - * @throws MojoExecutionException if the artifactString doesn't respect the format. + * @throws MojoException if the artifactString doesn't respect the format. */ - protected org.eclipse.aether.artifact.Artifact getAetherArtifact(String artifactString, String type) - throws MojoExecutionException { + protected ArtifactCoordinate getArtifactCoordinate(String artifactString, String type) throws MojoException { if (artifactString == null || artifactString.isEmpty()) { throw new IllegalArgumentException("artifact parameter could not be empty"); } @@ -141,7 +135,7 @@ protected org.eclipse.aether.artifact.Artifact getAetherArtifact(String artifact case 2: groupId = artifactParts[0]; artifactId = artifactParts[1]; - version = Artifact.LATEST_VERSION; + version = "LATEST"; break; case 3: groupId = artifactParts[0]; @@ -149,11 +143,11 @@ protected org.eclipse.aether.artifact.Artifact getAetherArtifact(String artifact version = artifactParts[2]; break; default: - throw new MojoExecutionException("The artifact parameter '" + artifactString - + "' should be conform to: " + "'groupId:artifactId[:version]'."); + throw new MojoException("The artifact parameter '" + artifactString + "' should be conform to: " + + "'groupId:artifactId[:version]'."); } - return new DefaultArtifact(groupId, artifactId, type, version); + return session.createArtifactCoordinate(groupId, artifactId, version, type); } /** @@ -163,39 +157,33 @@ protected org.eclipse.aether.artifact.Artifact getAetherArtifact(String artifact * * @param artifactString Coordinates of the Maven project to get. * @return New Maven project. - * @throws MojoExecutionException If there was an error while getting the Maven project. + * @throws MojoException If there was an error while getting the Maven project. */ - protected MavenProject getMavenProject(String artifactString) throws MojoExecutionException { + protected Project getMavenProject(String artifactString) throws MojoException { try { - ProjectBuildingRequest pbr = new DefaultProjectBuildingRequest(session.getProjectBuildingRequest()); - pbr.setRemoteRepositories(project.getRemoteArtifactRepositories()); - pbr.setPluginArtifactRepositories(project.getPluginArtifactRepositories()); - pbr.setProject(null); - pbr.setValidationLevel(ModelBuildingRequest.VALIDATION_LEVEL_MINIMAL); - pbr.setResolveDependencies(true); - - org.eclipse.aether.artifact.Artifact artifact = - resolveArtifact(getAetherArtifact(artifactString, "pom")).getArtifact(); - - return projectBuilder.build(artifact.getFile(), pbr).getProject(); + Path artifact = resolveArtifact(getArtifactCoordinate(artifactString, "pom")) + .getValue(); + + ProjectBuilder projectBuilder = session.getService(ProjectBuilder.class); + ProjectBuilderRequest request = ProjectBuilderRequest.builder() + .session(session.withRemoteRepositories( + session.getService(ProjectManager.class).getRemoteProjectRepositories(project))) + .path(artifact) + .processPlugins(false) + .build(); + return projectBuilder.build(request).getProject().orElseThrow(); } catch (Exception e) { - throw new MojoExecutionException( + throw new MojoException( "Unable to get the POM for the artifact '" + artifactString + "'. Verify the artifact parameter.", e); } } - protected org.eclipse.aether.resolution.ArtifactResult resolveArtifact( - org.eclipse.aether.artifact.Artifact artifact) throws RepositoryException { - RepositorySystemSession repositorySession = session.getRepositorySession(); - - // use descriptor to respect relocation - ArtifactDescriptorResult artifactDescriptor = repositorySystem.readArtifactDescriptor( - repositorySession, - new ArtifactDescriptorRequest(artifact, project.getRemoteProjectRepositories(), null)); + protected Map.Entry resolveArtifact(ArtifactCoordinate artifact) throws ArtifactResolverException { - return repositorySystem.resolveArtifact( - repositorySession, - new ArtifactRequest(artifactDescriptor.getArtifact(), project.getRemoteProjectRepositories(), null)); + // TODO: do we need an additional indirection to support relocation ? + Session s = session.withRemoteRepositories( + session.getService(ProjectManager.class).getRemoteProjectRepositories(project)); + return s.resolveArtifact(artifact); } } diff --git a/src/main/java/org/apache/maven/plugins/help/EffectivePomMojo.java b/src/main/java/org/apache/maven/plugins/help/EffectivePomMojo.java index 4e421487..0f53ed46 100644 --- a/src/main/java/org/apache/maven/plugins/help/EffectivePomMojo.java +++ b/src/main/java/org/apache/maven/plugins/help/EffectivePomMojo.java @@ -18,24 +18,26 @@ */ package org.apache.maven.plugins.help; +import javax.xml.stream.XMLStreamException; + import java.io.IOException; import java.io.StringWriter; +import java.nio.charset.Charset; import java.util.Collections; import java.util.List; -import java.util.Properties; - -import org.apache.maven.model.InputLocation; -import org.apache.maven.model.InputSource; -import org.apache.maven.model.Model; -import org.apache.maven.model.io.xpp3.MavenXpp3Writer; -import org.apache.maven.model.io.xpp3.MavenXpp3WriterEx; -import org.apache.maven.plugin.MojoExecution; -import org.apache.maven.plugin.MojoExecution.Source; -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; -import org.apache.maven.shared.utils.logging.MessageUtils; +import java.util.TreeMap; + +import org.apache.maven.api.MojoExecution; +import org.apache.maven.api.Project; +import org.apache.maven.api.di.Inject; +import org.apache.maven.api.model.InputLocation; +import org.apache.maven.api.model.InputSource; +import org.apache.maven.api.model.Model; +import org.apache.maven.api.plugin.MojoException; +import org.apache.maven.api.plugin.annotations.Mojo; +import org.apache.maven.api.plugin.annotations.Parameter; +import org.apache.maven.api.services.MessageBuilderFactory; +import org.apache.maven.model.v4.MavenStaxWriter; import org.codehaus.plexus.util.StringUtils; import org.codehaus.plexus.util.xml.PrettyPrintXMLWriter; import org.codehaus.plexus.util.xml.XMLWriter; @@ -57,13 +59,13 @@ public class EffectivePomMojo extends AbstractEffectiveMojo { * The projects in the current build. The effective-POM for * each of these projects will written. */ - @Parameter(defaultValue = "${reactorProjects}", required = true, readonly = true) - private List projects; + @Parameter(defaultValue = "${session.projects}", required = true, readonly = true) + private List projects; /** * This mojo execution, used to determine if it was launched from the lifecycle or the command-line. */ - @Parameter(defaultValue = "${mojo}", required = true, readonly = true) + @Inject private MojoExecution mojoExecution; /** @@ -90,14 +92,16 @@ public class EffectivePomMojo extends AbstractEffectiveMojo { // ---------------------------------------------------------------------- /** {@inheritDoc} */ - public void execute() throws MojoExecutionException { + public void execute() throws MojoException { if (artifact != null && !artifact.isEmpty()) { project = getMavenProject(artifact); projects = Collections.singletonList(project); } StringWriter w = new StringWriter(); - String encoding = output != null ? project.getModel().getModelEncoding() : System.getProperty("file.encoding"); + String encoding = output != null + ? project.getModel().getModelEncoding() + : Charset.defaultCharset().displayName(); XMLWriter writer = new PrettyPrintXMLWriter( w, StringUtils.repeat(" ", XmlWriterUtil.DEFAULT_INDENTATION_SIZE), encoding, null); @@ -106,7 +110,7 @@ public void execute() throws MojoExecutionException { if (shouldWriteAllEffectivePOMsInReactor()) { // outer root element writer.startElement("projects"); - for (MavenProject subProject : projects) { + for (Project subProject : projects) { writeEffectivePom(subProject, writer); } writer.endElement(); @@ -122,24 +126,31 @@ public void execute() throws MojoExecutionException { if (output != null) { try { - writeXmlFile(output, effectivePom); + writeFile(output, effectivePom); } catch (IOException e) { - throw new MojoExecutionException("Cannot write effective-POM to output: " + output, e); + throw new MojoException("Cannot write effective-POM to output: " + output, e); } getLog().info("Effective-POM written to: " + output); } else { - if (MessageUtils.isColorEnabled()) { - // add color to comments - String comment = MessageUtils.buffer().project("").toString(); - int dotIndex = comment.indexOf("."); - String commentStart = comment.substring(0, dotIndex); - String commentEnd = comment.substring(dotIndex + 1); - effectivePom = effectivePom.replace("", commentEnd); + if (verbose) { + MessageBuilderFactory mbf = session.getService(MessageBuilderFactory.class); + if (mbf.isColorEnabled()) { + // add color to comments + String comment = mbf.builder().project("").toString(); + int dotIndex = comment.indexOf("."); + String commentStart = comment.substring(0, dotIndex); + String commentEnd = comment.substring(dotIndex + 1); + effectivePom = effectivePom.replace("", commentEnd); + } } - getLog().info(LS + "Effective POMs, after inheritance, interpolation, and profiles are applied:" + LS + LS - + effectivePom + LS); + if (getLog().isInfoEnabled()) { + getLog().info(LS + "Effective POMs, after inheritance, interpolation, and profiles are applied:" + LS + + LS + effectivePom + LS); + } else if (forceStdout) { + System.out.println(effectivePom); + } } } @@ -150,10 +161,8 @@ public void execute() throws MojoExecutionException { * * @return true if all effective POMs should be written, false otherwise. */ - private boolean shouldWriteAllEffectivePOMsInReactor() { - Source source = mojoExecution.getSource(); - // [MNG-5550] For Maven < 3.2.1, the source is null, instead of LIFECYCLE: only rely on comparisons with CLI - return projects.size() > 1 && (source == Source.CLI || projects.get(0).equals(project)); + protected boolean shouldWriteAllEffectivePOMsInReactor() { + return projects.size() > 1 && ("default-cli".equals(mojoExecution.getExecutionId()) || project.isRootProject()); } // ---------------------------------------------------------------------- @@ -165,23 +174,19 @@ private boolean shouldWriteAllEffectivePOMsInReactor() { * * @param project the project of the current build, not null. * @param writer the XML writer , not null, not null. - * @throws MojoExecutionException if any + * @throws MojoException if any */ - private void writeEffectivePom(MavenProject project, XMLWriter writer) throws MojoExecutionException { - Model pom = project.getModel(); - cleanModel(pom); + private void writeEffectivePom(Project project, XMLWriter writer) throws MojoException { + Model pom = cleanModel(project.getModel()); StringWriter sWriter = new StringWriter(); try { - if (verbose) { - MavenXpp3WriterEx mavenXpp3WriterEx = new MavenXpp3WriterEx(); - mavenXpp3WriterEx.setStringFormatter(new InputLocationStringFormatter()); - mavenXpp3WriterEx.write(sWriter, pom); - } else { - new MavenXpp3Writer().write(sWriter, pom); - } - } catch (IOException e) { - throw new MojoExecutionException("Cannot serialize POM to XML.", e); + MavenStaxWriter w = new MavenStaxWriter(); + w.setAddLocationInformation(verbose); + w.setStringFormatter(EffectivePomMojo::toString); + w.write(sWriter, pom); + } catch (XMLStreamException | IOException e) { + throw new MojoException("Cannot serialize POM to XML.", e); } // This removes the XML declaration written by MavenXpp3Writer @@ -197,25 +202,20 @@ private void writeEffectivePom(MavenProject project, XMLWriter writer) throws Mo * * @param pom not null */ - private static void cleanModel(Model pom) { - Properties properties = new SortedProperties(); - properties.putAll(pom.getProperties()); - pom.setProperties(properties); + private static Model cleanModel(Model pom) { + return pom.withProperties(new TreeMap<>(pom.getProperties())); } - private static class InputLocationStringFormatter extends InputLocation.StringFormatter { - @Override - public String toString(InputLocation location) { - InputSource source = location.getSource(); - - String s = source.getModelId(); // by default, display modelId + public static String toString(InputLocation location) { + InputSource source = location.getSource(); - if (StringUtils.isBlank(s) || s.contains("[unknown-version]")) { - // unless it is blank or does not provide version information - s = source.toString(); - } + String s = source.getModelId(); // by default, display modelId - return '}' + s + ((location.getLineNumber() >= 0) ? ", line " + location.getLineNumber() : "") + ' '; + if (StringUtils.isBlank(s) || s.contains("[unknown-version]")) { + // unless it is blank or does not provide version information + s = source.toString(); } + + return '}' + s + ((location.getLineNumber() >= 0) ? ", line " + location.getLineNumber() : "") + ' '; } } diff --git a/src/main/java/org/apache/maven/plugins/help/EffectiveSettingsMojo.java b/src/main/java/org/apache/maven/plugins/help/EffectiveSettingsMojo.java index cf237086..5b034eb3 100644 --- a/src/main/java/org/apache/maven/plugins/help/EffectiveSettingsMojo.java +++ b/src/main/java/org/apache/maven/plugins/help/EffectiveSettingsMojo.java @@ -22,19 +22,20 @@ import java.io.StringWriter; import java.net.InetAddress; import java.net.UnknownHostException; -import java.util.ArrayList; -import java.util.List; -import java.util.Properties; - -import org.apache.maven.plugin.MojoExecutionException; -import org.apache.maven.plugins.annotations.Mojo; -import org.apache.maven.plugins.annotations.Parameter; -import org.apache.maven.settings.Profile; -import org.apache.maven.settings.Proxy; -import org.apache.maven.settings.Server; -import org.apache.maven.settings.Settings; -import org.apache.maven.settings.SettingsUtils; -import org.apache.maven.settings.io.xpp3.SettingsXpp3Writer; +import java.nio.charset.Charset; +import java.util.Map; +import java.util.TreeMap; +import java.util.function.Supplier; + +import org.apache.maven.api.plugin.MojoException; +import org.apache.maven.api.plugin.annotations.Mojo; +import org.apache.maven.api.plugin.annotations.Parameter; +import org.apache.maven.api.services.xml.SettingsXmlFactory; +import org.apache.maven.api.settings.Profile; +import org.apache.maven.api.settings.Proxy; +import org.apache.maven.api.settings.Server; +import org.apache.maven.api.settings.Settings; +import org.apache.maven.settings.v4.SettingsTransformer; import org.codehaus.plexus.util.StringUtils; import org.codehaus.plexus.util.xml.PrettyPrintXMLWriter; import org.codehaus.plexus.util.xml.XMLWriter; @@ -46,7 +47,7 @@ * * @since 2.0 */ -@Mojo(name = "effective-settings", requiresProject = false) +@Mojo(name = "effective-settings", projectRequired = false) public class EffectiveSettingsMojo extends AbstractEffectiveMojo { // ---------------------------------------------------------------------- // Mojo parameters @@ -56,7 +57,7 @@ public class EffectiveSettingsMojo extends AbstractEffectiveMojo { * The system settings for Maven. This is the instance resulting from * merging global and user-level settings files. */ - @Parameter(defaultValue = "${settings}", readonly = true, required = true) + @Parameter(property = "session.settings") private Settings settings; /** @@ -72,21 +73,13 @@ public class EffectiveSettingsMojo extends AbstractEffectiveMojo { // ---------------------------------------------------------------------- /** {@inheritDoc} */ - public void execute() throws MojoExecutionException { - Settings copySettings; - if (showPasswords) { - copySettings = settings; - } else { - copySettings = copySettings(settings); - if (copySettings != null) { - hidePasswords(copySettings); - } - } + public void execute() throws MojoException { + Settings copySettings = copySettings(settings, showPasswords); StringWriter w = new StringWriter(); String encoding = output != null && copySettings != null ? copySettings.getModelEncoding() - : System.getProperty("file.encoding"); + : Charset.defaultCharset().displayName(); XMLWriter writer = new PrettyPrintXMLWriter( w, StringUtils.repeat(" ", XmlWriterUtil.DEFAULT_INDENTATION_SIZE), encoding, null); @@ -98,14 +91,19 @@ public void execute() throws MojoExecutionException { if (output != null) { try { - writeXmlFile(output, effectiveSettings); + writeFile(output, effectiveSettings); } catch (IOException e) { - throw new MojoExecutionException("Cannot write effective-settings to output: " + output, e); + throw new MojoException("Cannot write effective-settings to output: " + output, e); } getLog().info("Effective-settings written to: " + output); } else { - getLog().info(LS + "Effective user-specific configuration settings:" + LS + LS + effectiveSettings + LS); + if (getLog().isInfoEnabled()) { + getLog().info(LS + "Effective user-specific configuration settings:" + LS + LS + effectiveSettings + + LS); + } else if (forceStdout) { + System.out.println(effectiveSettings); + } } } @@ -113,79 +111,58 @@ public void execute() throws MojoExecutionException { // Private methods // ---------------------------------------------------------------------- - /** - * Hide proxy and server passwords. - * - * @param aSettings not null - */ - private static void hidePasswords(Settings aSettings) { - List proxies = aSettings.getProxies(); - for (Proxy proxy : proxies) { - if (StringUtils.isNotEmpty(proxy.getPassword())) { - proxy.setPassword("***"); - } - } - - List servers = aSettings.getServers(); - for (Server server : servers) { - // Password - if (StringUtils.isNotEmpty(server.getPassword())) { - server.setPassword("***"); - } - // Passphrase - if (StringUtils.isNotEmpty(server.getPassphrase())) { - server.setPassphrase("***"); - } - } - } - /** * @param settings could be {@code null} * @return a new instance of settings or {@code null} if settings was {@code null}. */ - private static Settings copySettings(Settings settings) { + private static Settings copySettings(Settings settings, boolean showPasswords) { if (settings == null) { return null; } - // Not a deep copy in M2.2.1 !!! - Settings clone = SettingsUtils.copySettings(settings); - - List clonedServers = new ArrayList<>(settings.getServers().size()); - for (Server server : settings.getServers()) { - Server clonedServer = new Server(); - clonedServer.setConfiguration(server.getConfiguration()); - clonedServer.setDirectoryPermissions(server.getDirectoryPermissions()); - clonedServer.setFilePermissions(server.getFilePermissions()); - clonedServer.setId(server.getId()); - clonedServer.setPassphrase(server.getPassphrase()); - clonedServer.setPassword(server.getPassword()); - clonedServer.setPrivateKey(server.getPrivateKey()); - clonedServer.setSourceLevel(server.getSourceLevel()); - clonedServer.setUsername(server.getUsername()); - - clonedServers.add(clonedServer); - } - clone.setServers(clonedServers); - - List clonedProxies = new ArrayList<>(settings.getProxies().size()); - for (Proxy proxy : settings.getProxies()) { - Proxy clonedProxy = new Proxy(); - clonedProxy.setActive(proxy.isActive()); - clonedProxy.setHost(proxy.getHost()); - clonedProxy.setId(proxy.getId()); - clonedProxy.setNonProxyHosts(proxy.getNonProxyHosts()); - clonedProxy.setPassword(proxy.getPassword()); - clonedProxy.setPort(proxy.getPort()); - clonedProxy.setProtocol(proxy.getProtocol()); - clonedProxy.setSourceLevel(proxy.getSourceLevel()); - clonedProxy.setUsername(proxy.getUsername()); - - clonedProxies.add(clonedProxy); - } - clone.setProxies(clonedProxies); + SettingsTransformer transformer = new SettingsTransformer(s -> s) { + @Override + protected Server.Builder transformServer_Password( + Supplier creator, Server.Builder builder, Server target) { + String oldVal = target.getPassword(); + String newVal = !showPasswords && oldVal != null && !oldVal.isEmpty() ? "***" : oldVal; + return newVal != oldVal ? (builder != null ? builder : creator.get()).password(newVal) : builder; + } + + @Override + protected Server.Builder transformServer_Passphrase( + Supplier creator, Server.Builder builder, Server target) { + String oldVal = target.getPassphrase(); + String newVal = !showPasswords && oldVal != null && !oldVal.isEmpty() ? "***" : oldVal; + return newVal != oldVal ? (builder != null ? builder : creator.get()).passphrase(newVal) : builder; + } + + @Override + protected Proxy.Builder transformProxy_Password( + Supplier creator, Proxy.Builder builder, Proxy target) { + String oldVal = target.getPassword(); + String newVal = !showPasswords && oldVal != null && !oldVal.isEmpty() ? "***" : oldVal; + return newVal != oldVal ? (builder != null ? builder : creator.get()).password(newVal) : builder; + } + + @Override + protected Profile.Builder transformProfile_Properties( + Supplier creator, Profile.Builder builder, Profile target) { + Map props = target.getProperties(); + Map newProps = new TreeMap<>(props); + for (Map.Entry entry : props.entrySet()) { + String newVal = transform(entry.getValue()); + if (newVal != null) { + newProps.put(entry.getKey(), newVal); + } + } + builder = builder != null ? builder : creator.get(); + builder.properties(newProps); + return builder; + } + }; - return clone; + return transformer.visit(settings); } /** @@ -193,17 +170,14 @@ private static Settings copySettings(Settings settings) { * * @param settings the settings, not null. * @param writer the XML writer used, not null. - * @throws MojoExecutionException if any + * @throws MojoException if any */ - private static void writeEffectiveSettings(Settings settings, XMLWriter writer) throws MojoExecutionException { - cleanSettings(settings); - + private void writeEffectiveSettings(Settings settings, XMLWriter writer) throws MojoException { StringWriter sWriter = new StringWriter(); - SettingsXpp3Writer settingsWriter = new SettingsXpp3Writer(); try { - settingsWriter.write(sWriter, settings); - } catch (IOException e) { - throw new MojoExecutionException("Cannot serialize Settings to XML.", e); + session.getService(SettingsXmlFactory.class).write(settings, sWriter); + } catch (Exception e) { + throw new MojoException("Cannot serialize Settings to XML.", e); } // This removes the XML declaration written by MavenXpp3Writer @@ -214,20 +188,6 @@ private static void writeEffectiveSettings(Settings settings, XMLWriter writer) writer.writeMarkup(effectiveSettings); } - /** - * Apply some logic to clean the model before writing it. - * - * @param settings not null - */ - private static void cleanSettings(Settings settings) { - List profiles = settings.getProfiles(); - for (Profile profile : profiles) { - Properties properties = new SortedProperties(); - properties.putAll(profile.getProperties()); - profile.setProperties(properties); - } - } - /** * @return the current host name or unknown if error * @see InetAddress#getLocalHost() diff --git a/src/main/java/org/apache/maven/plugins/help/EvaluateMojo.java b/src/main/java/org/apache/maven/plugins/help/EvaluateMojo.java index aa2f2502..238ef6ee 100644 --- a/src/main/java/org/apache/maven/plugins/help/EvaluateMojo.java +++ b/src/main/java/org/apache/maven/plugins/help/EvaluateMojo.java @@ -19,44 +19,38 @@ package org.apache.maven.plugins.help; import java.io.File; -import java.io.FileInputStream; import java.io.IOException; -import java.io.InputStream; import java.io.StringWriter; +import java.net.URL; +import java.nio.file.Path; import java.util.List; -import java.util.Locale; import java.util.Map; -import java.util.Properties; +import java.util.Optional; import java.util.TreeMap; -import java.util.jar.JarEntry; -import java.util.jar.JarInputStream; +import java.util.zip.ZipFile; import com.thoughtworks.xstream.XStream; import com.thoughtworks.xstream.converters.MarshallingContext; import com.thoughtworks.xstream.converters.collections.PropertiesConverter; import com.thoughtworks.xstream.io.HierarchicalStreamWriter; import org.apache.commons.lang3.ClassUtils; -import org.apache.maven.lifecycle.internal.MojoDescriptorCreator; -import org.apache.maven.model.Dependency; -import org.apache.maven.model.Model; -import org.apache.maven.model.io.xpp3.MavenXpp3Writer; -import org.apache.maven.plugin.MojoExecution; -import org.apache.maven.plugin.MojoExecutionException; -import org.apache.maven.plugin.MojoFailureException; -import org.apache.maven.plugin.PluginParameterExpressionEvaluator; -import org.apache.maven.plugin.descriptor.MojoDescriptor; -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.settings.Settings; -import org.apache.maven.settings.io.xpp3.SettingsXpp3Writer; +import org.apache.maven.api.MojoExecution; +import org.apache.maven.api.Project; +import org.apache.maven.api.di.Inject; +import org.apache.maven.api.model.Model; +import org.apache.maven.api.plugin.MojoException; +import org.apache.maven.api.plugin.annotations.Mojo; +import org.apache.maven.api.plugin.annotations.Parameter; +import org.apache.maven.api.services.MavenException; +import org.apache.maven.api.services.Prompter; +import org.apache.maven.api.services.PrompterException; +import org.apache.maven.api.services.xml.ModelXmlFactory; +import org.apache.maven.api.services.xml.SettingsXmlFactory; +import org.apache.maven.api.services.xml.XmlWriterException; +import org.apache.maven.api.settings.Settings; +import org.apache.maven.plugin.PluginParameterExpressionEvaluatorV4; import org.codehaus.plexus.component.configurator.expression.ExpressionEvaluationException; -import org.codehaus.plexus.components.interactivity.InputHandler; import org.codehaus.plexus.util.StringUtils; -import org.eclipse.aether.RepositoryException; -import org.eclipse.aether.artifact.Artifact; -import org.eclipse.aether.artifact.DefaultArtifact; /** * Evaluates Maven expressions given by the user in an interactive mode. @@ -64,23 +58,8 @@ * @author Vincent Siveton * @since 2.1 */ -@Mojo(name = "evaluate", requiresProject = false) +@Mojo(name = "evaluate", projectRequired = false) public class EvaluateMojo extends AbstractHelpMojo { - // ---------------------------------------------------------------------- - // Mojo components - // ---------------------------------------------------------------------- - - /** - * Input handler, needed for command line handling. - */ - @Component - private InputHandler inputHandler; - - /** - * Component used to get mojo descriptors. - */ - @Component - private MojoDescriptorCreator mojoDescriptorCreator; // ---------------------------------------------------------------------- // Mojo parameters @@ -96,7 +75,7 @@ public class EvaluateMojo extends AbstractHelpMojo { * @since 3.0.0 */ @Parameter(property = "output") - private File output; + private Path output; /** * This options gives the option to output information in cases where the output has been suppressed by using @@ -130,30 +109,22 @@ public class EvaluateMojo extends AbstractHelpMojo { @Parameter(property = "expression") private String expression; + @Inject + private MojoExecution mojoExecution; + /** * The system settings for Maven. */ - @Parameter(defaultValue = "${settings}", readonly = true, required = true) + @Parameter(property = "session.settings") private Settings settings; - // ---------------------------------------------------------------------- - // Instance variables - // ---------------------------------------------------------------------- - - /** lazy loading evaluator variable */ - private PluginParameterExpressionEvaluator evaluator; - - /** lazy loading xstream variable */ - private XStream xstream; - // ---------------------------------------------------------------------- // Public methods // ---------------------------------------------------------------------- /** {@inheritDoc} */ - public void execute() throws MojoExecutionException, MojoFailureException { + public void execute() throws MojoException { if (expression == null && !settings.isInteractiveMode()) { - getLog().error("Maven is configured to NOT interact with the user for input. " + "This Mojo requires that 'interactiveMode' in your settings file is flag to 'true'."); return; @@ -174,15 +145,16 @@ public void execute() throws MojoExecutionException, MojoFailureException { getLog().info("Enter the Maven expression i.e. ${project.groupId} or 0 to exit?:"); try { - String userExpression = inputHandler.readLine(); - if (userExpression == null - || userExpression.toLowerCase(Locale.ENGLISH).equals("0")) { + Prompter prompter = session.getService(Prompter.class); + String userExpression = + prompter.prompt("Enter the Maven expression i.e. ${project.groupId} or 0 to exit?"); + if (userExpression == null || userExpression.equals("0")) { break; } handleResponse(userExpression, null); - } catch (IOException e) { - throw new MojoExecutionException("Unable to read from standard input.", e); + } catch (PrompterException e) { + throw new MojoException("Unable to read from standard input.", e); } } } else { @@ -206,45 +178,25 @@ private void validateParameters() { /** * @return a lazy loading evaluator object. - * @throws MojoFailureException if any reflection exceptions occur or missing components. + * @throws MojoException if any reflection exceptions occur or missing components. */ - private PluginParameterExpressionEvaluator getEvaluator() throws MojoFailureException { - if (evaluator == null) { - MojoDescriptor mojoDescriptor; - try { - mojoDescriptor = mojoDescriptorCreator.getMojoDescriptor("help:evaluate", session, project); - } catch (Exception e) { - throw new MojoFailureException("Failure while evaluating.", e); - } - MojoExecution mojoExecution = new MojoExecution(mojoDescriptor); - - MavenProject currentProject = session.getCurrentProject(); - // Maven 3: PluginParameterExpressionEvaluator gets the current project from the session: - // synchronize in case another thread wants to fetch the real current project in between - synchronized (session) { - session.setCurrentProject(project); - evaluator = new PluginParameterExpressionEvaluator(session, mojoExecution); - session.setCurrentProject(currentProject); - } - } - - return evaluator; + private PluginParameterExpressionEvaluatorV4 getEvaluator() throws MojoException { + return new PluginParameterExpressionEvaluatorV4(session, project, mojoExecution); } /** * @param expr the user expression asked. * @param output the file where to write the result, or null to print in standard output. - * @throws MojoExecutionException if any - * @throws MojoFailureException if any reflection exceptions occur or missing components. + * @throws MojoException if any reflection exceptions occur or missing components. */ - private void handleResponse(String expr, File output) throws MojoExecutionException, MojoFailureException { + private void handleResponse(String expr, Path output) throws MojoException { StringBuilder response = new StringBuilder(); Object obj; try { obj = getEvaluator().evaluate(expr); } catch (ExpressionEvaluationException e) { - throw new MojoExecutionException("Error when evaluating the Maven expression", e); + throw new MojoException("Error when evaluating the Maven expression", e); } if (obj != null && expr.equals(obj.toString())) { @@ -277,35 +229,30 @@ else if (obj instanceof String) { response.append(obj.toString()); } // handle specific objects - else if (obj instanceof File) { - File f = (File) obj; + else if (obj instanceof File f) { response.append(f.getAbsolutePath()); + } else if (obj instanceof Path p) { + response.append(p.toAbsolutePath().toString()); } // handle Maven pom object - else if (obj instanceof MavenProject) { - MavenProject projectAsked = (MavenProject) obj; - StringWriter sWriter = new StringWriter(); - MavenXpp3Writer pomWriter = new MavenXpp3Writer(); + else if (obj instanceof Project projectAsked) { try { - pomWriter.write(sWriter, projectAsked.getModel()); - } catch (IOException e) { - throw new MojoExecutionException("Error when writing pom", e); + StringWriter sWriter = new StringWriter(); + session.getService(ModelXmlFactory.class).write(projectAsked.getModel(), sWriter); + response.append(sWriter); + } catch (XmlWriterException e) { + throw new MojoException("Error when writing pom", e); } - - response.append(sWriter.toString()); } // handle Maven Settings object - else if (obj instanceof Settings) { - Settings settingsAsked = (Settings) obj; - StringWriter sWriter = new StringWriter(); - SettingsXpp3Writer settingsWriter = new SettingsXpp3Writer(); + else if (obj instanceof Settings settingsAsked) { try { - settingsWriter.write(sWriter, settingsAsked); - } catch (IOException e) { - throw new MojoExecutionException("Error when writing settings", e); + StringWriter sWriter = new StringWriter(); + session.getService(SettingsXmlFactory.class).write(settingsAsked, sWriter); + response.append(sWriter.toString()); + } catch (XmlWriterException e) { + throw new MojoException("Error when writing settings", e); } - - response.append(sWriter.toString()); } else { // others Maven objects response.append(toXML(expr, obj)); @@ -315,7 +262,7 @@ else if (obj instanceof Settings) { try { writeFile(output, response); } catch (IOException e) { - throw new MojoExecutionException("Cannot write evaluation of expression to output: " + output, e); + throw new MojoException("Cannot write evaluation of expression to output: " + output, e); } getLog().info("Result of evaluation written to: " + output); } else { @@ -339,8 +286,7 @@ private String toXML(String expr, Object obj) { XStream currentXStream = getXStream(); // beautify list - if (obj instanceof List) { - List list = (List) obj; + if (obj instanceof List list) { if (!list.isEmpty()) { Object elt = list.iterator().next(); @@ -362,31 +308,28 @@ private String toXML(String expr, Object obj) { * @return lazy loading xstream object. */ private XStream getXStream() { - if (xstream == null) { - xstream = new XStream(); - addAlias(xstream); - - // handle Properties a la Maven - xstream.registerConverter(new PropertiesConverter() { - /** {@inheritDoc} */ - @Override - public boolean canConvert(Class type) { - return Properties.class == type; - } + XStream xstream = new XStream(); + addAlias(xstream); + + // handle Properties a la Maven + xstream.registerConverter(new PropertiesConverter() { + /** {@inheritDoc} */ + @Override + public boolean canConvert(Class type) { + return Map.class.isAssignableFrom(type); + } - /** {@inheritDoc} */ - @Override - public void marshal(Object source, HierarchicalStreamWriter writer, MarshallingContext context) { - Properties properties = (Properties) source; - Map map = new TreeMap<>(properties); // sort - for (Map.Entry entry : map.entrySet()) { - writer.startNode(entry.getKey().toString()); - writer.setValue(entry.getValue().toString()); - writer.endNode(); - } + /** {@inheritDoc} */ + @Override + public void marshal(Object source, HierarchicalStreamWriter writer, MarshallingContext context) { + Map map = new TreeMap<>((Map) source); // sort + for (Map.Entry entry : map.entrySet()) { + writer.startNode(entry.getKey().toString()); + writer.setValue(entry.getValue() != null ? entry.getValue().toString() : null); + writer.endNode(); } - }); - } + } + }); return xstream; } @@ -396,9 +339,9 @@ public void marshal(Object source, HierarchicalStreamWriter writer, MarshallingC */ private void addAlias(XStream xstreamObject) { try { - addAlias(xstreamObject, getArtifactFile("maven-model"), "org.apache.maven.model"); - addAlias(xstreamObject, getArtifactFile("maven-settings"), "org.apache.maven.settings"); - } catch (MojoExecutionException | RepositoryException e) { + addAlias(xstreamObject, Model.class); + addAlias(xstreamObject, Settings.class); + } catch (MavenException e) { if (getLog().isDebugEnabled()) { getLog().debug(e.getMessage(), e); } @@ -407,90 +350,36 @@ private void addAlias(XStream xstreamObject) { // TODO need to handle specific Maven objects like DefaultArtifact? } - /** - * @param xstreamObject not null - * @param jarFile not null - * @param packageFilter a package name to filter. - */ - private void addAlias(XStream xstreamObject, File jarFile, String packageFilter) { - try (FileInputStream fis = new FileInputStream(jarFile); - JarInputStream jarStream = new JarInputStream(fis)) { - for (JarEntry jarEntry = jarStream.getNextJarEntry(); - jarEntry != null; - jarEntry = jarStream.getNextJarEntry()) { - if (jarEntry.getName().toLowerCase(Locale.ENGLISH).endsWith(".class")) { - String name = - jarEntry.getName().substring(0, jarEntry.getName().indexOf(".")); - name = name.replace("/", "\\."); - - if (name.contains(packageFilter) && !name.contains("$")) { - try { - Class clazz = ClassUtils.getClass(name); - String alias = StringUtils.lowercaseFirstLetter(clazz.getSimpleName()); - xstreamObject.alias(alias, clazz); - if (!clazz.equals(Model.class)) { - xstreamObject.omitField(clazz, "modelEncoding"); // unnecessary field - } - } catch (ClassNotFoundException e) { - getLog().error(e); - } + private void addAlias(XStream xstreamObject, Class clazz) { + String url = Optional.ofNullable( + clazz.getClassLoader().getResource(clazz.getName().replace('.', '/') + ".class")) + .map(URL::toExternalForm) + .orElse(null); + if (url != null && url.startsWith("jar:file:")) { + int exId = url.indexOf('!'); + String path = url.substring("jar:file:".length(), exId); + try (ZipFile zipFile = new ZipFile(path)) { + String prefix = clazz.getPackageName().replace('.', '/') + "/"; + List classes = zipFile.stream() + .map(e -> e.getName()) + .filter(e -> e.startsWith(prefix) + && e.endsWith(".class") + && !e.contains("$") + && !e.contains("package-info")) + .map(e -> e.substring(0, e.length() - ".class".length()).replace('/', '.')) + .toList(); + for (String c : classes) { + Class cl = ClassUtils.getClass(c); + String alias = StringUtils.lowercaseFirstLetter(cl.getSimpleName()); + xstreamObject.alias(alias, cl); + if ("TrackableBase".equals(cl.getSimpleName())) { + xstreamObject.omitField(cl, "locations"); } } - - jarStream.closeEntry(); - } - } catch (IOException e) { - if (getLog().isDebugEnabled()) { - getLog().debug("IOException: " + e.getMessage(), e); - } - } - } - - /** - * @return the org.apache.maven: artifactId artifact jar file for this current HelpPlugin pom. - * @throws MojoExecutionException if any - */ - private File getArtifactFile(String artifactId) throws MojoExecutionException, RepositoryException { - List 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 - result.txt diff --git a/src/test/resources/unit/evaluate/plugin-config-quiet-stdout.xml b/src/test/resources/unit/evaluate/plugin-config-quiet-stdout.xml deleted file mode 100644 index 0e9b41c8..00000000 --- a/src/test/resources/unit/evaluate/plugin-config-quiet-stdout.xml +++ /dev/null @@ -1,39 +0,0 @@ - - - - 4.0.0 - org.apache.maven.its.help - evaluate - jar - 1.0-SNAPSHOT - http://maven.apache.org - - - - org.apache.maven.plugins - maven-help-plugin - - true - project.groupId - - - - - diff --git a/src/test/java/org/apache/maven/plugins/help/ActiveProfilesMojoTest.java b/src/test/to-migrate/ActiveProfilesMojoTest.java similarity index 100% rename from src/test/java/org/apache/maven/plugins/help/ActiveProfilesMojoTest.java rename to src/test/to-migrate/ActiveProfilesMojoTest.java diff --git a/src/test/java/org/apache/maven/plugins/help/AllProfilesMojoTest.java b/src/test/to-migrate/AllProfilesMojoTest.java similarity index 100% rename from src/test/java/org/apache/maven/plugins/help/AllProfilesMojoTest.java rename to src/test/to-migrate/AllProfilesMojoTest.java diff --git a/src/test/java/org/apache/maven/plugins/help/DescribeMojoTest.java b/src/test/to-migrate/DescribeMojoTest.java similarity index 100% rename from src/test/java/org/apache/maven/plugins/help/DescribeMojoTest.java rename to src/test/to-migrate/DescribeMojoTest.java