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

Main.java 29KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800
  1. /* *******************************************************************
  2. * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
  3. * All rights reserved.
  4. * This program and the accompanying materials are made available
  5. * under the terms of the Common Public License v1.0
  6. * which accompanies this distribution and is available at
  7. * http://www.eclipse.org/legal/cpl-v10.html
  8. *
  9. * Contributors:
  10. * PARC initial implementation
  11. * ******************************************************************/
  12. package org.aspectj.tools.ajc;
  13. import java.io.File;
  14. import java.io.FileOutputStream;
  15. import java.io.IOException;
  16. import java.io.PrintStream;
  17. import java.util.Arrays;
  18. import java.util.List;
  19. import java.util.Date;
  20. import org.aspectj.bridge.AbortException;
  21. import org.aspectj.bridge.ICommand;
  22. import org.aspectj.bridge.IMessage;
  23. import org.aspectj.bridge.IMessageHandler;
  24. import org.aspectj.bridge.IMessageHolder;
  25. import org.aspectj.bridge.ISourceLocation;
  26. import org.aspectj.bridge.Message;
  27. import org.aspectj.bridge.MessageHandler;
  28. import org.aspectj.bridge.MessageUtil;
  29. import org.aspectj.bridge.ReflectionFactory;
  30. import org.aspectj.bridge.Version;
  31. import org.aspectj.bridge.context.CompilationAndWeavingContext;
  32. import org.aspectj.util.FileUtil;
  33. import org.aspectj.util.LangUtil;
  34. /**
  35. * Programmatic and command-line interface to AspectJ compiler.
  36. * The compiler is an ICommand obtained by reflection.
  37. * Not thread-safe.
  38. * By default, messages are printed as they are emitted;
  39. * info messages go to the output stream, and
  40. * warnings and errors go to the error stream.
  41. * <p>
  42. * Clients can handle all messages by registering a holder:
  43. * <pre>Main main = new Main();
  44. * IMessageHolder holder = new MessageHandler();
  45. * main.setHolder(holder);</pre>
  46. * Clients can get control after each command completes
  47. * by installing a Runnable:
  48. * <pre>main.setCompletionRunner(new Runnable() {..});</pre>
  49. *
  50. */
  51. public class Main {
  52. /** Header used when rendering exceptions for users */
  53. public static final String THROWN_PREFIX
  54. = "Exception thrown from AspectJ "+ Version.text + LangUtil.EOL
  55. + ""+ LangUtil.EOL
  56. + "This might be logged as a bug already -- find current bugs at" + LangUtil.EOL
  57. + " http://bugs.eclipse.org/bugs/buglist.cgi?product=AspectJ&component=Compiler" + LangUtil.EOL
  58. + "" + LangUtil.EOL
  59. + "Bugs for exceptions thrown have titles File:line from the top stack, " + LangUtil.EOL
  60. + "e.g., \"SomeFile.java:243\"" + LangUtil.EOL
  61. + "" + LangUtil.EOL
  62. + "If you don't find the exception below in a bug, please add a new bug" + LangUtil.EOL
  63. + "at http://bugs.eclipse.org/bugs/enter_bug.cgi?product=AspectJ" + LangUtil.EOL
  64. + "To make the bug a priority, please include a test program" + LangUtil.EOL
  65. + "that can reproduce this exception." + LangUtil.EOL;
  66. private static final String OUT_OF_MEMORY_MSG
  67. = "AspectJ " + Version.text + " ran out of memory during compilation:" + LangUtil.EOL + LangUtil.EOL
  68. + "Please increase the memory available to ajc by editing the ajc script " + LangUtil.EOL
  69. + "found in your AspectJ installation directory. The -Xmx parameter value" + LangUtil.EOL
  70. + "should be increased from 64M (default) to 128M or even 256M." + LangUtil.EOL + LangUtil.EOL
  71. + "See the AspectJ FAQ available from the documentation link" + LangUtil.EOL
  72. + "on the AspectJ home page at http://www.eclipse.org/aspectj";
  73. /** @param args the String[] of command-line arguments */
  74. public static void main(String[] args) throws IOException {
  75. new Main().runMain(args, true);
  76. }
  77. /**
  78. * Convenience method to run ajc and collect String lists of messages.
  79. * This can be reflectively invoked with the
  80. * List collecting parameters supplied by a parent class loader.
  81. * The String messages take the same form as command-line messages.
  82. * @param args the String[] args to pass to the compiler
  83. * @param useSystemExit if true and errors, return System.exit(errs)
  84. * @param fails the List sink, if any, for String failure (or worse) messages
  85. * @param errors the List sink, if any, for String error messages
  86. * @param warnings the List sink, if any, for String warning messages
  87. * @param info the List sink, if any, for String info messages
  88. * @return number of messages reported with level ERROR or above
  89. * @throws any unchecked exceptions the compiler does
  90. */
  91. public static int bareMain(
  92. String[] args,
  93. boolean useSystemExit,
  94. List fails,
  95. List errors,
  96. List warnings,
  97. List infos) {
  98. Main main = new Main();
  99. MessageHandler holder = new MessageHandler();
  100. main.setHolder(holder);
  101. try {
  102. main.runMain(args, useSystemExit);
  103. } finally {
  104. readMessages(holder, IMessage.FAIL, true, fails);
  105. readMessages(holder, IMessage.ERROR, false, errors);
  106. readMessages(holder, IMessage.WARNING, false, warnings);
  107. readMessages(holder, IMessage.INFO, false, infos);
  108. }
  109. return holder.numMessages(IMessage.ERROR, true);
  110. }
  111. /** Read messages of a given kind into a List as String */
  112. private static void readMessages(
  113. IMessageHolder holder,
  114. IMessage.Kind kind,
  115. boolean orGreater,
  116. List sink) {
  117. if ((null == sink) || (null == holder)) {
  118. return;
  119. }
  120. IMessage[] messages = holder.getMessages(kind, orGreater);
  121. if (!LangUtil.isEmpty(messages)) {
  122. for (int i = 0; i < messages.length; i++) {
  123. sink.add(MessagePrinter.render(messages[i]));
  124. }
  125. }
  126. }
  127. /**
  128. * @return String rendering throwable as compiler error for user/console,
  129. * including information on how to report as a bug.
  130. * @throws NullPointerException if thrown is null
  131. */
  132. public static String renderExceptionForUser(Throwable thrown) {
  133. String m = thrown.getMessage();
  134. return THROWN_PREFIX
  135. + (null != m ? m + "\n": "")
  136. + CompilationAndWeavingContext.getCurrentContext()
  137. + LangUtil.renderException(thrown, true);
  138. }
  139. private static String parmInArgs(String flag, String[] args) {
  140. int loc = 1+(null == args ? -1 :Arrays.asList(args).indexOf(flag));
  141. return ((0 == loc) || (args.length <= loc)?null:args[loc]);
  142. }
  143. private static boolean flagInArgs(String flag, String[] args) {
  144. return ((null != args) && (Arrays.asList(args).indexOf(flag) != -1));
  145. }
  146. /** append nothing if numItems is 0,
  147. * numItems + label + (numItems > 1? "s" : "") otherwise,
  148. * prefixing with " " if sink has content
  149. */
  150. private static void appendNLabel(StringBuffer sink, String label, int numItems) {
  151. if (0 == numItems) {
  152. return;
  153. }
  154. if (0 < sink.length()) {
  155. sink.append(", ");
  156. }
  157. sink.append(numItems + " ");
  158. if (!LangUtil.isEmpty(label)) {
  159. sink.append(label);
  160. }
  161. if (1 < numItems) {
  162. sink.append("s");
  163. }
  164. }
  165. /** control iteration/continuation for command (compiler) */
  166. protected CommandController controller;
  167. /** ReflectionFactory identifier for command (compiler) */
  168. protected String commandName;
  169. /** client-set message sink */
  170. private IMessageHolder clientHolder;
  171. /** internally-set message sink */
  172. protected final MessageHandler ourHandler;
  173. private int lastFails;
  174. private int lastErrors;
  175. /** if not null, run this synchronously after each compile completes */
  176. private Runnable completionRunner;
  177. public Main() {
  178. controller = new CommandController();
  179. commandName = ReflectionFactory.ECLIPSE;
  180. ourHandler = new MessageHandler(true);
  181. }
  182. public MessageHandler getMessageHandler() {
  183. return ourHandler;
  184. }
  185. // for unit testing...
  186. void setController(CommandController controller) {
  187. this.controller = controller;
  188. }
  189. /**
  190. * Run without throwing exceptions but optionally using System.exit(..).
  191. * This sets up a message handler which emits messages immediately,
  192. * so report(boolean, IMessageHandler) only reports total number
  193. * of errors or warnings.
  194. * @param args the String[] command line for the compiler
  195. * @param useSystemExit if true, use System.exit(int) to complete
  196. * unless one of the args is -noExit.
  197. * and signal result (0 no exceptions/error, <0 exceptions, >0 compiler errors).
  198. */
  199. public void runMain(String[] args, boolean useSystemExit) {
  200. final boolean verbose = flagInArgs("-verbose", args);
  201. IMessageHolder holder = clientHolder;
  202. if (null == holder) {
  203. holder = ourHandler;
  204. if (verbose) {
  205. ourHandler.setInterceptor(MessagePrinter.VERBOSE);
  206. } else {
  207. ourHandler.ignore(IMessage.INFO);
  208. ourHandler.setInterceptor(MessagePrinter.TERSE);
  209. }
  210. }
  211. // make sure we handle out of memory gracefully...
  212. try {
  213. // byte[] b = new byte[100000000]; for testing OoME only!
  214. run(args, holder);
  215. } catch (OutOfMemoryError outOfMemory) {
  216. IMessage outOfMemoryMessage = new Message(OUT_OF_MEMORY_MSG,null,true);
  217. holder.handleMessage(outOfMemoryMessage);
  218. systemExit(holder); // we can't reasonably continue from this point.
  219. }
  220. boolean skipExit = false;
  221. if (useSystemExit && !LangUtil.isEmpty(args)) { // sigh - pluck -noExit
  222. for (int i = 0; i < args.length; i++) {
  223. if ("-noExit".equals(args[i])) {
  224. skipExit = true;
  225. break;
  226. }
  227. }
  228. }
  229. if (useSystemExit && !skipExit) {
  230. systemExit(holder);
  231. }
  232. }
  233. /**
  234. * Run without using System.exit(..), putting all messages in holder:
  235. * <ul>
  236. * <li>ERROR: compiler error</li>
  237. * <li>WARNING: compiler warning</li>
  238. * <li>FAIL: command error (bad arguments, exception thrown)</li>
  239. * </ul>
  240. * This handles incremental behavior:
  241. * <ul>
  242. * <li>If args include "-incremental", repeat for every input char
  243. * until 'q' is entered.<li>
  244. * <li>If args include "-incrementalTagFile {file}", repeat every time
  245. * we detect that {file} modification time has changed. </li>
  246. * <li>Either way, list files recompiled each time if args includes "-verbose".</li>
  247. * <li>Exit when the commmand/compiler throws any Throwable.</li>
  248. * </ul>
  249. * When complete, this contains all the messages of the final
  250. * run of the command and/or any FAIL messages produced in running
  251. * the command, including any Throwable thrown by the command itself.
  252. *
  253. * @param args the String[] command line for the compiler
  254. * @param holder the MessageHandler sink for messages.
  255. */
  256. public void run(String[] args, IMessageHolder holder) {
  257. PrintStream logStream = null;
  258. FileOutputStream fos = null;
  259. String logFileName = parmInArgs("-log", args);
  260. if (null != logFileName){
  261. File logFile = new File(logFileName);
  262. try{
  263. logFile.createNewFile();
  264. fos = new FileOutputStream(logFileName, true);
  265. logStream = new PrintStream(fos,true);
  266. } catch(Exception e){
  267. fail(holder, "Couldn't open log file: " + logFileName, e);
  268. }
  269. Date now = new Date();
  270. logStream.println(now.toString());
  271. if (flagInArgs("-verbose", args)) {
  272. ourHandler.setInterceptor(new LogModeMessagePrinter(true,logStream));
  273. } else {
  274. ourHandler.ignore(IMessage.INFO);
  275. ourHandler.setInterceptor(new LogModeMessagePrinter(false,logStream));
  276. }
  277. holder = ourHandler;
  278. }
  279. if (LangUtil.isEmpty(args)) {
  280. args = new String[] { "-?" };
  281. } else if (controller.running()) {
  282. fail(holder, "already running with controller: " + controller, null);
  283. return;
  284. }
  285. args = controller.init(args, holder);
  286. if (0 < holder.numMessages(IMessage.ERROR, true)) {
  287. return;
  288. }
  289. ICommand command = ReflectionFactory.makeCommand(commandName, holder);
  290. if (0 < holder.numMessages(IMessage.ERROR, true)) {
  291. return;
  292. }
  293. try {
  294. outer:
  295. while (true) {
  296. boolean passed = command.runCommand(args, holder);
  297. if (report(passed, holder) && controller.incremental()) {
  298. while (controller.doRepeatCommand(command)) {
  299. holder.clearMessages();
  300. if (controller.buildFresh()) {
  301. continue outer;
  302. } else {
  303. passed = command.repeatCommand(holder);
  304. }
  305. if (!report(passed, holder)) {
  306. break;
  307. }
  308. }
  309. }
  310. break;
  311. }
  312. } catch (AbortException ae) {
  313. if (ae.isSilent()) {
  314. quit();
  315. } else {
  316. IMessage message = ae.getIMessage();
  317. Throwable thrown = ae.getThrown();
  318. if (null == thrown) { // toss AbortException wrapper
  319. if (null != message) {
  320. holder.handleMessage(message);
  321. } else {
  322. fail(holder, "abort without message", ae);
  323. }
  324. } else if (null == message) {
  325. fail(holder, "aborted", thrown);
  326. } else {
  327. String mssg = MessageUtil.MESSAGE_MOST.renderToString(message);
  328. fail(holder, mssg, thrown);
  329. }
  330. }
  331. } catch (Throwable t) {
  332. fail(holder, "unexpected exception", t);
  333. } finally{
  334. if (logStream != null){
  335. logStream.close();
  336. logStream = null;
  337. }
  338. if (fos != null){
  339. try {
  340. fos.close();
  341. } catch (IOException e){
  342. fail(holder, "unexpected exception", e);
  343. }
  344. fos = null;
  345. }
  346. }
  347. }
  348. /** call this to stop after the next iteration of incremental compile */
  349. public void quit() {
  350. controller.quit();
  351. }
  352. /**
  353. * Set holder to be passed all messages.
  354. * When holder is set, messages will not be printed by default.
  355. * @param holder the IMessageHolder sink for all messages
  356. * (use null to restore default behavior)
  357. */
  358. public void setHolder(IMessageHolder holder) {
  359. clientHolder = holder;
  360. }
  361. /**
  362. * Install a Runnable to be invoked synchronously
  363. * after each compile completes.
  364. * @param runner the Runnable to invoke - null to disable
  365. */
  366. public void setCompletionRunner(Runnable runner) {
  367. this.completionRunner = runner;
  368. }
  369. /**
  370. * Call System.exit(int) with values derived from the number
  371. * of failures/aborts or errors in messages.
  372. * @param messages the IMessageHolder to interrogate.
  373. * @param messages
  374. */
  375. protected void systemExit(IMessageHolder messages) {
  376. int num = lastFails; // messages.numMessages(IMessage.FAIL, true);
  377. if (0 < num) {
  378. System.exit(-num);
  379. }
  380. num = lastErrors; // messages.numMessages(IMessage.ERROR, false);
  381. if (0 < num) {
  382. System.exit(num);
  383. }
  384. System.exit(0);
  385. }
  386. /** Messages to the user */
  387. protected void outMessage(String message) { // XXX coordinate with MessagePrinter
  388. System.out.print(message);
  389. System.out.flush();
  390. }
  391. /**
  392. * Report results from a (possibly-incremental) compile run.
  393. * This delegates to any reportHandler or otherwise
  394. * prints summary counts of errors/warnings to System.err (if any errors)
  395. * or System.out (if only warnings).
  396. * WARNING: this silently ignores other messages like FAIL,
  397. * but clears the handler of all messages when returning true. XXX false
  398. *
  399. * This implementation ignores the pass parameter but
  400. * clears the holder after reporting
  401. * on the assumption messages were handled/printed already.
  402. * (ignoring UnsupportedOperationException from holder.clearMessages()).
  403. * @param pass true result of the command
  404. * @param holder IMessageHolder with messages from the command
  405. * @see reportCommandResults(IMessageHolder)
  406. * @return false if the process should abort
  407. */
  408. protected boolean report(boolean pass, IMessageHolder holder) {
  409. lastFails = holder.numMessages(IMessage.FAIL, true);
  410. boolean result = (0 == lastFails);
  411. final Runnable runner = completionRunner;
  412. if (null != runner) {
  413. runner.run();
  414. }
  415. if (holder == ourHandler) {
  416. lastErrors = holder.numMessages(IMessage.ERROR, false);
  417. int warnings = holder.numMessages(IMessage.WARNING, false);
  418. StringBuffer sb = new StringBuffer();
  419. appendNLabel(sb, "fail|abort", lastFails);
  420. appendNLabel(sb, "error", lastErrors);
  421. appendNLabel(sb, "warning", warnings);
  422. if (0 < sb.length()) {
  423. PrintStream out = (0 < (lastErrors + lastFails)
  424. ? System.err
  425. : System.out);
  426. out.println(""); // XXX "wrote class file" messages no eol?
  427. out.println(sb.toString());
  428. }
  429. }
  430. return result;
  431. }
  432. /** convenience API to make fail messages (without MessageUtils's fail prefix) */
  433. protected static void fail(IMessageHandler handler, String message, Throwable thrown) {
  434. handler.handleMessage(new Message(message, IMessage.FAIL, thrown, null));
  435. }
  436. /**
  437. * interceptor IMessageHandler to print as we go.
  438. * This formats all messages to the user.
  439. */
  440. public static class MessagePrinter implements IMessageHandler {
  441. public static final IMessageHandler VERBOSE
  442. = new MessagePrinter(true);
  443. public static final IMessageHandler TERSE
  444. = new MessagePrinter(false);
  445. final boolean verbose;
  446. protected MessagePrinter(boolean verbose) {
  447. this.verbose = verbose;
  448. }
  449. /**
  450. * Print errors and warnings to System.err,
  451. * and optionally info to System.out,
  452. * rendering message String only.
  453. * @return false always
  454. */
  455. public boolean handleMessage(IMessage message) {
  456. if (null != message) {
  457. PrintStream out = getStreamFor(message.getKind());
  458. if (null != out) {
  459. out.println(render(message));
  460. }
  461. }
  462. return false;
  463. }
  464. /**
  465. * Render message differently.
  466. * If abort, then prefix stack trace with feedback request.
  467. * If the actual message is empty, then use toString on the whole.
  468. * Prefix message part with file:line;
  469. * If it has context, suffix message with context.
  470. * @param message the IMessage to render
  471. * @return String rendering IMessage (never null)
  472. */
  473. public static String render(IMessage message) {
  474. // IMessage.Kind kind = message.getKind();
  475. StringBuffer sb = new StringBuffer();
  476. String text = message.getMessage();
  477. if (text.equals(AbortException.NO_MESSAGE_TEXT)) {
  478. text = null;
  479. }
  480. boolean toString = (LangUtil.isEmpty(text));
  481. if (toString) {
  482. text = message.toString();
  483. }
  484. ISourceLocation loc = message.getSourceLocation();
  485. String context = null;
  486. if (null != loc) {
  487. File file = loc.getSourceFile();
  488. if (null != file) {
  489. String name = file.getName();
  490. if (!toString || (-1 == text.indexOf(name))) {
  491. sb.append(FileUtil.getBestPath(file));
  492. if (loc.getLine() > 0) {
  493. sb.append(":" + loc.getLine());
  494. }
  495. int col = loc.getColumn();
  496. if (0 < col) {
  497. sb.append(":" + col);
  498. }
  499. sb.append(" ");
  500. }
  501. }
  502. context = loc.getContext();
  503. }
  504. // per Wes' suggestion on dev...
  505. if (message.getKind() == IMessage.ERROR) {
  506. sb.append("[error] ");
  507. } else if (message.getKind() == IMessage.WARNING) {
  508. sb.append("[warning] ");
  509. }
  510. sb.append(text);
  511. if (null != context) {
  512. sb.append(LangUtil.EOL);
  513. sb.append(context);
  514. }
  515. String details = message.getDetails();
  516. if (details != null) {
  517. sb.append(LangUtil.EOL);
  518. sb.append('\t');
  519. sb.append(details);
  520. }
  521. Throwable thrown = message.getThrown();
  522. if (null != thrown) {
  523. sb.append(LangUtil.EOL);
  524. sb.append(Main.renderExceptionForUser(thrown));
  525. }
  526. if (message.getExtraSourceLocations().isEmpty()) {
  527. return sb.toString();
  528. } else {
  529. return MessageUtil.addExtraSourceLocations(message, sb.toString());
  530. }
  531. }
  532. public boolean isIgnoring(IMessage.Kind kind) {
  533. return (null != getStreamFor(kind));
  534. }
  535. /**
  536. * No-op
  537. * @see org.aspectj.bridge.IMessageHandler#isIgnoring(org.aspectj.bridge.IMessage.Kind)
  538. * @param kind
  539. */
  540. public void dontIgnore(IMessage.Kind kind) {
  541. ;
  542. }
  543. /** @return System.err for FAIL, ABORT, ERROR, and WARNING,
  544. * System.out for INFO if -verbose and WEAVEINFO if -showWeaveInfo.
  545. */
  546. protected PrintStream getStreamFor(IMessage.Kind kind) {
  547. if (IMessage.WARNING.isSameOrLessThan(kind)) {
  548. return System.err;
  549. } else if (verbose && IMessage.INFO.equals(kind)) {
  550. return System.out;
  551. } else if (IMessage.WEAVEINFO.equals(kind)) {
  552. return System.out;
  553. } else {
  554. return null;
  555. }
  556. }
  557. }
  558. public static class LogModeMessagePrinter extends MessagePrinter {
  559. protected final PrintStream logStream;
  560. public LogModeMessagePrinter(boolean verbose, PrintStream logStream) {
  561. super(verbose);
  562. this.logStream = logStream;
  563. }
  564. protected PrintStream getStreamFor(IMessage.Kind kind) {
  565. if (IMessage.WARNING.isSameOrLessThan(kind)) {
  566. return logStream;
  567. } else if (verbose && IMessage.INFO.equals(kind)) {
  568. return logStream;
  569. } else if (IMessage.WEAVEINFO.equals(kind)) {
  570. return logStream;
  571. } else {
  572. return null;
  573. }
  574. }
  575. }
  576. /** controller for repeatable command delays until input or file changed or removed */
  577. public static class CommandController {
  578. public static String TAG_FILE_OPTION = "-XincrementalFile";
  579. public static String INCREMENTAL_OPTION = "-incremental";
  580. /** maximum 10-minute delay between filesystem checks */
  581. public static long MAX_DELAY = 1000 * 600;
  582. /** default 5-second delay between filesystem checks */
  583. public static long DEFAULT_DELAY = 1000 * 5;
  584. /** @see init(String[]) */
  585. private static String[][] OPTIONS = new String[][]
  586. { new String[] { INCREMENTAL_OPTION },
  587. new String[] { TAG_FILE_OPTION, null } };
  588. /** true between init(String[]) and doRepeatCommand() that returns false */
  589. private boolean running;
  590. /** true after quit() called */
  591. private boolean quit;
  592. /** true if incremental mode, waiting for input other than 'q' */
  593. private boolean incremental;
  594. /** true if incremental mode, waiting for file to change (repeat) or disappear (quit) */
  595. private File tagFile;
  596. /** last modification time for tagFile as of last command - 0 to start */
  597. private long fileModTime;
  598. /** delay between filesystem checks for tagFile modification time */
  599. private long delay;
  600. /** true just after user types 'r' for rebuild */
  601. private boolean buildFresh;
  602. public CommandController() {
  603. delay = DEFAULT_DELAY;
  604. }
  605. /**
  606. * @param argList read and strip incremental args from this
  607. * @param sink IMessageHandler for error messages
  608. * @return String[] remainder of args
  609. */
  610. public String[] init(String[] args, IMessageHandler sink) {
  611. running = true;
  612. // String[] unused;
  613. if (!LangUtil.isEmpty(args)) {
  614. String[][] options = LangUtil.copyStrings(OPTIONS);
  615. /*unused = */LangUtil.extractOptions(args, options);
  616. incremental = (null != options[0][0]);
  617. if (null != options[1][0]) {
  618. File file = new File(options[1][1]);
  619. if (!file.exists()) {
  620. MessageUtil.abort(sink, "tag file does not exist: " + file);
  621. } else {
  622. tagFile = file;
  623. fileModTime = tagFile.lastModified();
  624. }
  625. }
  626. }
  627. return args;
  628. }
  629. /** @return true if init(String[]) called but doRepeatCommand has not
  630. * returned false */
  631. public boolean running() {
  632. return running;
  633. }
  634. /** @param delay milliseconds between filesystem checks */
  635. public void setDelay(long delay) {
  636. if ((delay > -1) && (delay < MAX_DELAY)) {
  637. this.delay = delay;
  638. }
  639. }
  640. /** @return true if INCREMENTAL_OPTION or TAG_FILE_OPTION was in args */
  641. public boolean incremental() {
  642. return (incremental || (null != tagFile));
  643. }
  644. /** @return true if INCREMENTAL_OPTION was in args */
  645. public boolean commandLineIncremental() {
  646. return incremental;
  647. }
  648. public void quit() {
  649. if (!quit) {
  650. quit = true;
  651. }
  652. }
  653. /** @return true just after user typed 'r' */
  654. boolean buildFresh() {
  655. return buildFresh;
  656. }
  657. /** @return false if we should quit, true to do another command */
  658. boolean doRepeatCommand(ICommand command) {
  659. if (!running) {
  660. return false;
  661. }
  662. boolean result = false;
  663. if (quit) {
  664. result = false;
  665. } else if (incremental) {
  666. try {
  667. if (buildFresh) { // reset before input request
  668. buildFresh = false;
  669. }
  670. System.out.println(" press enter to recompile, r to rebuild, q to quit: ");
  671. System.out.flush();
  672. // boolean doMore = false;
  673. // seek for one q or a series of [\n\r]...
  674. do {
  675. int input = System.in.read();
  676. if ('q' == input) {
  677. break; // result = false;
  678. } else if ('r' == input) {
  679. buildFresh = true;
  680. result = true;
  681. } else if (('\n' == input) || ('\r' == input)) {
  682. result = true;
  683. } // else eat anything else
  684. } while (!result);
  685. System.in.skip(Integer.MAX_VALUE);
  686. } catch (IOException e) { // XXX silence for error?
  687. result = false;
  688. }
  689. } else if (null != tagFile) {
  690. long curModTime;
  691. while (true) {
  692. if (!tagFile.exists()) {
  693. result = false;
  694. break;
  695. } else if (fileModTime == (curModTime = tagFile.lastModified())) {
  696. fileCheckDelay();
  697. } else {
  698. fileModTime = curModTime;
  699. result = true;
  700. break;
  701. }
  702. }
  703. } // else, not incremental - false
  704. if (!result && running) {
  705. running = false;
  706. }
  707. return result;
  708. }
  709. /** delay between filesystem checks, returning if quit is set */
  710. protected void fileCheckDelay() {
  711. // final Thread thread = Thread.currentThread();
  712. long targetTime = System.currentTimeMillis() + delay;
  713. // long curTime;
  714. while (targetTime > System.currentTimeMillis()) {
  715. if (quit) {
  716. return;
  717. }
  718. try { Thread.sleep(300); } // 1/3-second delta for quit check
  719. catch (InterruptedException e) {}
  720. }
  721. }
  722. }
  723. }