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 33 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841
  1. /*
  2. * The Apache Software License, Version 1.1
  3. *
  4. * Copyright (c) 2000-2002 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", "Ant", 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.File;
  56. import java.io.FileInputStream;
  57. import java.io.PrintStream;
  58. import java.io.FileOutputStream;
  59. import java.io.IOException;
  60. import java.io.InputStream;
  61. import java.util.Vector;
  62. import java.util.Properties;
  63. import java.util.Enumeration;
  64. /**
  65. * Command line entry point into Ant. This class is entered via the
  66. * cannonical `public static void main` entry point and reads the
  67. * command line arguments. It then assembles and executes an Ant
  68. * project.
  69. * <p>
  70. * If you integrating Ant into some other tool, this is not the class
  71. * to use as an entry point. Please see the source code of this
  72. * class to see how it manipulates the Ant project classes.
  73. *
  74. * @author duncan@x180.com
  75. */
  76. public class Main {
  77. /** The default build file name. */
  78. public final static String DEFAULT_BUILD_FILENAME = "build.xml";
  79. /** Our current message output status. Follows Project.MSG_XXX. */
  80. private int msgOutputLevel = Project.MSG_INFO;
  81. /** File that we are using for configuration. */
  82. private File buildFile; /* null */
  83. /** Stream to use for logging. */
  84. private PrintStream out = System.out;
  85. /** Stream that we are using for logging error messages. */
  86. private PrintStream err = System.err;
  87. /** The build targets. */
  88. private Vector targets = new Vector(5);
  89. /** Set of properties that can be used by tasks. */
  90. private Properties definedProps = new Properties();
  91. /** Names of classes to add as listeners to project. */
  92. private Vector listeners = new Vector(5);
  93. /** File names of property files to load on startup. */
  94. private Vector propertyFiles = new Vector(5);
  95. /**
  96. * The Ant logger class. There may be only one logger. It will have
  97. * the right to use the 'out' PrintStream. The class must implements the
  98. * BuildLogger interface.
  99. */
  100. private String loggerClassname = null;
  101. /**
  102. * Whether or not output to the log is to be unadorned.
  103. */
  104. private boolean emacsMode = false;
  105. /**
  106. * Whether or not this instance has successfully been
  107. * constructed and is ready to run.
  108. */
  109. private boolean readyToRun = false;
  110. /**
  111. * Whether or not we should only parse and display the project help
  112. * information.
  113. */
  114. private boolean projectHelp = false;
  115. /**
  116. * Prints the message of the Throwable if it (the message) is not
  117. * <code>null</code>.
  118. *
  119. * @param t Throwable to print the message of.
  120. * Must not be <code>null</code>.
  121. */
  122. private static void printMessage(Throwable t) {
  123. String message = t.getMessage();
  124. if (message != null) {
  125. System.err.println(message);
  126. }
  127. }
  128. /**
  129. * Creates a new instance of this class using the
  130. * arguments specified, gives it any extra user properties which have been
  131. * specified, and then runs the build using the classloader provided.
  132. *
  133. * @param args Command line arguments. Must not be <code>null</code>.
  134. * @param additionalUserProperties Any extra properties to use in this
  135. * build. May be <code>null</code>, which is the equivalent to
  136. * passing in an empty set of properties.
  137. * @param coreLoader Classloader used for core classes. May be
  138. * <code>null</code> in which case the system classloader is used.
  139. */
  140. public static void start(String[] args, Properties additionalUserProperties,
  141. ClassLoader coreLoader) {
  142. Main m = null;
  143. try {
  144. m = new Main(args);
  145. } catch(Throwable exc) {
  146. printMessage(exc);
  147. System.exit(1);
  148. }
  149. if (additionalUserProperties != null) {
  150. for (Enumeration e = additionalUserProperties.keys(); e.hasMoreElements(); ) {
  151. String key = (String) e.nextElement();
  152. String property = additionalUserProperties.getProperty(key);
  153. m.definedProps.put(key, property);
  154. }
  155. }
  156. try {
  157. m.runBuild(coreLoader);
  158. System.exit(0);
  159. } catch (BuildException be) {
  160. if (m.err != System.err) {
  161. printMessage(be);
  162. }
  163. System.exit(1);
  164. } catch(Throwable exc) {
  165. exc.printStackTrace();
  166. printMessage(exc);
  167. System.exit(1);
  168. }
  169. }
  170. /**
  171. * Command line entry point. This method kicks off the building
  172. * of a project object and executes a build using either a given
  173. * target or the default target.
  174. *
  175. * @param args Command line arguments. Must not be <code>null</code>.
  176. */
  177. public static void main(String[] args) {
  178. start(args, null, null);
  179. }
  180. // XXX: (Jon Skeet) Error handling appears to be inconsistent here.
  181. // Sometimes there's just a return statement, and sometimes a
  182. // BuildException is thrown. What's the rationale for when to do
  183. // what?
  184. /**
  185. * Sole constructor, which parses and deals with command line
  186. * arguments.
  187. *
  188. * @param args Command line arguments. Must not be <code>null</code>.
  189. *
  190. * @exception BuildException if the specified build file doesn't exist
  191. * or is a directory.
  192. */
  193. protected Main(String[] args) throws BuildException {
  194. String searchForThis = null;
  195. // cycle through given args
  196. for (int i = 0; i < args.length; i++) {
  197. String arg = args[i];
  198. if (arg.equals("-help")) {
  199. printUsage();
  200. return;
  201. } else if (arg.equals("-version")) {
  202. printVersion();
  203. return;
  204. } else if (arg.equals("-quiet") || arg.equals("-q")) {
  205. msgOutputLevel = Project.MSG_WARN;
  206. } else if (arg.equals("-verbose") || arg.equals("-v")) {
  207. printVersion();
  208. msgOutputLevel = Project.MSG_VERBOSE;
  209. } else if (arg.equals("-debug")) {
  210. printVersion();
  211. msgOutputLevel = Project.MSG_DEBUG;
  212. } else if (arg.equals("-logfile") || arg.equals("-l")) {
  213. try {
  214. File logFile = new File(args[i+1]);
  215. i++;
  216. out = new PrintStream(new FileOutputStream(logFile));
  217. err = out;
  218. System.setOut(out);
  219. System.setErr(out);
  220. } catch (IOException ioe) {
  221. String msg = "Cannot write on the specified log file. " +
  222. "Make sure the path exists and you have write permissions.";
  223. System.out.println(msg);
  224. return;
  225. } catch (ArrayIndexOutOfBoundsException aioobe) {
  226. String msg = "You must specify a log file when " +
  227. "using the -log argument";
  228. System.out.println(msg);
  229. return;
  230. }
  231. } else if (arg.equals("-buildfile") || arg.equals("-file") || arg.equals("-f")) {
  232. try {
  233. buildFile = new File(args[i+1]);
  234. i++;
  235. } catch (ArrayIndexOutOfBoundsException aioobe) {
  236. String msg = "You must specify a buildfile when " +
  237. "using the -buildfile argument";
  238. System.out.println(msg);
  239. return;
  240. }
  241. } else if (arg.equals("-listener")) {
  242. try {
  243. listeners.addElement(args[i+1]);
  244. i++;
  245. } catch (ArrayIndexOutOfBoundsException aioobe) {
  246. String msg = "You must specify a classname when " +
  247. "using the -listener argument";
  248. System.out.println(msg);
  249. return;
  250. }
  251. } else if (arg.startsWith("-D")) {
  252. /* Interestingly enough, we get to here when a user
  253. * uses -Dname=value. However, in some cases, the JDK
  254. * goes ahead and parses this out to args
  255. * {"-Dname", "value"}
  256. * so instead of parsing on "=", we just make the "-D"
  257. * characters go away and skip one argument forward.
  258. *
  259. * I don't know how to predict when the JDK is going
  260. * to help or not, so we simply look for the equals sign.
  261. */
  262. String name = arg.substring(2, arg.length());
  263. String value = null;
  264. int posEq = name.indexOf("=");
  265. if (posEq > 0) {
  266. value = name.substring(posEq+1);
  267. name = name.substring(0, posEq);
  268. } else if (i < args.length-1) {
  269. value = args[++i];
  270. }
  271. definedProps.put(name, value);
  272. } else if (arg.equals("-logger")) {
  273. if (loggerClassname != null) {
  274. System.out.println("Only one logger class may be specified.");
  275. return;
  276. }
  277. try {
  278. loggerClassname = args[++i];
  279. }
  280. catch (ArrayIndexOutOfBoundsException aioobe) {
  281. System.out.println("You must specify a classname when " +
  282. "using the -logger argument");
  283. return;
  284. }
  285. } else if (arg.equals("-emacs")) {
  286. emacsMode = true;
  287. } else if (arg.equals("-projecthelp")) {
  288. // set the flag to display the targets and quit
  289. projectHelp = true;
  290. } else if (arg.equals("-find")) {
  291. // eat up next arg if present, default to build.xml
  292. if (i < args.length-1) {
  293. searchForThis = args[++i];
  294. } else {
  295. searchForThis = DEFAULT_BUILD_FILENAME;
  296. }
  297. } else if (arg.startsWith("-propertyfile")) {
  298. try {
  299. propertyFiles.addElement(args[i+1]);
  300. i++;
  301. } catch (ArrayIndexOutOfBoundsException aioobe) {
  302. String msg = "You must specify a property filename when " +
  303. "using the -propertyfile argument";
  304. System.out.println(msg);
  305. return;
  306. }
  307. } else if (arg.startsWith("-")) {
  308. // we don't have any more args to recognize!
  309. String msg = "Unknown argument: " + arg;
  310. System.out.println(msg);
  311. printUsage();
  312. return;
  313. } else {
  314. // if it's no other arg, it may be the target
  315. targets.addElement(arg);
  316. }
  317. }
  318. // if buildFile was not specified on the command line,
  319. if (buildFile == null) {
  320. // but -find then search for it
  321. if (searchForThis != null) {
  322. buildFile = findBuildFile(System.getProperty("user.dir"),
  323. searchForThis);
  324. } else {
  325. buildFile = new File(DEFAULT_BUILD_FILENAME);
  326. }
  327. }
  328. // make sure buildfile exists
  329. if (!buildFile.exists()) {
  330. System.out.println("Buildfile: " + buildFile + " does not exist!");
  331. throw new BuildException("Build failed");
  332. }
  333. // make sure it's not a directory (this falls into the ultra
  334. // paranoid lets check everything catagory
  335. if (buildFile.isDirectory()) {
  336. System.out.println("What? Buildfile: " + buildFile + " is a dir!");
  337. throw new BuildException("Build failed");
  338. }
  339. // Load the property files specified by -propertyfile
  340. for (int propertyFileIndex=0;
  341. propertyFileIndex < propertyFiles.size();
  342. propertyFileIndex++) {
  343. String filename = (String) propertyFiles.elementAt(propertyFileIndex);
  344. Properties props = new Properties();
  345. FileInputStream fis = null;
  346. try {
  347. fis = new FileInputStream(filename);
  348. props.load(fis);
  349. }
  350. catch (IOException e) {
  351. System.out.println("Could not load property file "
  352. + filename + ": " + e.getMessage());
  353. } finally {
  354. if (fis != null){
  355. try {
  356. fis.close();
  357. } catch (IOException e){
  358. }
  359. }
  360. }
  361. // ensure that -D properties take precedence
  362. Enumeration propertyNames = props.propertyNames();
  363. while (propertyNames.hasMoreElements()) {
  364. String name = (String) propertyNames.nextElement();
  365. if (definedProps.getProperty(name) == null) {
  366. definedProps.put(name, props.getProperty(name));
  367. }
  368. }
  369. }
  370. readyToRun = true;
  371. }
  372. /**
  373. * Helper to get the parent file for a given file.
  374. * <p>
  375. * Added to simulate File.getParentFile() from JDK 1.2.
  376. *
  377. * @param file File to find parent of. Must not be <code>null</code>.
  378. * @return Parent file or null if none
  379. */
  380. private File getParentFile(File file) {
  381. String filename = file.getAbsolutePath();
  382. file = new File(filename);
  383. filename = file.getParent();
  384. if (filename != null && msgOutputLevel >= Project.MSG_VERBOSE) {
  385. System.out.println("Searching in "+filename);
  386. }
  387. return (filename == null) ? null : new File(filename);
  388. }
  389. /**
  390. * Search parent directories for the build file.
  391. * <p>
  392. * Takes the given target as a suffix to append to each
  393. * parent directory in seach of a build file. Once the
  394. * root of the file-system has been reached an exception
  395. * is thrown.
  396. *
  397. * @param start Leaf directory of search.
  398. * Must not be <code>null</code>.
  399. * @param suffix Suffix filename to look for in parents.
  400. * Must not be <code>null</code>.
  401. *
  402. * @return A handle to the build file if one is found
  403. *
  404. * @exception BuildException if no build file is found
  405. */
  406. private File findBuildFile(String start, String suffix) throws BuildException {
  407. if (msgOutputLevel >= Project.MSG_INFO) {
  408. System.out.println("Searching for " + suffix + " ...");
  409. }
  410. File parent = new File(new File(start).getAbsolutePath());
  411. File file = new File(parent, suffix);
  412. // check if the target file exists in the current directory
  413. while (!file.exists()) {
  414. // change to parent directory
  415. parent = getParentFile(parent);
  416. // if parent is null, then we are at the root of the fs,
  417. // complain that we can't find the build file.
  418. if (parent == null) {
  419. throw new BuildException("Could not locate a build file!");
  420. }
  421. // refresh our file handle
  422. file = new File(parent, suffix);
  423. }
  424. return file;
  425. }
  426. /**
  427. * Executes the build. If the constructor for this instance failed
  428. * (e.g. returned after issuing a warning), this method returns
  429. * immediately.
  430. *
  431. * @param coreLoader The classloader to use to find core classes.
  432. * May be <code>null</code>, in which case the
  433. * system classloader is used.
  434. *
  435. * @exception BuildException if the build fails
  436. */
  437. private void runBuild(ClassLoader coreLoader) throws BuildException {
  438. if (!readyToRun) {
  439. return;
  440. }
  441. // track when we started
  442. if (msgOutputLevel >= Project.MSG_INFO) {
  443. System.out.println("Buildfile: " + buildFile);
  444. }
  445. final Project project = new Project();
  446. project.setCoreLoader(coreLoader);
  447. Throwable error = null;
  448. try {
  449. addBuildListeners(project);
  450. PrintStream err = System.err;
  451. PrintStream out = System.out;
  452. // use a system manager that prevents from System.exit()
  453. // only in JDK > 1.1
  454. SecurityManager oldsm = null;
  455. if ( !Project.JAVA_1_0.equals(Project.getJavaVersion()) &&
  456. !Project.JAVA_1_1.equals(Project.getJavaVersion()) ){
  457. oldsm = System.getSecurityManager();
  458. //SecurityManager can not be installed here for backwards
  459. //compatability reasons (PD). Needs to be loaded prior to
  460. //ant class if we are going to implement it.
  461. //System.setSecurityManager(new NoExitSecurityManager());
  462. }
  463. try {
  464. System.setOut(new PrintStream(new DemuxOutputStream(project, false)));
  465. System.setErr(new PrintStream(new DemuxOutputStream(project, true)));
  466. if (!projectHelp) {
  467. project.fireBuildStarted();
  468. }
  469. project.init();
  470. project.setUserProperty("ant.version", getAntVersion());
  471. // set user-define properties
  472. Enumeration e = definedProps.keys();
  473. while (e.hasMoreElements()) {
  474. String arg = (String)e.nextElement();
  475. String value = (String)definedProps.get(arg);
  476. project.setUserProperty(arg, value);
  477. }
  478. project.setUserProperty("ant.file" , buildFile.getAbsolutePath() );
  479. // first use the ProjectHelper to create the project object
  480. // from the given build file.
  481. String noParserMessage =
  482. "No JAXP compliant XML parser found. Please visit http://xml.apache.org for a suitable parser";
  483. try {
  484. Class.forName("javax.xml.parsers.SAXParserFactory");
  485. ProjectHelper.configureProject(project, buildFile);
  486. } catch (NoClassDefFoundError ncdfe) {
  487. throw new BuildException(noParserMessage, ncdfe);
  488. } catch (ClassNotFoundException cnfe) {
  489. throw new BuildException(noParserMessage, cnfe);
  490. } catch (NullPointerException npe) {
  491. throw new BuildException(noParserMessage, npe);
  492. }
  493. if (projectHelp) {
  494. printDescription(project);
  495. printTargets(project, msgOutputLevel > Project.MSG_INFO );
  496. return;
  497. }
  498. // make sure that we have a target to execute
  499. if (targets.size() == 0) {
  500. targets.addElement(project.getDefaultTarget());
  501. }
  502. project.executeTargets(targets);
  503. }
  504. finally {
  505. // put back the original security manager
  506. //The following will never eval to true. (PD)
  507. if (oldsm != null){
  508. System.setSecurityManager(oldsm);
  509. }
  510. System.setOut(out);
  511. System.setErr(err);
  512. }
  513. }
  514. catch(RuntimeException exc) {
  515. error = exc;
  516. throw exc;
  517. }
  518. catch(Error err) {
  519. error = err;
  520. throw err;
  521. }
  522. finally {
  523. if (!projectHelp) {
  524. project.fireBuildFinished(error);
  525. }
  526. }
  527. }
  528. /**
  529. * Adds the listeners specified in the command line arguments,
  530. * along with the default listener, to the specified project.
  531. *
  532. * @param project The project to add listeners to.
  533. * Must not be <code>null</code>.
  534. */
  535. protected void addBuildListeners(Project project) {
  536. // Add the default listener
  537. project.addBuildListener(createLogger());
  538. for (int i = 0; i < listeners.size(); i++) {
  539. String className = (String) listeners.elementAt(i);
  540. try {
  541. BuildListener listener =
  542. (BuildListener) Class.forName(className).newInstance();
  543. project.addBuildListener(listener);
  544. }
  545. catch(Throwable exc) {
  546. throw new BuildException("Unable to instantiate listener " + className, exc);
  547. }
  548. }
  549. }
  550. // XXX: (Jon Skeet) Any reason for writing a message and then using a bare
  551. // RuntimeException rather than just using a BuildException here? Is it
  552. // in case the message could end up being written to no loggers (as the loggers
  553. // could have failed to be created due to this failure)?
  554. /**
  555. * Creates the default build logger for sending build events to the ant log.
  556. */
  557. private BuildLogger createLogger() {
  558. BuildLogger logger = null;
  559. if (loggerClassname != null) {
  560. try {
  561. logger = (BuildLogger)(Class.forName(loggerClassname).newInstance());
  562. }
  563. catch (ClassCastException e) {
  564. System.err.println("The specified logger class " + loggerClassname +
  565. " does not implement the BuildLogger interface");
  566. throw new RuntimeException();
  567. }
  568. catch (Exception e) {
  569. System.err.println("Unable to instantiate specified logger class " +
  570. loggerClassname + " : " + e.getClass().getName());
  571. throw new RuntimeException();
  572. }
  573. }
  574. else {
  575. logger = new DefaultLogger();
  576. }
  577. logger.setMessageOutputLevel(msgOutputLevel);
  578. logger.setOutputPrintStream(out);
  579. logger.setErrorPrintStream(err);
  580. logger.setEmacsMode(emacsMode);
  581. return logger;
  582. }
  583. /**
  584. * Prints the usage information for this class to <code>System.out</code>.
  585. */
  586. private static void printUsage() {
  587. String lSep = System.getProperty("line.separator");
  588. StringBuffer msg = new StringBuffer();
  589. msg.append("ant [options] [target [target2 [target3] ...]]" + lSep);
  590. msg.append("Options: " + lSep);
  591. msg.append(" -help print this message" + lSep);
  592. msg.append(" -projecthelp print project help information" + lSep);
  593. msg.append(" -version print the version information and exit" + lSep);
  594. msg.append(" -quiet be extra quiet" + lSep);
  595. msg.append(" -verbose be extra verbose" + lSep);
  596. msg.append(" -debug print debugging information" + lSep);
  597. msg.append(" -emacs produce logging information without adornments" + lSep);
  598. msg.append(" -logfile <file> use given file for log" + lSep);
  599. msg.append(" -logger <classname> the class which is to perform logging" + lSep);
  600. msg.append(" -listener <classname> add an instance of class as a project listener" + lSep);
  601. msg.append(" -buildfile <file> use given buildfile" + lSep);
  602. msg.append(" -D<property>=<value> use value for given property" + lSep);
  603. msg.append(" -propertyfile <name> load all properties from file with -D" + lSep);
  604. msg.append(" properties taking precedence" + lSep);
  605. msg.append(" -find <file> search for buildfile towards the root of the" + lSep);
  606. msg.append(" filesystem and use it" + lSep);
  607. System.out.println(msg.toString());
  608. }
  609. /**
  610. * Prints the Ant version information to <code>System.out</code>.
  611. *
  612. * @exception BuildException if the version information is unavailable
  613. */
  614. private static void printVersion() throws BuildException {
  615. System.out.println(getAntVersion());
  616. }
  617. /**
  618. * Cache of the Ant version information when it has been loaded.
  619. */
  620. private static String antVersion = null;
  621. /**
  622. * Returns the Ant version information, if available. Once the information
  623. * has been loaded once, it's cached and returned from the cache on future
  624. * calls.
  625. *
  626. * @return the Ant version information as a String
  627. * (always non-<code>null</code>)
  628. *
  629. * @exception BuildException if the version information is unavailable
  630. */
  631. public static synchronized String getAntVersion() throws BuildException {
  632. if (antVersion == null) {
  633. try {
  634. Properties props = new Properties();
  635. InputStream in =
  636. Main.class.getResourceAsStream("/org/apache/tools/ant/version.txt");
  637. props.load(in);
  638. in.close();
  639. String lSep = System.getProperty("line.separator");
  640. StringBuffer msg = new StringBuffer();
  641. msg.append("Apache Ant version ");
  642. msg.append(props.getProperty("VERSION"));
  643. msg.append(" compiled on ");
  644. msg.append(props.getProperty("DATE"));
  645. antVersion = msg.toString();
  646. } catch (IOException ioe) {
  647. throw new BuildException("Could not load the version information:"
  648. + ioe.getMessage());
  649. } catch (NullPointerException npe) {
  650. throw new BuildException("Could not load the version information.");
  651. }
  652. }
  653. return antVersion;
  654. }
  655. /**
  656. * Prints the description of a project (if there is one) to
  657. * <code>System.out</code>.
  658. *
  659. * @param project The project to display a description of.
  660. * Must not be <code>null</code>.
  661. */
  662. private static void printDescription(Project project) {
  663. if (project.getDescription() != null) {
  664. System.out.println(project.getDescription());
  665. }
  666. }
  667. /**
  668. * Prints a list of all targets in the specified project to
  669. * <code>System.out</code>, optionally including subtargets.
  670. *
  671. * @param project The project to display a description of.
  672. * Must not be <code>null</code>.
  673. * @param printSubTargets Whether or not subtarget names should also be
  674. * printed.
  675. */
  676. private static void printTargets(Project project, boolean printSubTargets) {
  677. // find the target with the longest name
  678. int maxLength = 0;
  679. Enumeration ptargets = project.getTargets().elements();
  680. String targetName;
  681. String targetDescription;
  682. Target currentTarget;
  683. // split the targets in top-level and sub-targets depending
  684. // on the presence of a description
  685. Vector topNames = new Vector();
  686. Vector topDescriptions = new Vector();
  687. Vector subNames = new Vector();
  688. while (ptargets.hasMoreElements()) {
  689. currentTarget = (Target)ptargets.nextElement();
  690. targetName = currentTarget.getName();
  691. targetDescription = currentTarget.getDescription();
  692. // maintain a sorted list of targets
  693. if (targetDescription == null) {
  694. int pos = findTargetPosition(subNames, targetName);
  695. subNames.insertElementAt(targetName, pos);
  696. } else {
  697. int pos = findTargetPosition(topNames, targetName);
  698. topNames.insertElementAt(targetName, pos);
  699. topDescriptions.insertElementAt(targetDescription, pos);
  700. if (targetName.length() > maxLength) {
  701. maxLength = targetName.length();
  702. }
  703. }
  704. }
  705. printTargets(topNames, topDescriptions, "Main targets:", maxLength);
  706. if( printSubTargets ) {
  707. printTargets(subNames, null, "Subtargets:", 0);
  708. }
  709. String defaultTarget = project.getDefaultTarget();
  710. if (defaultTarget != null && !"".equals(defaultTarget)) { // shouldn't need to check but...
  711. System.out.println( "Default target: " + defaultTarget );
  712. }
  713. }
  714. /**
  715. * Searches for the correct place to insert a name into a list so as
  716. * to keep the list sorted alphabetically.
  717. *
  718. * @param names The current list of names. Must not be <code>null</code>.
  719. * @param name The name to find a place for.
  720. * Must not be <code>null</code>.
  721. *
  722. * @return the correct place in the list for the given name
  723. */
  724. private static int findTargetPosition(Vector names, String name) {
  725. int res = names.size();
  726. for (int i=0; i<names.size() && res == names.size(); i++) {
  727. if (name.compareTo((String)names.elementAt(i)) < 0) {
  728. res = i;
  729. }
  730. }
  731. return res;
  732. }
  733. /**
  734. * Writes a formatted list of target names to <code>System.out</code>
  735. * with an optional description
  736. */
  737. private static void printTargets(Vector names, Vector descriptions, String heading, int maxlen) {
  738. // now, start printing the targets and their descriptions
  739. String lSep = System.getProperty("line.separator");
  740. // got a bit annoyed that I couldn't find a pad function
  741. String spaces = " ";
  742. while (spaces.length()<maxlen) {
  743. spaces += spaces;
  744. }
  745. StringBuffer msg = new StringBuffer();
  746. msg.append(heading + lSep + lSep);
  747. for (int i=0; i<names.size(); i++) {
  748. msg.append(" ");
  749. msg.append(names.elementAt(i));
  750. if (descriptions != null) {
  751. msg.append(spaces.substring(0, maxlen - ((String)names.elementAt(i)).length() + 2));
  752. msg.append(descriptions.elementAt(i));
  753. }
  754. msg.append(lSep);
  755. }
  756. System.out.println(msg.toString());
  757. }
  758. }