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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594
  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", "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.*;
  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. public final static String BANNER =
  71. "Ant version " + Constants.VERSION + " compiled on " + Constants.DATE;
  72. /** The default build file name */
  73. public static final String DEFAULT_BUILD_FILENAME = "build.xml";
  74. /** Our current message output status. Follows Project.MSG_XXX */
  75. private int msgOutputLevel = Project.MSG_INFO;
  76. /** File that we are using for configuration */
  77. private File buildFile; /** null */
  78. /** Stream that we are using for logging */
  79. private PrintStream out = System.out;
  80. /** Stream that we are using for logging error messages */
  81. private PrintStream err = System.err;
  82. /** The build targets */
  83. private Vector targets = new Vector(5);
  84. /** Set of properties that can be used by tasks */
  85. private Properties definedProps = new Properties();
  86. /** Names of classes to add as listeners to project */
  87. private Vector listeners = new Vector(5);
  88. /**
  89. * The Ant logger class. There may be only one logger. It will have the
  90. * right to use the 'out' PrintStream. The class must implements the BuildLogger
  91. * interface
  92. */
  93. private String loggerClassname = null;
  94. /**
  95. * Indicates whether output to the log is to be unadorned.
  96. */
  97. private boolean emacsMode = false;
  98. /**
  99. * Indicates if this ant should be run.
  100. */
  101. private boolean readyToRun = false;
  102. /**
  103. * Indicates we should only parse and display the project help information
  104. */
  105. private boolean projectHelp = false;
  106. /**
  107. * Prints the message of the Throwable if it's not null.
  108. */
  109. private static void printMessage(Throwable t) {
  110. String message = t.getMessage();
  111. if (message != null) {
  112. System.err.println(message);
  113. }
  114. }
  115. /**
  116. * Command line entry point. This method kicks off the building
  117. * of a project object and executes a build using either a given
  118. * target or the default target.
  119. *
  120. * @param args Command line args.
  121. */
  122. public static void main(String[] args) {
  123. Main m = null;
  124. try {
  125. m = new Main(args);
  126. } catch(Throwable exc) {
  127. printMessage(exc);
  128. System.exit(1);
  129. }
  130. try {
  131. m.runBuild();
  132. System.exit(0);
  133. } catch (BuildException be) {
  134. if (m.err != System.err) {
  135. printMessage(be);
  136. }
  137. System.exit(1);
  138. } catch(Throwable exc) {
  139. printMessage(exc);
  140. System.exit(1);
  141. }
  142. }
  143. protected Main(String[] args) throws BuildException {
  144. String searchForThis = null;
  145. // cycle through given args
  146. for (int i = 0; i < args.length; i++) {
  147. String arg = args[i];
  148. if (arg.equals("-help")) {
  149. printUsage();
  150. return;
  151. } else if (arg.equals("-version")) {
  152. printVersion();
  153. return;
  154. } else if (arg.equals("-quiet") || arg.equals("-q")) {
  155. msgOutputLevel = Project.MSG_WARN;
  156. } else if (arg.equals("-verbose") || arg.equals("-v")) {
  157. printVersion();
  158. msgOutputLevel = Project.MSG_VERBOSE;
  159. } else if (arg.equals("-debug")) {
  160. printVersion();
  161. msgOutputLevel = Project.MSG_DEBUG;
  162. } else if (arg.equals("-logfile") || arg.equals("-l")) {
  163. try {
  164. File logFile = new File(args[i+1]);
  165. i++;
  166. out = new PrintStream(new FileOutputStream(logFile));
  167. err = out;
  168. System.setOut(out);
  169. System.setErr(out);
  170. } catch (IOException ioe) {
  171. String msg = "Cannot write on the specified log file. " +
  172. "Make sure the path exists and you have write permissions.";
  173. System.out.println(msg);
  174. return;
  175. } catch (ArrayIndexOutOfBoundsException aioobe) {
  176. String msg = "You must specify a log file when " +
  177. "using the -log argument";
  178. System.out.println(msg);
  179. return;
  180. }
  181. } else if (arg.equals("-buildfile") || arg.equals("-file") || arg.equals("-f")) {
  182. try {
  183. buildFile = new File(args[i+1]);
  184. i++;
  185. } catch (ArrayIndexOutOfBoundsException aioobe) {
  186. String msg = "You must specify a buildfile when " +
  187. "using the -buildfile argument";
  188. System.out.println(msg);
  189. return;
  190. }
  191. } else if (arg.equals("-listener")) {
  192. try {
  193. listeners.addElement(args[i+1]);
  194. i++;
  195. } catch (ArrayIndexOutOfBoundsException aioobe) {
  196. String msg = "You must specify a classname when " +
  197. "using the -listener argument";
  198. System.out.println(msg);
  199. return;
  200. }
  201. } else if (arg.startsWith("-D")) {
  202. /* Interestingly enough, we get to here when a user
  203. * uses -Dname=value. However, in some cases, the JDK
  204. * goes ahead * and parses this out to args
  205. * {"-Dname", "value"}
  206. * so instead of parsing on "=", we just make the "-D"
  207. * characters go away and skip one argument forward.
  208. *
  209. * I don't know how to predict when the JDK is going
  210. * to help or not, so we simply look for the equals sign.
  211. */
  212. String name = arg.substring(2, arg.length());
  213. String value = null;
  214. int posEq = name.indexOf("=");
  215. if (posEq > 0) {
  216. value = name.substring(posEq+1);
  217. name = name.substring(0, posEq);
  218. } else if (i < args.length-1)
  219. value = args[++i];
  220. definedProps.put(name, value);
  221. } else if (arg.equals("-logger")) {
  222. if (loggerClassname != null) {
  223. System.out.println("Only one logger class may be specified.");
  224. return;
  225. }
  226. loggerClassname = args[++i];
  227. } else if (arg.equals("-emacs")) {
  228. emacsMode = true;
  229. } else if (arg.equals("-projecthelp")) {
  230. // set the flag to display the targets and quit
  231. projectHelp = true;
  232. } else if (arg.equals("-find")) {
  233. // eat up next arg if present, default to build.xml
  234. if (i < args.length-1) {
  235. searchForThis = args[++i];
  236. } else {
  237. searchForThis = DEFAULT_BUILD_FILENAME;
  238. }
  239. } else if (arg.startsWith("-")) {
  240. // we don't have any more args to recognize!
  241. String msg = "Unknown argument: " + arg;
  242. System.out.println(msg);
  243. printUsage();
  244. return;
  245. } else {
  246. // if it's no other arg, it may be the target
  247. targets.addElement(arg);
  248. }
  249. }
  250. // if buildFile was not specified on the command line,
  251. if (buildFile == null) {
  252. // but -find then search for it
  253. if (searchForThis != null) {
  254. buildFile = findBuildFile(".", searchForThis);
  255. } else {
  256. buildFile = new File(DEFAULT_BUILD_FILENAME);
  257. }
  258. }
  259. // make sure buildfile exists
  260. if (!buildFile.exists()) {
  261. System.out.println("Buildfile: " + buildFile + " does not exist!");
  262. throw new BuildException("Build failed");
  263. }
  264. // make sure it's not a directory (this falls into the ultra
  265. // paranoid lets check everything catagory
  266. if (buildFile.isDirectory()) {
  267. System.out.println("What? Buildfile: " + buildFile + " is a dir!");
  268. throw new BuildException("Build failed");
  269. }
  270. readyToRun = true;
  271. }
  272. /**
  273. * Helper to get the parent file for a given file.
  274. *
  275. * <P>Added to simulate File.getParentFile() from JDK 1.2.
  276. *
  277. * @param file File
  278. * @return Parent file or null if none
  279. */
  280. private File getParentFile(File file) {
  281. String filename = file.getAbsolutePath();
  282. file = new File(filename);
  283. filename = file.getParent();
  284. if (filename != null && msgOutputLevel >= Project.MSG_VERBOSE) {
  285. System.out.println("Searching in "+filename);
  286. }
  287. return (filename == null) ? null : new File(filename);
  288. }
  289. /**
  290. * Search parent directories for the build file.
  291. *
  292. * <P>Takes the given target as a suffix to append to each
  293. * parent directory in seach of a build file. Once the
  294. * root of the file-system has been reached an exception
  295. * is thrown.
  296. *
  297. * @param suffix Suffix filename to look for in parents.
  298. * @return A handle to the build file
  299. *
  300. * @exception BuildException Failed to locate a build file
  301. */
  302. private File findBuildFile(String start, String suffix) throws BuildException {
  303. if (msgOutputLevel >= Project.MSG_INFO) {
  304. System.out.println("Searching for " + suffix + " ...");
  305. }
  306. File parent = new File(new File(start).getAbsolutePath());
  307. File file = new File(parent, suffix);
  308. // check if the target file exists in the current directory
  309. while (!file.exists()) {
  310. // change to parent directory
  311. parent = getParentFile(parent);
  312. // if parent is null, then we are at the root of the fs,
  313. // complain that we can't find the build file.
  314. if (parent == null) {
  315. throw new BuildException("Could not locate a build file!");
  316. }
  317. // refresh our file handle
  318. file = new File(parent, suffix);
  319. }
  320. return file;
  321. }
  322. /**
  323. * Executes the build.
  324. */
  325. private void runBuild() throws BuildException {
  326. if (!readyToRun) {
  327. return;
  328. }
  329. // track when we started
  330. if (msgOutputLevel >= Project.MSG_INFO) {
  331. System.out.println("Buildfile: " + buildFile);
  332. }
  333. Project project = new Project();
  334. Throwable error = null;
  335. try {
  336. addBuildListeners(project);
  337. project.fireBuildStarted();
  338. project.init();
  339. // set user-define properties
  340. Enumeration e = definedProps.keys();
  341. while (e.hasMoreElements()) {
  342. String arg = (String)e.nextElement();
  343. String value = (String)definedProps.get(arg);
  344. project.setUserProperty(arg, value);
  345. }
  346. project.setUserProperty( "ant.file" , buildFile.getAbsolutePath() );
  347. // first use the ProjectHelper to create the project object
  348. // from the given build file.
  349. try {
  350. Class.forName("javax.xml.parsers.SAXParserFactory");
  351. ProjectHelper.configureProject(project, buildFile);
  352. } catch (NoClassDefFoundError ncdfe) {
  353. throw new BuildException("No JAXP compliant XML parser found. See http://java.sun.com/xml for the\nreference implementation.", ncdfe);
  354. } catch (ClassNotFoundException cnfe) {
  355. throw new BuildException("No JAXP compliant XML parser found. See http://java.sun.com/xml for the\nreference implementation.", cnfe);
  356. } catch (NullPointerException npe) {
  357. throw new BuildException("No JAXP compliant XML parser found. See http://java.sun.com/xml for the\nreference implementation.", npe);
  358. }
  359. // make sure that we have a target to execute
  360. if (targets.size() == 0) {
  361. targets.addElement(project.getDefaultTarget());
  362. }
  363. if (projectHelp) {
  364. printTargets(project);
  365. } else {
  366. // actually do some work
  367. project.executeTargets(targets);
  368. }
  369. }
  370. catch(RuntimeException exc) {
  371. error = exc;
  372. throw exc;
  373. }
  374. catch(Error err) {
  375. error = err;
  376. throw err;
  377. }
  378. finally {
  379. project.fireBuildFinished(error);
  380. }
  381. }
  382. protected void addBuildListeners(Project project) {
  383. // Add the default listener
  384. project.addBuildListener(createLogger());
  385. for (int i = 0; i < listeners.size(); i++) {
  386. String className = (String) listeners.elementAt(i);
  387. try {
  388. BuildListener listener =
  389. (BuildListener) Class.forName(className).newInstance();
  390. project.addBuildListener(listener);
  391. }
  392. catch(Exception exc) {
  393. throw new BuildException("Unable to instantiate listener " + className, exc);
  394. }
  395. }
  396. }
  397. /**
  398. * Creates the default build logger for sending build events to the ant log.
  399. */
  400. private BuildLogger createLogger() {
  401. BuildLogger logger = null;
  402. if (loggerClassname != null) {
  403. try {
  404. logger = (BuildLogger)(Class.forName(loggerClassname).newInstance());
  405. }
  406. catch (ClassCastException e) {
  407. System.err.println("The specified logger class " + loggerClassname +
  408. " does not implement the BuildLogger interface");
  409. throw new RuntimeException();
  410. }
  411. catch (Exception e) {
  412. System.err.println("Unable to instantiate specified logger class " +
  413. loggerClassname + " : " + e.getClass().getName());
  414. throw new RuntimeException();
  415. }
  416. }
  417. else {
  418. logger = new DefaultLogger();
  419. }
  420. logger.setMessageOutputLevel(msgOutputLevel);
  421. logger.setOutputPrintStream(out);
  422. logger.setErrorPrintStream(err);
  423. logger.setEmacsMode(emacsMode);
  424. return logger;
  425. }
  426. /**
  427. * Prints the usage of how to use this class to System.out
  428. */
  429. private static void printUsage() {
  430. String lSep = System.getProperty("line.separator");
  431. StringBuffer msg = new StringBuffer();
  432. msg.append("ant [options] [target [target2 [target3] ...]]" + lSep);
  433. msg.append("Options: " + lSep);
  434. msg.append(" -help print this message" + lSep);
  435. msg.append(" -projecthelp print project help information" + lSep);
  436. msg.append(" -version print the version information and exit" + lSep);
  437. msg.append(" -quiet be extra quiet" + lSep);
  438. msg.append(" -verbose be extra verbose" + lSep);
  439. msg.append(" -debug print debugging information" + lSep);
  440. msg.append(" -emacs produce logging information without adornments" + lSep);
  441. msg.append(" -logfile <file> use given file for log" + lSep);
  442. msg.append(" -logger <classname> the class which is to perform logging" + lSep);
  443. msg.append(" -listener <classname> add an instance of class as a project listener" + lSep);
  444. msg.append(" -buildfile <file> use given buildfile" + lSep);
  445. msg.append(" -D<property>=<value> use value for given property" + lSep);
  446. msg.append(" -find <file> search for buildfile towards the root of the" + lSep);
  447. msg.append(" filesystem and use it" + lSep);
  448. System.out.println(msg.toString());
  449. }
  450. private static void printVersion() {
  451. System.out.println( BANNER );
  452. System.out.println();
  453. }
  454. /**
  455. * Print out a list of all targets in the current buildfile
  456. */
  457. private static void printTargets(Project project) {
  458. // find the target with the longest name
  459. int maxLength = 0;
  460. Enumeration ptargets = project.getTargets().elements();
  461. String targetName;
  462. String targetDescription;
  463. Target currentTarget;
  464. // split the targets in top-level and sub-targets depending
  465. // on the presence of a description
  466. Vector topNames = new Vector();
  467. Vector topDescriptions = new Vector();
  468. Vector subNames = new Vector();
  469. while (ptargets.hasMoreElements()) {
  470. currentTarget = (Target)ptargets.nextElement();
  471. targetName = currentTarget.getName();
  472. targetDescription = currentTarget.getDescription();
  473. // maintain a sorted list of targets
  474. if (targetDescription == null) {
  475. int pos = findTargetPosition(subNames, targetName);
  476. subNames.insertElementAt(targetName, pos);
  477. } else {
  478. int pos = findTargetPosition(topNames, targetName);
  479. topNames.insertElementAt(targetName, pos);
  480. topDescriptions.insertElementAt(targetDescription, pos);
  481. if (targetName.length() > maxLength) {
  482. maxLength = targetName.length();
  483. }
  484. }
  485. }
  486. printTargets(topNames, topDescriptions, "Main targets:", maxLength);
  487. printTargets(subNames, null, "Subtargets:", 0);
  488. }
  489. /**
  490. * Search for the insert position to keep names a sorted list of Strings
  491. */
  492. private static int findTargetPosition(Vector names, String name) {
  493. int res = names.size();
  494. for (int i=0; i<names.size() && res == names.size(); i++) {
  495. if (name.compareTo((String)names.elementAt(i)) < 0) {
  496. res = i;
  497. }
  498. }
  499. return res;
  500. }
  501. /**
  502. * Output a formatted list of target names with an optional description
  503. */
  504. private static void printTargets(Vector names, Vector descriptions, String heading, int maxlen) {
  505. // now, start printing the targets and their descriptions
  506. String lSep = System.getProperty("line.separator");
  507. // got a bit annoyed that I couldn't find a pad function
  508. String spaces = " ";
  509. while (spaces.length()<maxlen) {
  510. spaces += spaces;
  511. }
  512. StringBuffer msg = new StringBuffer();
  513. msg.append(heading + lSep + lSep);
  514. for (int i=0; i<names.size(); i++) {
  515. msg.append(" ");
  516. msg.append(names.elementAt(i));
  517. if (descriptions != null) {
  518. msg.append(spaces.substring(0, maxlen - ((String)names.elementAt(i)).length() + 2));
  519. msg.append(descriptions.elementAt(i));
  520. }
  521. msg.append(lSep);
  522. }
  523. System.out.println(msg.toString());
  524. }
  525. }