You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

Main.java 18 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466
  1. /*
  2. * The Apache Software License, Version 1.1
  3. *
  4. * Copyright (c) 1999, 2000 The Apache Software Foundation. All rights
  5. * reserved.
  6. *
  7. * Redistribution and use in source and binary forms, with or without
  8. * modification, are permitted provided that the following conditions
  9. * are met:
  10. *
  11. * 1. Redistributions of source code must retain the above copyright
  12. * notice, this list of conditions and the following disclaimer.
  13. *
  14. * 2. Redistributions in binary form must reproduce the above copyright
  15. * notice, this list of conditions and the following disclaimer in
  16. * the documentation and/or other materials provided with the
  17. * distribution.
  18. *
  19. * 3. The end-user documentation included with the redistribution, if
  20. * any, must include the following acknowlegement:
  21. * "This product includes software developed by the
  22. * Apache Software Foundation (http://www.apache.org/)."
  23. * Alternately, this acknowlegement may appear in the software itself,
  24. * if and wherever such third-party acknowlegements normally appear.
  25. *
  26. * 4. The names "The Jakarta Project", "Tomcat", and "Apache Software
  27. * Foundation" must not be used to endorse or promote products derived
  28. * from this software without prior written permission. For written
  29. * permission, please contact apache@apache.org.
  30. *
  31. * 5. Products derived from this software may not be called "Apache"
  32. * nor may "Apache" appear in their names without prior written
  33. * permission of the Apache Group.
  34. *
  35. * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
  36. * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  37. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  38. * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
  39. * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  40. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  41. * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
  42. * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  43. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  44. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
  45. * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  46. * SUCH DAMAGE.
  47. * ====================================================================
  48. *
  49. * This software consists of voluntary contributions made by many
  50. * individuals on behalf of the Apache Software Foundation. For more
  51. * information on the Apache Software Foundation, please see
  52. * <http://www.apache.org/>.
  53. */
  54. package org.apache.tools.ant;
  55. import java.io.*;
  56. import java.util.*;
  57. /**
  58. * Command line entry point into Ant. This class is entered via the
  59. * cannonical `public static void main` entry point and reads the
  60. * command line arguments. It then assembles and executes an Ant
  61. * project.
  62. * <p>
  63. * If you integrating Ant into some other tool, this is not the class
  64. * to use as an entry point. Please see the source code of this
  65. * class to see how it manipulates the Ant project classes.
  66. *
  67. * @author duncan@x180.com
  68. */
  69. public class Main {
  70. /** Our current message output status. Follows Project.MSG_XXX */
  71. private int msgOutputLevel = Project.MSG_INFO;
  72. /** File that we are using for configuration */
  73. private File buildFile = new File("build.xml");
  74. /** Stream that we are using for logging */
  75. private PrintStream out = System.out;
  76. /** The build targets */
  77. private Vector targets = new Vector(5);
  78. /** Set of properties that can be used by tasks */
  79. private Properties definedProps = new Properties();
  80. /** Names of classes to add as listeners to project */
  81. private Vector listeners = new Vector(5);
  82. /**
  83. * The Ant logger class. There may be only one logger. It will have the
  84. * right to use the 'out' PrintStream. The class must implements the BuildLogger
  85. * interface
  86. */
  87. private String loggerClassname = null;
  88. /**
  89. * Indicates whether output to the log is to be unadorned.
  90. */
  91. private boolean emacsMode = false;
  92. /**
  93. * Indicates if this ant should be run.
  94. */
  95. private boolean readyToRun = false;
  96. /**
  97. * Indicates we should only parse and display the project help information
  98. */
  99. private boolean projectHelp = false;
  100. /**
  101. * Command line entry point. This method kicks off the building
  102. * of a project object and executes a build using either a given
  103. * target or the default target.
  104. *
  105. * @param args Command line args.
  106. */
  107. public static void main(String[] args) {
  108. try {
  109. new Main(args).runBuild();
  110. System.exit(0);
  111. }
  112. catch(Throwable exc) {
  113. System.exit(1);
  114. }
  115. }
  116. protected Main(String[] args) throws BuildException {
  117. // cycle through given args
  118. for (int i = 0; i < args.length; i++) {
  119. String arg = args[i];
  120. if (arg.equals("-help")) {
  121. printUsage();
  122. return;
  123. } else if (arg.equals("-version")) {
  124. printVersion();
  125. return;
  126. } else if (arg.equals("-quiet") || arg.equals("-q")) {
  127. msgOutputLevel = Project.MSG_WARN;
  128. } else if (arg.equals("-verbose") || arg.equals("-v")) {
  129. printVersion();
  130. msgOutputLevel = Project.MSG_VERBOSE;
  131. } else if (arg.equals("-logfile") || arg.equals("-l")) {
  132. try {
  133. File logFile = new File(args[i+1]);
  134. i++;
  135. out = new PrintStream(new FileOutputStream(logFile));
  136. System.setOut(out);
  137. System.setErr(out);
  138. } catch (IOException ioe) {
  139. String msg = "Cannot write on the specified log file. " +
  140. "Make sure the path exists and you have write permissions.";
  141. System.out.println(msg);
  142. return;
  143. } catch (ArrayIndexOutOfBoundsException aioobe) {
  144. String msg = "You must specify a log file when " +
  145. "using the -log argument";
  146. System.out.println(msg);
  147. return;
  148. }
  149. } else if (arg.equals("-buildfile") || arg.equals("-file") || arg.equals("-f")) {
  150. try {
  151. buildFile = new File(args[i+1]);
  152. i++;
  153. } catch (ArrayIndexOutOfBoundsException aioobe) {
  154. String msg = "You must specify a buildfile when " +
  155. "using the -buildfile argument";
  156. System.out.println(msg);
  157. return;
  158. }
  159. } else if (arg.equals("-listener")) {
  160. try {
  161. listeners.addElement(args[i+1]);
  162. i++;
  163. } catch (ArrayIndexOutOfBoundsException aioobe) {
  164. String msg = "You must specify a classname when " +
  165. "using the -listener argument";
  166. System.out.println(msg);
  167. return;
  168. }
  169. } else if (arg.startsWith("-D")) {
  170. /* Interestingly enough, we get to here when a user
  171. * uses -Dname=value. However, in some cases, the JDK
  172. * goes ahead * and parses this out to args
  173. * {"-Dname", "value"}
  174. * so instead of parsing on "=", we just make the "-D"
  175. * characters go away and skip one argument forward.
  176. *
  177. * I don't know how to predict when the JDK is going
  178. * to help or not, so we simply look for the equals sign.
  179. */
  180. String name = arg.substring(2, arg.length());
  181. String value = null;
  182. int posEq = name.indexOf("=");
  183. if (posEq > 0) {
  184. value = name.substring(posEq+1);
  185. name = name.substring(0, posEq);
  186. } else if (i < args.length)
  187. value = args[++i];
  188. definedProps.put(name, value);
  189. } else if (arg.equals("-logger")) {
  190. if (loggerClassname != null) {
  191. System.out.println("Only one logger class may be specified.");
  192. return;
  193. }
  194. loggerClassname = args[++i];
  195. } else if (arg.equals("-emacs")) {
  196. emacsMode = true;
  197. } else if (arg.equals("-projecthelp")) {
  198. // set the flag to display the targets and quit
  199. projectHelp = true;
  200. } else if (arg.startsWith("-")) {
  201. // we don't have any more args to recognize!
  202. String msg = "Unknown arg: " + arg;
  203. System.out.println(msg);
  204. printUsage();
  205. return;
  206. } else {
  207. // if it's no other arg, it may be the target
  208. targets.addElement(arg);
  209. }
  210. }
  211. // make sure buildfile exists
  212. if (!buildFile.exists()) {
  213. System.out.println("Buildfile: " + buildFile + " does not exist!");
  214. return;
  215. }
  216. // make sure it's not a directory (this falls into the ultra
  217. // paranoid lets check everything catagory
  218. if (buildFile.isDirectory()) {
  219. System.out.println("What? Buildfile: " + buildFile + " is a dir!");
  220. return;
  221. }
  222. readyToRun = true;
  223. }
  224. /**
  225. * Executes the build.
  226. */
  227. private void runBuild() throws BuildException {
  228. if (!readyToRun) {
  229. return;
  230. }
  231. // track when we started
  232. if (msgOutputLevel >= Project.MSG_INFO) {
  233. System.out.println("Buildfile: " + buildFile);
  234. }
  235. Project project = new Project();
  236. Throwable error = null;
  237. try {
  238. addBuildListeners(project);
  239. project.fireBuildStarted();
  240. project.init();
  241. // set user-define properties
  242. Enumeration e = definedProps.keys();
  243. while (e.hasMoreElements()) {
  244. String arg = (String)e.nextElement();
  245. String value = (String)definedProps.get(arg);
  246. project.setUserProperty(arg, value);
  247. }
  248. project.setUserProperty( "ant.file" , buildFile.getAbsolutePath() );
  249. // first use the ProjectHelper to create the project object
  250. // from the given build file.
  251. try {
  252. Class.forName("javax.xml.parsers.SAXParserFactory");
  253. ProjectHelper.configureProject(project, buildFile);
  254. } catch (NoClassDefFoundError ncdfe) {
  255. throw new BuildException("No JAXP compliant XML parser found. See http://java.sun.com/xml for the\nreference implementation.", ncdfe);
  256. } catch (ClassNotFoundException cnfe) {
  257. throw new BuildException("No JAXP compliant XML parser found. See http://java.sun.com/xml for the\nreference implementation.", cnfe);
  258. } catch (NullPointerException npe) {
  259. throw new BuildException("No JAXP compliant XML parser found. See http://java.sun.com/xml for the\nreference implementation.", npe);
  260. }
  261. // make sure that we have a target to execute
  262. if (targets.size() == 0) {
  263. targets.addElement(project.getDefaultTarget());
  264. }
  265. if (projectHelp) {
  266. printTargets(project);
  267. } else {
  268. // actually do some work
  269. project.executeTargets(targets);
  270. }
  271. }
  272. catch(RuntimeException exc) {
  273. error = exc;
  274. throw exc;
  275. }
  276. catch(Error err) {
  277. error = err;
  278. throw err;
  279. }
  280. finally {
  281. project.fireBuildFinished(error);
  282. }
  283. }
  284. protected void addBuildListeners(Project project) {
  285. // Add the default listener
  286. project.addBuildListener(createLogger());
  287. for (int i = 0; i < listeners.size(); i++) {
  288. String className = (String) listeners.elementAt(i);
  289. try {
  290. BuildListener listener =
  291. (BuildListener) Class.forName(className).newInstance();
  292. project.addBuildListener(listener);
  293. }
  294. catch(Exception exc) {
  295. throw new BuildException("Unable to instantiate listener " + className, exc);
  296. }
  297. }
  298. }
  299. /**
  300. * Creates the default build logger for sending build events to the ant log.
  301. */
  302. private BuildLogger createLogger() {
  303. BuildLogger logger = null;
  304. if (loggerClassname != null) {
  305. try {
  306. logger = (BuildLogger)(Class.forName(loggerClassname).newInstance());
  307. }
  308. catch (ClassCastException e) {
  309. System.err.println("The specified logger class " + loggerClassname +
  310. " does not implement the BuildLogger interface");
  311. throw new RuntimeException();
  312. }
  313. catch (Exception e) {
  314. System.err.println("Unable to instantiate specified logger class " +
  315. loggerClassname + " : " + e.getClass().getName());
  316. throw new RuntimeException();
  317. }
  318. }
  319. else {
  320. logger = new DefaultLogger();
  321. }
  322. logger.setMessageOutputLevel(msgOutputLevel);
  323. logger.setOutputPrintStream(out);
  324. logger.setEmacsMode(emacsMode);
  325. return logger;
  326. }
  327. /**
  328. * Prints the usage of how to use this class to System.out
  329. */
  330. private static void printUsage() {
  331. String lSep = System.getProperty("line.separator");
  332. StringBuffer msg = new StringBuffer();
  333. msg.append("ant [options] [target]" + lSep);
  334. msg.append("Options: " + lSep);
  335. msg.append(" -help print this message" + lSep);
  336. msg.append(" -projecthelp print project help information" + lSep);
  337. msg.append(" -version print the version information and exit" + lSep);
  338. msg.append(" -quiet be extra quiet" + lSep);
  339. msg.append(" -verbose be extra verbose" + lSep);
  340. msg.append(" -emacs produce logging information without adornments" + lSep);
  341. msg.append(" -logfile <file> use given file for log" + lSep);
  342. msg.append(" -logger <classname> the class which is to perform logging" + lSep);
  343. msg.append(" -listener <classname> add an instance of class as a project listener" + lSep);
  344. msg.append(" -buildfile <file> use given buildfile" + lSep);
  345. msg.append(" -D<property>=<value> use value for given property" + lSep);
  346. System.out.println(msg.toString());
  347. }
  348. private static void printVersion() {
  349. try {
  350. Properties props = new Properties();
  351. InputStream in =
  352. Main.class.getResourceAsStream("/org/apache/tools/ant/version.txt");
  353. props.load(in);
  354. in.close();
  355. String lSep = System.getProperty("line.separator");
  356. StringBuffer msg = new StringBuffer();
  357. msg.append("Ant version ");
  358. msg.append(props.getProperty("VERSION"));
  359. msg.append(" compiled on ");
  360. msg.append(props.getProperty("DATE"));
  361. msg.append(lSep);
  362. System.out.println(msg.toString());
  363. } catch (IOException ioe) {
  364. System.err.println("Could not load the version information.");
  365. System.err.println(ioe.getMessage());
  366. } catch (NullPointerException npe) {
  367. System.err.println("Could not load the version information.");
  368. }
  369. }
  370. /**
  371. * Print out a list of all targets in the current buildfile
  372. */
  373. private static void printTargets(Project project) {
  374. // find the target with the longest name and
  375. // filter out the targets with no description
  376. int maxLength = 0;
  377. Enumeration ptargets = project.getTargets().elements();
  378. String targetName;
  379. String targetDescription;
  380. Target currentTarget;
  381. Vector names = new Vector();
  382. Vector descriptions = new Vector();
  383. while (ptargets.hasMoreElements()) {
  384. currentTarget = (Target)ptargets.nextElement();
  385. targetName = currentTarget.getName();
  386. targetDescription = currentTarget.getDescription();
  387. if (targetDescription == null) {
  388. targetDescription = "";
  389. }
  390. names.addElement(targetName);
  391. descriptions.addElement(targetDescription);
  392. if (targetName.length() > maxLength) {
  393. maxLength = targetName.length();
  394. }
  395. }
  396. // now, start printing the targets and their descriptions
  397. String lSep = System.getProperty("line.separator");
  398. // got a bit annoyed that I couldn't find a pad function
  399. String spaces = " ";
  400. while (spaces.length()<maxLength) {
  401. spaces += spaces;
  402. }
  403. StringBuffer msg = new StringBuffer();
  404. msg.append("Targets: " + lSep);
  405. for (int i=0; i<names.size(); i++) {
  406. msg.append(" -"+names.elementAt(i));
  407. msg.append(spaces.substring(0, maxLength - ((String)names.elementAt(i)).length() + 2));
  408. msg.append(descriptions.elementAt(i)+lSep);
  409. }
  410. System.out.println(msg.toString());
  411. }
  412. }