From 3bd3bb5b79d40e52d30b6640ffd488ae9c51731b Mon Sep 17 00:00:00 2001 From: Jason van Zyl Date: Sun, 4 Mar 2007 00:48:55 +0000 Subject: [PATCH] o moving over the stuff required for the CLI here git-svn-id: https://svn.apache.org/repos/asf/maven/components/trunk@514296 13f79535-47bb-0310-9956-ffa450edef68 --- maven-embedder/LICENSE.txt | 202 +++++++ maven-embedder/NOTICE.txt | 11 + maven-embedder/README.txt | 23 + maven-embedder/pom.xml | 67 ++- maven-embedder/src/assemble/bin.xml | 66 +++ maven-embedder/src/bin/m2.conf | 6 + maven-embedder/src/bin/mvn | 165 ++++++ maven-embedder/src/bin/mvn.bat | 156 ++++++ maven-embedder/src/conf/settings.xml | 241 +++++++++ .../cli/AbstractConsoleDownloadMonitor.java | 129 +++++ .../maven/cli/BatchModeDownloadMonitor.java | 49 ++ .../java/org/apache/maven/cli/CLIManager.java | 295 +++++++++++ .../maven/cli/ConsoleDownloadMonitor.java | 66 +++ .../java/org/apache/maven/cli/MavenCli.java | 497 ++++++++++++++++++ .../AbstractConsoleDownloadMonitorTest.java | 129 +++++ .../cli/BatchModeDownloadMonitorTest.java | 38 ++ .../maven/cli/ConsoleDownloadMonitorTest.java | 39 ++ .../org/apache/maven/cli/MavenCliTest.java | 81 +++ 18 files changed, 2256 insertions(+), 4 deletions(-) create mode 100644 maven-embedder/LICENSE.txt create mode 100644 maven-embedder/NOTICE.txt create mode 100644 maven-embedder/README.txt create mode 100644 maven-embedder/src/assemble/bin.xml create mode 100644 maven-embedder/src/bin/m2.conf create mode 100755 maven-embedder/src/bin/mvn create mode 100644 maven-embedder/src/bin/mvn.bat create mode 100644 maven-embedder/src/conf/settings.xml create mode 100644 maven-embedder/src/main/java/org/apache/maven/cli/AbstractConsoleDownloadMonitor.java create mode 100644 maven-embedder/src/main/java/org/apache/maven/cli/BatchModeDownloadMonitor.java create mode 100644 maven-embedder/src/main/java/org/apache/maven/cli/CLIManager.java create mode 100644 maven-embedder/src/main/java/org/apache/maven/cli/ConsoleDownloadMonitor.java create mode 100644 maven-embedder/src/main/java/org/apache/maven/cli/MavenCli.java create mode 100644 maven-embedder/src/test/java/org/apache/maven/cli/AbstractConsoleDownloadMonitorTest.java create mode 100644 maven-embedder/src/test/java/org/apache/maven/cli/BatchModeDownloadMonitorTest.java create mode 100644 maven-embedder/src/test/java/org/apache/maven/cli/ConsoleDownloadMonitorTest.java create mode 100644 maven-embedder/src/test/java/org/apache/maven/cli/MavenCliTest.java diff --git a/maven-embedder/LICENSE.txt b/maven-embedder/LICENSE.txt new file mode 100644 index 0000000000..d645695673 --- /dev/null +++ b/maven-embedder/LICENSE.txt @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed 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. diff --git a/maven-embedder/NOTICE.txt b/maven-embedder/NOTICE.txt new file mode 100644 index 0000000000..d4dc4abfca --- /dev/null +++ b/maven-embedder/NOTICE.txt @@ -0,0 +1,11 @@ +This product includes software developed by +The Apache Software Foundation (http://www.apache.org/). + +This product includes software (Plexus and Classworlds) developed by +The Codehaus Foundation (http://www.codehaus.org/). + +This product includes software (JSCH) developed by +JCraft Inc. (http://www.jcraft.com/). + +This product includes software (JTidy) developed by +SourceForge (http://www.sourceforge.net/). diff --git a/maven-embedder/README.txt b/maven-embedder/README.txt new file mode 100644 index 0000000000..1ba98e0504 --- /dev/null +++ b/maven-embedder/README.txt @@ -0,0 +1,23 @@ +Installing Maven 2 +================== + +The following instructions show how to install Maven 2: + +1) Unpack the archive where you would like to store the binaries, eg: + tar zxvf maven-2.0.tar.gz +or + unzip maven-2.0.zip + +2) A directory called "maven-2.0" will be created. + +3) Add the bin directory to your PATH, eg: + export PATH=/usr/local/maven-2.0/bin:$PATH +or + set PATH="c:\program files\maven-2.0\bin";%PATH% + +4) Make sure JAVA_HOME is set to the location of your JDK + +5) Run "mvn --version" to verify that it is correctly installed. + +For more information, please see http://maven.apache.org + diff --git a/maven-embedder/pom.xml b/maven-embedder/pom.xml index 0841ad156c..15aeea028e 100644 --- a/maven-embedder/pom.xml +++ b/maven-embedder/pom.xml @@ -40,6 +40,7 @@ under the License. + + + maven-assembly-plugin + 2.1 + + + src/assemble/bin.xml + + maven-${version} + + + + install + + attached + + + + + + minijar-maven-plugin + org.codehaus.mojo + 1.0-SNAPSHOT + + + package + + ueberjar + + + false + + classworlds:classworlds + junit:junit + jmock:jmock + + + + + + @@ -63,14 +110,26 @@ under the License. org.codehaus.plexus plexus-container-default - - commons-lang - commons-lang - jdom jdom + + + commons-cli + commons-cli + 1.0 + + + commons-lang + commons-lang + + + commons-logging + commons-logging + + + diff --git a/maven-embedder/src/assemble/bin.xml b/maven-embedder/src/assemble/bin.xml new file mode 100644 index 0000000000..4766c0ad52 --- /dev/null +++ b/maven-embedder/src/assemble/bin.xml @@ -0,0 +1,66 @@ + + + + bin + + tar.gz + tar.bz2 + zip + + + + + README* + LICENSE* + NOTICE* + + + + src/bin + bin + + *.bat + *.conf + + dos + + + src/bin + bin + + m2 + mvn + + unix + 0755 + + + src/conf + conf + + + target + lib + + maven-embedder-*ueber.jar + + + + diff --git a/maven-embedder/src/bin/m2.conf b/maven-embedder/src/bin/m2.conf new file mode 100644 index 0000000000..78cafb06b8 --- /dev/null +++ b/maven-embedder/src/bin/m2.conf @@ -0,0 +1,6 @@ +main is org.apache.maven.cli.MavenCli from plexus.core + +set maven.home default ${user.home}/m2 + +[plexus.core] +load ${maven.home}/lib/*.jar diff --git a/maven-embedder/src/bin/mvn b/maven-embedder/src/bin/mvn new file mode 100755 index 0000000000..151894ff36 --- /dev/null +++ b/maven-embedder/src/bin/mvn @@ -0,0 +1,165 @@ +#!/bin/sh +# ---------------------------------------------------------------------------- +# Copyright 2001-2004 The Apache Software Foundation. +# +# Licensed 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. +# ---------------------------------------------------------------------------- + +# Copyright (c) 2001-2002 The Apache Software Foundation. All rights +# reserved. + +# ---------------------------------------------------------------------------- +# Maven2 Start Up Batch script +# +# Required ENV vars: +# ------------------ +# JAVA_HOME - location of a JDK home dir +# +# Optional ENV vars +# ----------------- +# M2_HOME - location of maven2's installed home dir +# MAVEN_OPTS - parameters passed to the Java VM when running Maven +# e.g. to debug Maven itself, use +# set MAVEN_OPTS=-Xdebug -Xnoagent -Djava.compiler=NONE -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +# ---------------------------------------------------------------------------- + + +QUOTED_ARGS="" +while [ "$1" != "" ] ; do + + QUOTED_ARGS="$QUOTED_ARGS \"$1\"" + shift + +done + +if [ -f /etc/mavenrc ] ; then + . /etc/mavenrc +fi + +if [ -f "$HOME/.mavenrc" ] ; then + . "$HOME/.mavenrc" +fi + +# OS specific support. $var _must_ be set to either true or false. +cygwin=false; +darwin=false; +mingw=false +case "`uname`" in + CYGWIN*) cygwin=true ;; + MINGW*) mingw=true;; + Darwin*) darwin=true + if [ -z "$JAVA_VERSION" ] ; then + JAVA_VERSION="CurrentJDK" + else + echo "Using Java version: $JAVA_VERSION" + fi + if [ -z "$JAVA_HOME" ] ; then + JAVA_HOME=/System/Library/Frameworks/JavaVM.framework/Versions/${JAVA_VERSION}/Home + fi + ;; +esac + +if [ -z "$JAVA_HOME" ] ; then + if [ -r /etc/gentoo-release ] ; then + JAVA_HOME=`java-config --jre-home` + fi +fi + +if [ -z "$M2_HOME" ] ; then + ## resolve links - $0 may be a link to maven's home + PRG="$0" + + # need this for relative symlinks + while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG="`dirname "$PRG"`/$link" + fi + done + + saveddir=`pwd` + + M2_HOME=`dirname "$PRG"`/.. + + # make it fully qualified + M2_HOME=`cd "$M2_HOME" && pwd` + + cd "$saveddir" + # echo Using m2 at $M2_HOME +fi + +# For Cygwin, ensure paths are in UNIX format before anything is touched +if $cygwin ; then + [ -n "$M2_HOME" ] && + M2_HOME=`cygpath --unix "$M2_HOME"` + [ -n "$JAVA_HOME" ] && + JAVA_HOME=`cygpath --unix "$JAVA_HOME"` + [ -n "$CLASSPATH" ] && + CLASSPATH=`cygpath --path --unix "$CLASSPATH"` +fi + +# For Migwn, ensure paths are in UNIX format before anything is touched +if $mingw ; then + [ -n "$M2_HOME" ] && + M2_HOME="`(cd "$M2_HOME"; pwd)`" + [ -n "$JAVA_HOME" ] && + JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" + # TODO classpath? +fi + +if [ -z "$JAVACMD" ] ; then + if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + else + JAVACMD=java + fi +fi + +if [ ! -x "$JAVACMD" ] ; then + echo "Error: JAVA_HOME is not defined correctly." + echo " We cannot execute $JAVACMD" + exit 1 +fi + +if [ -z "$JAVA_HOME" ] ; then + echo "Warning: JAVA_HOME environment variable is not set." +fi + +CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher + +# For Cygwin, switch paths to Windows format before running java +if $cygwin; then + [ -n "$M2_HOME" ] && + M2_HOME=`cygpath --path --windows "$M2_HOME"` + [ -n "$JAVA_HOME" ] && + JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` + [ -n "$HOME" ] && + HOME=`cygpath --path --windows "$HOME"` +fi + +exec "$JAVACMD" \ + $MAVEN_OPTS \ + -classpath "${M2_HOME}"/lib/maven-embedder-*.jar \ + "-Dclassworlds.conf=${M2_HOME}/bin/m2.conf" \ + "-Dmaven.home=${M2_HOME}" \ + ${CLASSWORLDS_LAUNCHER} $QUOTED_ARGS + + diff --git a/maven-embedder/src/bin/mvn.bat b/maven-embedder/src/bin/mvn.bat new file mode 100644 index 0000000000..39ed99ca09 --- /dev/null +++ b/maven-embedder/src/bin/mvn.bat @@ -0,0 +1,156 @@ +@REM ---------------------------------------------------------------------------- +@REM Copyright 2001-2004 The Apache Software Foundation. +@REM +@REM Licensed under the Apache License, Version 2.0 (the "License"); +@REM you may not use this file except in compliance with the License. +@REM You may obtain a copy of the License at +@REM +@REM http://www.apache.org/licenses/LICENSE-2.0 +@REM +@REM Unless required by applicable law or agreed to in writing, software +@REM distributed under the License is distributed on an "AS IS" BASIS, +@REM WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@REM See the License for the specific language governing permissions and +@REM limitations under the License. +@REM ---------------------------------------------------------------------------- +@REM + +@REM ---------------------------------------------------------------------------- +@REM Maven2 Start Up Batch script +@REM +@REM Required ENV vars: +@REM JAVA_HOME - location of a JDK home dir +@REM +@REM Optional ENV vars +@REM M2_HOME - location of maven2's installed home dir +@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands +@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending +@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven +@REM e.g. to debug Maven itself, use +@REM set MAVEN_OPTS=-Xdebug -Xnoagent -Djava.compiler=NONE -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +@REM ---------------------------------------------------------------------------- + +@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' +@echo off +@REM enable echoing my setting MAVEN_BATCH_ECHO to 'on' +@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% + +@REM Execute a user defined script before this one +if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" + +set ERROR_CODE=0 + +@REM set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" @setlocal + +@REM ==== START VALIDATION ==== +if not "%JAVA_HOME%" == "" goto OkJHome + +echo. +echo ERROR: JAVA_HOME not found in your environment. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation +echo. +goto error + +:OkJHome +if exist "%JAVA_HOME%\bin\java.exe" goto chkMHome + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory. +echo JAVA_HOME = %JAVA_HOME% +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation +echo. +goto error + +:chkMHome +if not "%M2_HOME%"=="" goto valMHome + +if "%OS%"=="Windows_NT" SET M2_HOME=%~dp0\.. +if not "%M2_HOME%"=="" goto valMHome + +echo. +echo ERROR: M2_HOME not found in your environment. +echo Please set the M2_HOME variable in your environment to match the +echo location of the Maven installation +echo. +goto error + +:valMHome +if exist "%M2_HOME%\bin\mvn.bat" goto init + +echo. +echo ERROR: M2_HOME is set to an invalid directory. +echo M2_HOME = %M2_HOME% +echo Please set the M2_HOME variable in your environment to match the +echo location of the Maven installation +echo. +goto error +@REM ==== END VALIDATION ==== + +:init +@REM Decide how to startup depending on the version of windows + +@REM -- Win98ME +if NOT "%OS%"=="Windows_NT" goto Win9xArg + +@REM -- 4NT shell +if "%eval[2+2]" == "4" goto 4NTArgs + +@REM -- Regular WinNT shell +set MAVEN_CMD_LINE_ARGS=%* +goto endInit + +@REM The 4NT Shell from jp software +:4NTArgs +set MAVEN_CMD_LINE_ARGS=%$ +goto endInit + +:Win9xArg +@REM Slurp the command line arguments. This loop allows for an unlimited number +@REM of agruments (up to the command line limit, anyway). +set MAVEN_CMD_LINE_ARGS= +:Win9xApp +if %1a==a goto endInit +set MAVEN_CMD_LINE_ARGS=%MAVEN_CMD_LINE_ARGS% %1 +shift +goto Win9xApp + +@REM Reaching here means variables are defined and arguments have been captured +:endInit +SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" + +@REM Start MAVEN2 +for %%i in ("%M2_HOME%"\core\boot\plexus-classworlds-*) do set CLASSWORLDS_JAR="%%i" +%MAVEN_JAVA_EXE% %MAVEN_OPTS% -classpath %CLASSWORLDS_JAR% "-Dclassworlds.conf=%M2_HOME%\bin\m2.conf" "-Dmaven.home=%M2_HOME%" org.codehaus.plexus.classworlds.launcher.Launcher %MAVEN_CMD_LINE_ARGS% +if ERRORLEVEL 1 goto error +goto end + +:error +if "%OS%"=="Windows_NT" @endlocal +set ERROR_CODE=1 + +:end +@REM set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" goto endNT + +@REM For old DOS remove the set variables from ENV - we assume they were not set +@REM before we started - at least we don't leave any baggage around +set MAVEN_JAVA_EXE= +set MAVEN_CMD_LINE_ARGS= +goto postExec + +:endNT +@endlocal + +:postExec +if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" +@REM pause the batch file if MAVEN_BATCH_PAUSE is set to 'on' +if "%MAVEN_BATCH_PAUSE%" == "on" pause + +if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% + +exit /B %ERROR_CODE% + + diff --git a/maven-embedder/src/conf/settings.xml b/maven-embedder/src/conf/settings.xml new file mode 100644 index 0000000000..84862915ee --- /dev/null +++ b/maven-embedder/src/conf/settings.xml @@ -0,0 +1,241 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/maven-embedder/src/main/java/org/apache/maven/cli/AbstractConsoleDownloadMonitor.java b/maven-embedder/src/main/java/org/apache/maven/cli/AbstractConsoleDownloadMonitor.java new file mode 100644 index 0000000000..beb7329ec1 --- /dev/null +++ b/maven-embedder/src/main/java/org/apache/maven/cli/AbstractConsoleDownloadMonitor.java @@ -0,0 +1,129 @@ +package org.apache.maven.cli; + +/* + * 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. + */ + +import org.apache.maven.MavenTransferListener; +import org.apache.maven.wagon.WagonConstants; +import org.apache.maven.wagon.events.TransferEvent; +import org.codehaus.plexus.logging.AbstractLogEnabled; +import org.codehaus.plexus.util.StringUtils; + +/** + * Abstract console download progress meter. + * + * @author Carlos Sanchez + * @version $Id$ + * @since 2.0.5 + */ +public abstract class AbstractConsoleDownloadMonitor + extends AbstractLogEnabled + implements MavenTransferListener +{ + private boolean showChecksumEvents = false; + + protected boolean showEvent( TransferEvent event ) + { + if ( event.getResource() == null ) + { + return true; + } + + String resource = event.getResource().getName(); + + if ( resource == null || resource.trim().length() == 0 ) + { + return true; + } + + if ( resource.endsWith( ".sha1" ) || resource.endsWith( ".md5" ) ) + { + return showChecksumEvents; + } + + return true; + } + + public void transferInitiated( TransferEvent transferEvent ) + { + if ( !showEvent( transferEvent ) ) + { + return; + } + + String message = transferEvent.getRequestType() == TransferEvent.REQUEST_PUT ? "Uploading" : "Downloading"; + + String url = transferEvent.getWagon().getRepository().getUrl(); + + // TODO: can't use getLogger() because this isn't currently instantiated as a component + System.out.println( message + ": " + url + "/" + transferEvent.getResource().getName() ); + } + + /** + * Do nothing + */ + public void transferStarted( TransferEvent transferEvent ) + { + // This space left intentionally blank + } + + /** + * Do nothing + */ + public void transferProgress( TransferEvent transferEvent, byte[] buffer, int length ) + { + // This space left intentionally blank + } + + public void transferCompleted( TransferEvent transferEvent ) + { + long contentLength = transferEvent.getResource().getContentLength(); + if ( contentLength != WagonConstants.UNKNOWN_LENGTH ) + { + String type = ( transferEvent.getRequestType() == TransferEvent.REQUEST_PUT ? "uploaded" : "downloaded" ); + String l = contentLength >= 1024 ? ( contentLength / 1024 ) + "K" : contentLength + "b"; + System.out.println( l + " " + type ); + } + } + + public void transferError( TransferEvent transferEvent ) + { + // TODO: can't use getLogger() because this isn't currently instantiated as a component + transferEvent.getException().printStackTrace(); + } + + /** + * Do nothing + */ + public void debug( String message ) + { + // TODO: can't use getLogger() because this isn't currently instantiated as a component +// getLogger().debug( message ); + } + + public boolean isShowChecksumEvents() + { + return showChecksumEvents; + } + + public void setShowChecksumEvents( boolean showChecksumEvents ) + { + this.showChecksumEvents = showChecksumEvents; + } +} diff --git a/maven-embedder/src/main/java/org/apache/maven/cli/BatchModeDownloadMonitor.java b/maven-embedder/src/main/java/org/apache/maven/cli/BatchModeDownloadMonitor.java new file mode 100644 index 0000000000..4c897fadac --- /dev/null +++ b/maven-embedder/src/main/java/org/apache/maven/cli/BatchModeDownloadMonitor.java @@ -0,0 +1,49 @@ +package org.apache.maven.cli; + +/* + * 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. + */ + +import org.apache.maven.wagon.events.TransferEvent; + +/** + * Console download progress meter. + * + * @author Brett Porter + * @version $Id$ + */ +public class BatchModeDownloadMonitor + extends AbstractConsoleDownloadMonitor +{ + public void transferInitiated( TransferEvent transferEvent ) + { + if ( !showEvent( transferEvent ) ) + { + return; + } + + String message = transferEvent.getRequestType() == TransferEvent.REQUEST_PUT ? "Uploading" : "Downloading"; + + String url = transferEvent.getWagon().getRepository().getUrl(); + + System.out.println( "url = " + url ); + + // TODO: can't use getLogger() because this isn't currently instantiated as a component + System.out.println( message + ": " + url + "/" + transferEvent.getResource().getName() ); + } +} diff --git a/maven-embedder/src/main/java/org/apache/maven/cli/CLIManager.java b/maven-embedder/src/main/java/org/apache/maven/cli/CLIManager.java new file mode 100644 index 0000000000..fd1401eac9 --- /dev/null +++ b/maven-embedder/src/main/java/org/apache/maven/cli/CLIManager.java @@ -0,0 +1,295 @@ +package org.apache.maven.cli; + +/* + * 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. + */ + +import org.apache.commons.cli.CommandLine; +import org.apache.commons.cli.CommandLineParser; +import org.apache.commons.cli.GnuParser; +import org.apache.commons.cli.HelpFormatter; +import org.apache.commons.cli.OptionBuilder; +import org.apache.commons.cli.Options; +import org.apache.commons.cli.ParseException; + +import java.util.ArrayList; +import java.util.List; + +/** + * @author Jason van Zyl + * @version $Revision: 381114 $ + */ +public class CLIManager +{ + public static final char ALTERNATE_POM_FILE = 'f'; + + public static final char BATCH_MODE = 'B'; + + public static final char SET_SYSTEM_PROPERTY = 'D'; + + public static final char OFFLINE = 'o'; + + public static final char REACTOR = 'r'; + + public static final char QUIET = 'q'; + + public static final char DEBUG = 'X'; + + public static final char ERRORS = 'e'; + + public static final char HELP = 'h'; + + public static final char VERSION = 'v'; + + public static final char NON_RECURSIVE = 'N'; + + public static final char UPDATE_SNAPSHOTS = 'U'; + + public static final char ACTIVATE_PROFILES = 'P'; + + public static final String FORCE_PLUGIN_UPDATES = "cpu"; + + public static final String FORCE_PLUGIN_UPDATES2 = "up"; + + public static final String SUPPRESS_PLUGIN_UPDATES = "npu"; + + public static final String SUPPRESS_PLUGIN_REGISTRY = "npr"; + + public static final String SUPRESS_SNAPSHOT_UPDATES = "nsu"; + + public static final char CHECKSUM_FAILURE_POLICY = 'C'; + + public static final char CHECKSUM_WARNING_POLICY = 'c'; + + public static final char ALTERNATE_USER_SETTINGS = 's'; + + public static final String FAIL_FAST = "ff"; + + public static final String FAIL_AT_END = "fae"; + + public static final String FAIL_NEVER = "fn"; + + private Options options; + + public CLIManager() + { + options = new Options(); + + options.addOption( OptionBuilder.withLongOpt( "file" ).hasArg().withDescription( + "Force the use of an alternate POM file." ).create( ALTERNATE_POM_FILE ) ); + + options.addOption( + OptionBuilder.withLongOpt( "define" ).hasArg().withDescription( "Define a system property" ).create( + SET_SYSTEM_PROPERTY ) ); + options.addOption( + OptionBuilder.withLongOpt( "offline" ).withDescription( "Work offline" ).create( OFFLINE ) ); + options.addOption( + OptionBuilder.withLongOpt( "help" ).withDescription( "Display help information" ).create( HELP ) ); + options.addOption( + OptionBuilder.withLongOpt( "version" ).withDescription( "Display version information" ).create( + VERSION ) ); + options.addOption( + OptionBuilder.withLongOpt( "quiet" ).withDescription( "Quiet output - only show errors" ).create( + QUIET ) ); + options.addOption( + OptionBuilder.withLongOpt( "debug" ).withDescription( "Produce execution debug output" ).create( + DEBUG ) ); + options.addOption( + OptionBuilder.withLongOpt( "errors" ).withDescription( "Produce execution error messages" ).create( + ERRORS ) ); + options.addOption( OptionBuilder.withLongOpt( "reactor" ).withDescription( + "Execute goals for project found in the reactor" ).create( REACTOR ) ); + options.addOption( OptionBuilder.withLongOpt( "non-recursive" ).withDescription( + "Do not recurse into sub-projects" ).create( NON_RECURSIVE ) ); + options.addOption( OptionBuilder.withLongOpt( "update-snapshots" ).withDescription( + "Forces a check for updated releases and snapshots on remote repositories" ).create( UPDATE_SNAPSHOTS ) ); + options.addOption( OptionBuilder.withLongOpt( "activate-profiles" ).withDescription( + "Comma-delimited list of profiles to activate" ).hasArg().create( ACTIVATE_PROFILES ) ); + + options.addOption( OptionBuilder.withLongOpt( "batch-mode" ).withDescription( + "Run in non-interactive (batch) mode" ).create( BATCH_MODE ) ); + + options.addOption( OptionBuilder.withLongOpt( "check-plugin-updates" ).withDescription( + "Force upToDate check for any relevant registered plugins" ).create( FORCE_PLUGIN_UPDATES ) ); + options.addOption( OptionBuilder.withLongOpt( "update-plugins" ).withDescription( + "Synonym for " + FORCE_PLUGIN_UPDATES ).create( FORCE_PLUGIN_UPDATES2 ) ); + options.addOption( OptionBuilder.withLongOpt( "no-plugin-updates" ).withDescription( + "Suppress upToDate check for any relevant registered plugins" ).create( SUPPRESS_PLUGIN_UPDATES ) ); + + options.addOption(OptionBuilder.withLongOpt("no-snapshot-updates") + .withDescription("Supress SNAPSHOT updates") + .create(SUPRESS_SNAPSHOT_UPDATES)); + + options.addOption( OptionBuilder.withLongOpt( "no-plugin-registry" ).withDescription( + "Don't use ~/.m2/plugin-registry.xml for plugin versions" ).create( SUPPRESS_PLUGIN_REGISTRY ) ); + + options.addOption( OptionBuilder.withLongOpt( "strict-checksums" ).withDescription( + "Fail the build if checksums don't match" ).create( CHECKSUM_FAILURE_POLICY ) ); + options.addOption( + OptionBuilder.withLongOpt( "lax-checksums" ).withDescription( "Warn if checksums don't match" ).create( + CHECKSUM_WARNING_POLICY ) ); + + options.addOption( OptionBuilder.withLongOpt( "settings" ) + .withDescription( "Alternate path for the user settings file" ).hasArg() + .create( ALTERNATE_USER_SETTINGS ) ); + + options.addOption( OptionBuilder.withLongOpt( "fail-fast" ).withDescription( + "Stop at first failure in reactorized builds" ).create( FAIL_FAST ) ); + + options.addOption( OptionBuilder.withLongOpt( "fail-at-end" ).withDescription( + "Only fail the build afterwards; allow all non-impacted builds to continue" ).create( FAIL_AT_END ) ); + + options.addOption( OptionBuilder.withLongOpt( "fail-never" ).withDescription( + "NEVER fail the build, regardless of project result" ).create( FAIL_NEVER ) ); + } + + public CommandLine parse( String[] args ) + throws ParseException + { + // We need to eat any quotes surrounding arguments... + String[] cleanArgs = cleanArgs( args ); + + CommandLineParser parser = new GnuParser(); + + return parser.parse( options, cleanArgs ); + } + + private String[] cleanArgs( String[] args ) + { + List cleaned = new ArrayList(); + + StringBuffer currentArg = null; + + for ( int i = 0; i < args.length; i++ ) + { + String arg = args[i]; + +// System.out.println( "Processing raw arg: " + arg ); + + boolean addedToBuffer = false; + + if ( arg.startsWith( "\"" ) ) + { + // if we're in the process of building up another arg, push it and start over. + // this is for the case: "-Dfoo=bar "-Dfoo2=bar two" (note the first unterminated quote) + if ( currentArg != null ) + { +// System.out.println( "Flushing last arg buffer: \'" + currentArg + "\' to cleaned list." ); + cleaned.add( currentArg.toString() ); + } + + // start building an argument here. + currentArg = new StringBuffer( arg.substring( 1 ) ); + addedToBuffer = true; + } + + // this has to be a separate "if" statement, to capture the case of: "-Dfoo=bar" + if ( arg.endsWith( "\"" ) ) + { + String cleanArgPart = arg.substring( 0, arg.length() - 1 ); + + // if we're building an argument, keep doing so. + if ( currentArg != null ) + { + // if this is the case of "-Dfoo=bar", then we need to adjust the buffer. + if ( addedToBuffer ) + { +// System.out.println( "Adjusting argument already appended to the arg buffer." ); + currentArg.setLength( currentArg.length() - 1 ); + } + // otherwise, we trim the trailing " and append to the buffer. + else + { +// System.out.println( "Appending arg part: \'" + cleanArgPart + "\' with preceding space to arg buffer." ); + // TODO: introducing a space here...not sure what else to do but collapse whitespace + currentArg.append( ' ' ).append( cleanArgPart ); + } + +// System.out.println( "Flushing completed arg buffer: \'" + currentArg + "\' to cleaned list." ); + + // we're done with this argument, so add it. + cleaned.add( currentArg.toString() ); + } + else + { +// System.out.println( "appending cleaned arg: \'" + cleanArgPart + "\' directly to cleaned list." ); + // this is a simple argument...just add it. + cleaned.add( cleanArgPart ); + } + +// System.out.println( "Clearing arg buffer." ); + // the currentArg MUST be finished when this completes. + currentArg = null; + continue; + } + + // if we haven't added this arg to the buffer, and we ARE building an argument + // buffer, then append it with a preceding space...again, not sure what else to + // do other than collapse whitespace. + // NOTE: The case of a trailing quote is handled by nullifying the arg buffer. + if ( !addedToBuffer ) + { + // append to the argument we're building, collapsing whitespace to a single space. + if ( currentArg != null ) + { +// System.out.println( "Append unquoted arg part: \'" + arg + "\' to arg buffer." ); + currentArg.append( ' ' ).append( arg ); + } + // this is a loner, just add it directly. + else + { +// System.out.println( "Append unquoted arg part: \'" + arg + "\' directly to cleaned list." ); + cleaned.add( arg ); + } + } + } + + // clean up. + if ( currentArg != null ) + { +// System.out.println( "Adding unterminated arg buffer: \'" + currentArg + "\' to cleaned list." ); + cleaned.add( currentArg.toString() ); + } + + int cleanedSz = cleaned.size(); + String[] cleanArgs = null; + + if ( cleanedSz == 0 ) + { + // if we didn't have any arguments to clean, simply pass the original array through + cleanArgs = args; + } + else + { +// System.out.println( "Cleaned argument list:\n" + cleaned ); + cleanArgs = (String[]) cleaned.toArray( new String[cleanedSz] ); + } + + return cleanArgs; + } + + + public void displayHelp() + { + System.out.println(); + + HelpFormatter formatter = new HelpFormatter(); + + formatter.printHelp( "mvn [options] [] []", "\nOptions:", options, "\n" ); + } +} diff --git a/maven-embedder/src/main/java/org/apache/maven/cli/ConsoleDownloadMonitor.java b/maven-embedder/src/main/java/org/apache/maven/cli/ConsoleDownloadMonitor.java new file mode 100644 index 0000000000..7c0cc39a42 --- /dev/null +++ b/maven-embedder/src/main/java/org/apache/maven/cli/ConsoleDownloadMonitor.java @@ -0,0 +1,66 @@ +package org.apache.maven.cli; + +/* + * 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. + */ + +import org.apache.maven.wagon.WagonConstants; +import org.apache.maven.wagon.events.TransferEvent; + +/** + * Console download progress meter. + * + * @author Brett Porter + * @version $Id$ + */ +public class ConsoleDownloadMonitor + extends AbstractConsoleDownloadMonitor +{ + private long complete; + + public void transferInitiated( TransferEvent transferEvent ) + { + super.transferInitiated( transferEvent ); + + complete = 0; + } + + public void transferProgress( TransferEvent transferEvent, byte[] buffer, int length ) + { + long total = transferEvent.getResource().getContentLength(); + complete += length; + + if ( !showEvent( transferEvent ) ) + { + return; + } + + // TODO [BP]: Sys.out may no longer be appropriate, but will \r work with getLogger()? + if ( total >= 1024 ) + { + System.out.print( + ( complete / 1024 ) + "/" + ( total == WagonConstants.UNKNOWN_LENGTH ? "?" : ( total / 1024 ) + "K" ) + + "\r" ); + } + else + { + System.out.print( complete + "/" + ( total == WagonConstants.UNKNOWN_LENGTH ? "?" : total + "b" ) + "\r" ); + } + } +} + diff --git a/maven-embedder/src/main/java/org/apache/maven/cli/MavenCli.java b/maven-embedder/src/main/java/org/apache/maven/cli/MavenCli.java new file mode 100644 index 0000000000..44cc33e563 --- /dev/null +++ b/maven-embedder/src/main/java/org/apache/maven/cli/MavenCli.java @@ -0,0 +1,497 @@ +package org.apache.maven.cli; + +/* + * 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. + */ + +import org.apache.commons.cli.CommandLine; +import org.apache.commons.cli.ParseException; +import org.apache.maven.MavenTransferListener; +import org.apache.maven.embedder.Configuration; +import org.apache.maven.embedder.DefaultConfiguration; +import org.apache.maven.embedder.MavenEmbedder; +import org.apache.maven.embedder.MavenEmbedderException; +import org.apache.maven.execution.DefaultMavenExecutionRequest; +import org.apache.maven.execution.MavenExecutionRequest; +import org.apache.maven.execution.MavenExecutionResult; +import org.codehaus.plexus.classworlds.ClassWorld; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.List; +import java.util.Properties; +import java.util.StringTokenizer; + +/** + * @author jason van zyl + * @version $Id$ + * @noinspection UseOfSystemOutOrSystemErr,ACCESS_STATIC_VIA_INSTANCE + */ +public class MavenCli +{ + public static final String LOCAL_REPO_PROPERTY = "maven.repo.local"; + + public static void main( String[] args ) + { + ClassWorld classWorld = new ClassWorld( "plexus.core", Thread.currentThread().getContextClassLoader() ); + + int result = main( args, classWorld ); + + System.exit( result ); + } + + /** @noinspection ConfusingMainMethod */ + public static int main( String[] args, + ClassWorld classWorld ) + { + // ---------------------------------------------------------------------- + // Setup the command line parser + // ---------------------------------------------------------------------- + + CLIManager cliManager = new CLIManager(); + + CommandLine commandLine; + try + { + commandLine = cliManager.parse( args ); + } + catch ( ParseException e ) + { + System.err.println( "Unable to parse command line options: " + e.getMessage() ); + cliManager.displayHelp(); + return 1; + } + + // TODO: maybe classworlds could handle this requirement... + if ( "1.4".compareTo( System.getProperty( "java.specification.version" ) ) > 0 ) + { + System.err.println( + "Sorry, but JDK 1.4 or above is required to execute Maven. You appear to be using " + "Java:" ); + System.err.println( + "java version \"" + System.getProperty( "java.version", "" ) + "\"" ); + System.err.println( System.getProperty( "java.runtime.name", "" ) + " (build " + + System.getProperty( "java.runtime.version", "" ) + ")" ); + System.err.println( System.getProperty( "java.vm.name", "" ) + " (build " + + System.getProperty( "java.vm.version", "" ) + ", " + + System.getProperty( "java.vm.info", "" ) + ")" ); + + return 1; + } + + boolean debug = commandLine.hasOption( CLIManager.DEBUG ); + + boolean quiet = !debug && commandLine.hasOption( CLIManager.QUIET ); + + boolean showErrors = debug || commandLine.hasOption( CLIManager.ERRORS ); + + if ( showErrors ) + { + System.out.println( "+ Error stacktraces are turned on." ); + } + + // ---------------------------------------------------------------------- + // Process particular command line options + // ---------------------------------------------------------------------- + + if ( commandLine.hasOption( CLIManager.HELP ) ) + { + cliManager.displayHelp(); + return 0; + } + + if ( commandLine.hasOption( CLIManager.VERSION ) ) + { + showVersion(); + + return 0; + } + else if ( debug ) + { + showVersion(); + } + + // ---------------------------------------------------------------------- + // Now that we have everything that we need we will fire up plexus and + // bring the maven component to life for use. + // ---------------------------------------------------------------------- + + boolean interactive = true; + + if ( commandLine.hasOption( CLIManager.BATCH_MODE ) ) + { + interactive = false; + } + + // This is now off by default and should just be removed as it causes too many problems and + // is turned off in 2.0.4. + boolean usePluginRegistry = false; + + if ( commandLine.hasOption( CLIManager.SUPPRESS_PLUGIN_REGISTRY ) ) + { + usePluginRegistry = false; + } + + boolean pluginUpdateOverride = false; + + if ( commandLine.hasOption( CLIManager.FORCE_PLUGIN_UPDATES ) || + commandLine.hasOption( CLIManager.FORCE_PLUGIN_UPDATES2 ) ) + { + pluginUpdateOverride = true; + } + else if ( commandLine.hasOption( CLIManager.SUPPRESS_PLUGIN_UPDATES ) ) + { + pluginUpdateOverride = false; + } + + boolean noSnapshotUpdates = false; + if ( commandLine.hasOption( CLIManager.SUPRESS_SNAPSHOT_UPDATES ) ) + { + noSnapshotUpdates = true; + } + + // ---------------------------------------------------------------------- + // + // ---------------------------------------------------------------------- + + List goals = commandLine.getArgList(); + + boolean recursive = true; + + String reactorFailureBehaviour = null; + + if ( commandLine.hasOption( CLIManager.NON_RECURSIVE ) ) + { + recursive = false; + } + + if ( commandLine.hasOption( CLIManager.FAIL_FAST ) ) + { + reactorFailureBehaviour = MavenExecutionRequest.REACTOR_FAIL_FAST; + } + else if ( commandLine.hasOption( CLIManager.FAIL_AT_END ) ) + { + reactorFailureBehaviour = MavenExecutionRequest.REACTOR_FAIL_AT_END; + } + else if ( commandLine.hasOption( CLIManager.FAIL_NEVER ) ) + { + reactorFailureBehaviour = MavenExecutionRequest.REACTOR_FAIL_NEVER; + } + + boolean offline = false; + + if ( commandLine.hasOption( CLIManager.OFFLINE ) ) + { + offline = true; + } + + boolean updateSnapshots = false; + + if ( commandLine.hasOption( CLIManager.UPDATE_SNAPSHOTS ) ) + { + updateSnapshots = true; + } + + String globalChecksumPolicy = null; + + if ( commandLine.hasOption( CLIManager.CHECKSUM_FAILURE_POLICY ) ) + { + // todo; log + System.out.println( "+ Enabling strict checksum verification on all artifact downloads." ); + + globalChecksumPolicy = MavenExecutionRequest.CHECKSUM_POLICY_FAIL; + } + else if ( commandLine.hasOption( CLIManager.CHECKSUM_WARNING_POLICY ) ) + { + // todo: log + System.out.println( "+ Disabling strict checksum verification on all artifact downloads." ); + + globalChecksumPolicy = MavenExecutionRequest.CHECKSUM_POLICY_WARN; + } + + File baseDirectory = new File( System.getProperty( "user.dir" ) ); + + // ---------------------------------------------------------------------- + // Profile Activation + // ---------------------------------------------------------------------- + + List activeProfiles = new ArrayList(); + + List inactiveProfiles = new ArrayList(); + + if ( commandLine.hasOption( CLIManager.ACTIVATE_PROFILES ) ) + { + String profilesLine = commandLine.getOptionValue( CLIManager.ACTIVATE_PROFILES ); + + StringTokenizer profileTokens = new StringTokenizer( profilesLine, "," ); + + while ( profileTokens.hasMoreTokens() ) + { + String profileAction = profileTokens.nextToken().trim(); + + if ( profileAction.startsWith( "-" ) ) + { + activeProfiles.add( profileAction.substring( 1 ) ); + } + else if ( profileAction.startsWith( "+" ) ) + { + inactiveProfiles.add( profileAction.substring( 1 ) ); + } + else + { + // TODO: deprecate this eventually! + activeProfiles.add( profileAction ); + } + } + } + + MavenTransferListener transferListener; + + if ( interactive ) + { + transferListener = new ConsoleDownloadMonitor(); + } + else + { + transferListener = new BatchModeDownloadMonitor(); + } + + transferListener.setShowChecksumEvents( false ); + + // This means to scan a directory structure for POMs and process them. + boolean useReactor = false; + + if ( commandLine.hasOption( CLIManager.REACTOR ) ) + { + useReactor = true; + } + + String alternatePomFile = null; + if ( commandLine.hasOption( CLIManager.ALTERNATE_POM_FILE ) ) + { + alternatePomFile = commandLine.getOptionValue( CLIManager.ALTERNATE_POM_FILE ); + } + + int loggingLevel; + + if ( debug ) + { + loggingLevel = MavenExecutionRequest.LOGGING_LEVEL_DEBUG; + } + else if ( quiet ) + { + // TODO: we need to do some more work here. Some plugins use sys out or log errors at info level. + // Ideally, we could use Warn across the board + loggingLevel = MavenExecutionRequest.LOGGING_LEVEL_ERROR; + // TODO:Additionally, we can't change the mojo level because the component key includes the version and it isn't known ahead of time. This seems worth changing. + } + else + { + loggingLevel = MavenExecutionRequest.LOGGING_LEVEL_INFO; + } + + Properties executionProperties = getExecutionProperties( commandLine ); + + MavenExecutionRequest request = new DefaultMavenExecutionRequest() + .setBaseDirectory( baseDirectory ) + .setGoals( goals ) + .setProperties( executionProperties ) // optional + .setReactorFailureBehavior( reactorFailureBehaviour ) // default: fail fast + .setRecursive( recursive ) // default: true + .setUseReactor( useReactor ) // default: false + .setPomFile( alternatePomFile ) // optional + .setShowErrors( showErrors ) // default: false + .setInteractiveMode( interactive ) // default: false + .setUsePluginRegistry( usePluginRegistry ) + .setOffline( offline ) // default: false + .setUsePluginUpdateOverride( pluginUpdateOverride ) + .addActiveProfiles( activeProfiles ) // optional + .addInactiveProfiles( inactiveProfiles ) // optional + .setLoggingLevel( loggingLevel ) // default: info + .setTransferListener( transferListener ) // default: batch mode which goes along with interactive + .setUpdateSnapshots( updateSnapshots ) // default: false + .setNoSnapshotUpdates( noSnapshotUpdates ) // default: false + .setGlobalChecksumPolicy( globalChecksumPolicy ); // default: warn + + File userSettingsFile; + + if ( commandLine.getOptionValue( CLIManager.ALTERNATE_USER_SETTINGS ) != null ) + { + userSettingsFile = new File( commandLine.getOptionValue( CLIManager.ALTERNATE_USER_SETTINGS ) ); + } + else + { + userSettingsFile = MavenEmbedder.DEFAULT_USER_SETTINGS_FILE; + } + + Configuration configuration = new DefaultConfiguration() + .setUserSettingsFile( userSettingsFile ) + .setGlobalSettingsFile( MavenEmbedder.DEFAULT_GLOBAL_SETTINGS_FILE ) + .setClassWorld( classWorld ); + + String localRepoProperty = executionProperties.getProperty( LOCAL_REPO_PROPERTY ); + + if ( localRepoProperty != null ) + { + configuration.setLocalRepository( new File( localRepoProperty ) ); + } + + MavenEmbedder mavenEmbedder; + + try + { + mavenEmbedder = new MavenEmbedder( configuration ); + } + catch ( MavenEmbedderException e ) + { + showFatalError( "Unable to start the embedded plexus container", e, showErrors ); + + return 1; + } + + + MavenExecutionResult result = mavenEmbedder.execute( request ); + + if ( result.hasExceptions() ) + { + showFatalError( "Unable to configure the Maven application", (Exception) result.getExceptions().get( 0 ), showErrors ); + + return 1; + } + + return 0; + } + + private static void showFatalError( String message, + Exception e, + boolean show ) + { + System.err.println( "FATAL ERROR: " + message ); + if ( show ) + { + System.err.println( "Error stacktrace:" ); + + e.printStackTrace(); + } + else + { + System.err.println( "For more information, run with the -e flag" ); + } + } + + private static void showError( String message, + Exception e, + boolean show ) + { + System.err.println( message ); + if ( show ) + { + System.err.println( "Error stacktrace:" ); + + e.printStackTrace(); + } + } + + private static void showVersion() + { + InputStream resourceAsStream; + try + { + Properties properties = new Properties(); + resourceAsStream = MavenCli.class.getClassLoader().getResourceAsStream( + "META-INF/maven/org.apache.maven/maven-core/pom.properties" ); + properties.load( resourceAsStream ); + + if ( properties.getProperty( "builtOn" ) != null ) + { + System.out.println( "Maven version: " + properties.getProperty( "version", "unknown" ) + " built on " + + properties.getProperty( "builtOn" ) ); + } + else + { + System.out.println( "Maven version: " + properties.getProperty( "version", "unknown" ) ); + } + } + catch ( IOException e ) + { + System.err.println( "Unable determine version from JAR file: " + e.getMessage() ); + } + } + + // ---------------------------------------------------------------------- + // System properties handling + // ---------------------------------------------------------------------- + + private static Properties getExecutionProperties( CommandLine commandLine ) + { + Properties executionProperties = new Properties(); + + // ---------------------------------------------------------------------- + // Options that are set on the command line become system properties + // and therefore are set in the session properties. System properties + // are most dominant. + // ---------------------------------------------------------------------- + + if ( commandLine.hasOption( CLIManager.SET_SYSTEM_PROPERTY ) ) + { + String[] defStrs = commandLine.getOptionValues( CLIManager.SET_SYSTEM_PROPERTY ); + + for ( int i = 0; i < defStrs.length; ++i ) + { + setCliProperty( defStrs[i], executionProperties ); + } + } + + executionProperties.putAll( System.getProperties() ); + + return executionProperties; + } + + private static void setCliProperty( String property, + Properties executionProperties ) + { + String name; + + String value; + + int i = property.indexOf( "=" ); + + if ( i <= 0 ) + { + name = property.trim(); + + value = "true"; + } + else + { + name = property.substring( 0, i ).trim(); + + value = property.substring( i + 1 ).trim(); + } + + executionProperties.setProperty( name, value ); + + // ---------------------------------------------------------------------- + // I'm leaving the setting of system properties here as not to break + // the SystemPropertyProfileActivator. This won't harm embedding. jvz. + // ---------------------------------------------------------------------- + + System.setProperty( name, value ); + } +} diff --git a/maven-embedder/src/test/java/org/apache/maven/cli/AbstractConsoleDownloadMonitorTest.java b/maven-embedder/src/test/java/org/apache/maven/cli/AbstractConsoleDownloadMonitorTest.java new file mode 100644 index 0000000000..a1df559ae9 --- /dev/null +++ b/maven-embedder/src/test/java/org/apache/maven/cli/AbstractConsoleDownloadMonitorTest.java @@ -0,0 +1,129 @@ +package org.apache.maven.cli; + +/* + * 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. + */ + +import junit.framework.TestCase; +import org.apache.maven.MavenTransferListener; +import org.apache.maven.wagon.ConnectionException; +import org.apache.maven.wagon.authentication.AuthenticationException; +import org.apache.maven.wagon.events.TransferEvent; +import org.apache.maven.wagon.providers.file.FileWagon; +import org.apache.maven.wagon.repository.Repository; +import org.apache.maven.wagon.resource.Resource; + +import java.io.File; + +/** + * Test for {@link AbstractConsoleDownloadMonitor} + * + * @author Carlos Sanchez + * @version $Id$ + */ +public abstract class AbstractConsoleDownloadMonitorTest + extends TestCase +{ + private MavenTransferListener monitor; + + public AbstractConsoleDownloadMonitorTest() + { + super(); + } + + public void setMonitor( MavenTransferListener monitor ) + { + this.monitor = monitor; + } + + public MavenTransferListener getMonitor() + { + return monitor; + } + + public void testTransferInitiated() + throws Exception + { + monitor.transferInitiated( new TransferEventMock() ); + } + + public void testTransferStarted() + throws Exception + { + monitor.transferStarted( new TransferEventMock() ); + } + + public void testTransferProgress() + throws Exception + { + byte[] buffer = new byte[1000]; + monitor.transferProgress( new TransferEventMock(), buffer, 1000 ); + } + + public void testTransferCompleted() + throws Exception + { + monitor.transferCompleted( new TransferEventMock() ); + } + + public void testTransferError() + throws Exception + { + monitor.transferError( new TransferEventMock( new RuntimeException() ) ); + } + + public void testDebug() + throws Exception + { + monitor.debug( "msg" ); + } + + private class RepositoryMock + extends Repository + { + public RepositoryMock() + { + super(); + setId("mock"); + File basedir = new File(System.getProperty( "basedir", "." )); + setUrl( "file://" + basedir.getAbsolutePath() + "/target/" ); + } + } + + private class TransferEventMock + extends TransferEvent + { + public TransferEventMock() + throws ConnectionException, AuthenticationException + { + super( new FileWagon(), new RepositoryMock(), new Resource(), TransferEvent.TRANSFER_INITIATED, TransferEvent.REQUEST_GET ); + getResource().setContentLength( 100000 ); + getWagon().setRepository( new RepositoryMock() ); + getWagon().connect(); + } + + public TransferEventMock( Exception exception ) + throws ConnectionException, AuthenticationException + { + super( new FileWagon(), new RepositoryMock(), new Resource(), exception, TransferEvent.REQUEST_GET ); + getResource().setContentLength( 100000 ); + getWagon().setRepository( new RepositoryMock() ); + getWagon().connect(); + } + } +} \ No newline at end of file diff --git a/maven-embedder/src/test/java/org/apache/maven/cli/BatchModeDownloadMonitorTest.java b/maven-embedder/src/test/java/org/apache/maven/cli/BatchModeDownloadMonitorTest.java new file mode 100644 index 0000000000..80b85f5c9a --- /dev/null +++ b/maven-embedder/src/test/java/org/apache/maven/cli/BatchModeDownloadMonitorTest.java @@ -0,0 +1,38 @@ +package org.apache.maven.cli; + +/* + * 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. + */ + +/** + * Test for {@link BatchModeDownloadMonitor} + * + * @author Carlos Sanchez + * @version $Id$ + */ +public class BatchModeDownloadMonitorTest + extends AbstractConsoleDownloadMonitorTest +{ + protected void setUp() + throws Exception + { + super.setMonitor( new BatchModeDownloadMonitor() ); + + super.setUp(); + } +} diff --git a/maven-embedder/src/test/java/org/apache/maven/cli/ConsoleDownloadMonitorTest.java b/maven-embedder/src/test/java/org/apache/maven/cli/ConsoleDownloadMonitorTest.java new file mode 100644 index 0000000000..3e18731900 --- /dev/null +++ b/maven-embedder/src/test/java/org/apache/maven/cli/ConsoleDownloadMonitorTest.java @@ -0,0 +1,39 @@ +package org.apache.maven.cli; + +/* + * 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. + */ + +/** + * Test for {@link ConsoleDownloadMonitor} + * + * @author Carlos Sanchez + * @version $Id$ + */ +public class ConsoleDownloadMonitorTest + extends AbstractConsoleDownloadMonitorTest +{ + + protected void setUp() + throws Exception + { + super.setMonitor( new ConsoleDownloadMonitor() ); + + super.setUp(); + } +} diff --git a/maven-embedder/src/test/java/org/apache/maven/cli/MavenCliTest.java b/maven-embedder/src/test/java/org/apache/maven/cli/MavenCliTest.java new file mode 100644 index 0000000000..b5be6c8744 --- /dev/null +++ b/maven-embedder/src/test/java/org/apache/maven/cli/MavenCliTest.java @@ -0,0 +1,81 @@ +package org.apache.maven.cli; + +/* + * 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. + */ + +import junit.framework.TestCase; +import org.codehaus.plexus.classworlds.ClassWorld; +import org.codehaus.plexus.util.StringOutputStream; + +import java.io.OutputStream; +import java.io.PrintStream; + +/** + * Test method for 'org.apache.maven.cli.MavenCli.main(String[], ClassWorld)' + * + * @author Vincent Siveton + * @version $Id$ + */ +public class MavenCliTest + extends TestCase +{ + /** + * Test that JDK 1.4 or above is required to execute MavenCli + * + * @throws Exception + */ + public void testMain() + throws Exception + { + ClassWorld classWorld = new ClassWorld(); + + PrintStream oldErr = System.err; + PrintStream oldOut = System.out; + + OutputStream errOS = new StringOutputStream(); + PrintStream err = new PrintStream( errOS ); + System.setErr( err ); + OutputStream outOS = new StringOutputStream(); + PrintStream out = new PrintStream( outOS ); + System.setOut( out ); + + try + { + System.setProperty( "java.specification.version", "1.0" ); + assertEquals( 1, MavenCli.main( new String[] { "-h" }, classWorld ) ); + System.setProperty( "java.specification.version", "1.1" ); + assertEquals( 1, MavenCli.main( new String[] { "-h" }, classWorld ) ); + System.setProperty( "java.specification.version", "1.2" ); + assertEquals( 1, MavenCli.main( new String[] { "-h" }, classWorld ) ); + System.setProperty( "java.specification.version", "1.3" ); + assertEquals( 1, MavenCli.main( new String[] { "-h" }, classWorld ) ); + System.setProperty( "java.specification.version", "1.4" ); + assertEquals( 0, MavenCli.main( new String[] { "-h" }, classWorld ) ); + System.setProperty( "java.specification.version", "1.5" ); + assertEquals( 0, MavenCli.main( new String[] { "-h" }, classWorld ) ); + System.setProperty( "java.specification.version", "1.6" ); + assertEquals( 0, MavenCli.main( new String[] { "-h" }, classWorld ) ); + } + finally + { + System.setErr( oldErr ); + System.setErr( oldOut ); + } + } +}