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.

AntBuilder.java 27KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825
  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 Eclipse Public License v1.0
  6. * which accompanies this distribution and is available at
  7. * http://www.eclipse.org/legal/epl-v10.html
  8. *
  9. * Contributors:
  10. * Xerox/PARC initial implementation
  11. * ******************************************************************/
  12. package org.aspectj.internal.tools.ant.taskdefs;
  13. import java.io.File;
  14. import java.io.FileWriter;
  15. import java.io.IOException;
  16. import java.lang.reflect.Method;
  17. import java.net.URL;
  18. import java.net.URLClassLoader;
  19. import java.util.ArrayList;
  20. import java.util.Arrays;
  21. import java.util.Collection;
  22. import java.util.HashMap;
  23. import java.util.Hashtable;
  24. import java.util.Iterator;
  25. import java.util.List;
  26. import java.util.Map;
  27. import org.apache.tools.ant.BuildException;
  28. import org.apache.tools.ant.Project;
  29. import org.apache.tools.ant.Target;
  30. import org.apache.tools.ant.Task;
  31. import org.apache.tools.ant.taskdefs.Copy;
  32. import org.apache.tools.ant.taskdefs.Javac;
  33. import org.apache.tools.ant.taskdefs.Zip;
  34. import org.apache.tools.ant.types.FileSet;
  35. import org.apache.tools.ant.types.Path;
  36. import org.apache.tools.ant.types.ZipFileSet;
  37. import org.aspectj.internal.tools.build.BuildSpec;
  38. import org.aspectj.internal.tools.build.Builder;
  39. import org.aspectj.internal.tools.build.Messager;
  40. import org.aspectj.internal.tools.build.Module;
  41. import org.aspectj.internal.tools.build.Result;
  42. import org.aspectj.internal.tools.build.Util;
  43. /**
  44. * Implement Builder in Ant.
  45. */
  46. public class AntBuilder extends Builder {
  47. private static final boolean FORCE_FORK_FOR_LIBRARIES = false;
  48. /**
  49. * Factory for a Builder.
  50. *
  51. * @param config the String configuration, where only substrings "verbose" and "useEclipseCompiles" are significant
  52. * @param project the owning Project for all tasks (not null)
  53. * @param tempDir the File path to a temporary dir for side effects (may be null)
  54. * @return a Builder for this project and configuration
  55. */
  56. public static Builder getBuilder(String config, Project project, File tempDir) {
  57. boolean useEclipseCompiles = false;
  58. boolean verbose = false;
  59. if (null != config) {
  60. if (-1 != config.indexOf("useEclipseCompiles")) {
  61. useEclipseCompiles = true;
  62. }
  63. if (-1 != config.indexOf("verbose")) {
  64. verbose = true;
  65. }
  66. }
  67. // Messager handler = new Messager(); // debugging
  68. Messager handler = new ProjectMessager(project);
  69. Builder result = new ProductBuilder(project, tempDir, useEclipseCompiles, handler);
  70. if (verbose) {
  71. result.setVerbose(true);
  72. }
  73. return result;
  74. }
  75. private static String resultToTargetName(Result result) {
  76. return result.getName();
  77. }
  78. /**
  79. * Ensure targets exist for this module and all antecedants, so topoSort can work.
  80. */
  81. private static void makeTargetsForResult(final Result result, final Hashtable<String,Target> targets) {
  82. final String resultTargetName = resultToTargetName(result);
  83. Target target = (Target) targets.get(resultTargetName);
  84. if (null == target) {
  85. // first add the target
  86. target = new Target();
  87. target.setName(resultTargetName);
  88. Result[] reqs = result.getRequired();
  89. StringBuffer depends = new StringBuffer();
  90. boolean first = true;
  91. for (int i = 0; i < reqs.length; i++) {
  92. Result reqResult = reqs[i];
  93. if (!first) {
  94. depends.append(",");
  95. } else {
  96. first = false;
  97. }
  98. depends.append(resultToTargetName(reqResult));
  99. }
  100. if (0 < depends.length()) {
  101. target.setDepends(depends.toString());
  102. }
  103. targets.put(resultTargetName, target);
  104. // then recursively add any required results
  105. for (int i = 0; i < reqs.length; i++) {
  106. Result reqResult = reqs[i];
  107. makeTargetsForResult(reqResult, targets);
  108. }
  109. }
  110. }
  111. private final Project project;
  112. protected AntBuilder(Project project, File tempDir, boolean useEclipseCompiles, Messager handler) {
  113. super(tempDir, useEclipseCompiles, handler);
  114. this.project = project;
  115. Util.iaxIfNull(project, "project");
  116. }
  117. /**
  118. * Initialize task with project and "ajbuild-" + name as name. (Using bm- prefix distinguishes these tasks from tasks found in
  119. * the build script.)
  120. *
  121. * @param task the Task to initialize - not null
  122. * @param name the String name suffix for the task
  123. * @return true unless some error
  124. */
  125. protected boolean setupTask(Task task, String name) {
  126. task.setProject(project);
  127. task.setTaskName("ajbuild-" + name);
  128. return true;
  129. }
  130. /**
  131. * Copy file, optionally filtering. (Filters set in project.)
  132. *
  133. * @param fromFile the readable File source to copy
  134. * @param toFile the writable File destination file
  135. * @param boolean filter if true, enable filtering
  136. * @see org.aspectj.internal.tools.build.Builder#copyFile(File, File, boolean)
  137. */
  138. protected boolean copyFile(File fromFile, File toFile, boolean filter) {
  139. Copy copy = makeCopyTask(filter);
  140. copy.setFile(fromFile);
  141. copy.setTofile(toFile);
  142. executeTask(copy);
  143. return true;
  144. }
  145. /**
  146. * (Filters set in project.)
  147. *
  148. * @see org.aspectj.internal.tools.ant.taskdefs.Builder#copyFiles(File, File, String, String, boolean)
  149. */
  150. protected boolean copyFiles(File fromDir, File toDir, String includes, String excludes, boolean filter) {
  151. Copy copy = makeCopyTask(filter);
  152. copy.setTodir(toDir);
  153. FileSet fileset = new FileSet();
  154. fileset.setDir(fromDir);
  155. if (null != includes) {
  156. fileset.setIncludes(includes);
  157. }
  158. if (null != excludes) {
  159. fileset.setExcludes(excludes);
  160. }
  161. copy.addFileset(fileset);
  162. executeTask(copy);
  163. return false;
  164. }
  165. protected void copyFileset(File toDir, FileSet fileSet, boolean filter) {
  166. Copy copy = makeCopyTask(filter);
  167. copy.addFileset(fileSet);
  168. copy.setTodir(toDir);
  169. executeTask(copy);
  170. }
  171. /**
  172. * @param filter if FILTER_ON, use filters
  173. */
  174. protected Copy makeCopyTask(boolean filter) {
  175. Copy copy = new Copy();
  176. setupTask(copy, "copy");
  177. if (FILTER_ON == filter) {
  178. copy.setFiltering(true);
  179. }
  180. return copy;
  181. }
  182. protected void dumpMinFile(Result result, File classesDir, List<String> errors) {
  183. String name = result.getName() + "-empty";
  184. File minFile = new File(classesDir, name);
  185. FileWriter fw = null;
  186. try {
  187. fw = new FileWriter(minFile);
  188. fw.write(name);
  189. } catch (IOException e) {
  190. errors.add("IOException writing " + name + " to " + minFile + ": " + Util.renderException(e));
  191. } finally {
  192. Util.close(fw);
  193. }
  194. }
  195. @Override
  196. protected boolean compile(Result result, File classesDir, boolean useExistingClasses, List<String> errors) {
  197. if (!classesDir.exists() && !classesDir.mkdirs()) {
  198. errors.add("compile - unable to create " + classesDir);
  199. return false;
  200. }
  201. if (useExistingClasses) {
  202. return true;
  203. }
  204. // -- source paths
  205. Path path = new Path(project);
  206. boolean hasSourceDirectories = false;
  207. boolean isJava5Compile = false;
  208. boolean isJava8Compile = false;
  209. for (File file: result.getSrcDirs()) {
  210. // for (Iterator iter = result.getSrcDirs().iterator(); iter.hasNext();) {
  211. // File file = (File) iter.next();
  212. path.createPathElement().setLocation(file);
  213. if (!isJava5Compile
  214. && (Util.Constants.JAVA5_SRC.equals(file.getName()) ||
  215. Util.Constants.JAVA5_TESTSRC.equals(file.getName()) ||
  216. new File(file.getParent(), ".isJava5").exists())) {
  217. isJava5Compile = true;
  218. }
  219. if (new File(file.getParent(),".isJava8").exists()) {
  220. isJava8Compile = true;
  221. }
  222. if (!hasSourceDirectories) {
  223. hasSourceDirectories = true;
  224. }
  225. }
  226. if (!hasSourceDirectories) {
  227. return true; // nothing to compile - ok
  228. }
  229. // XXX test whether build.compiler property takes effect automatically
  230. // I suspect it requires the proper adapter setup.
  231. Javac javac = new Javac();
  232. setupTask(javac, "javac");
  233. javac.setIncludeantruntime(false);
  234. javac.setDestdir(classesDir);
  235. javac.setSrcdir(path);
  236. javac.setVerbose(verbose);
  237. path = null;
  238. // -- classpath
  239. Path classpath = new Path(project);
  240. boolean hasLibraries = setupClasspath(result, classpath);
  241. if (hasLibraries && FORCE_FORK_FOR_LIBRARIES) {
  242. javac.setFork(true); // otherwise never releases library jars
  243. // can we build under 1.4, but fork javac 1.5 compile?
  244. }
  245. // also fork if using 1.5?
  246. // -- set output directory
  247. classpath.createPathElement().setLocation(classesDir);
  248. javac.setClasspath(classpath);
  249. // misc
  250. javac.setDebug(true);
  251. if (!isJava5Compile) {
  252. javac.setTarget("1.1"); // 1.1 class files - Javac in 1.4 uses 1.4
  253. javac.setSource("1.3");
  254. } else {
  255. if (isJava8Compile) {
  256. javac.setSource("1.8");
  257. javac.setTarget("1.8");
  258. } else {
  259. javac.setSource("1.7");
  260. javac.setTarget("1.7");
  261. }
  262. }
  263. // compile
  264. boolean passed = false;
  265. BuildException failure = null;
  266. try {
  267. passed = executeTask(AspectJSupport.wrapIfNeeded(result, javac));
  268. } catch (BuildException e) {
  269. failure = e;
  270. } catch (Error e) {
  271. failure = new BuildException(e);
  272. } catch (RuntimeException e) {
  273. failure = new BuildException(e);
  274. } finally {
  275. if (!passed) {
  276. String args = "" + Arrays.asList(javac.getCurrentCompilerArgs());
  277. if ("[]".equals(args)) {
  278. args = "{" + result.toLongString() + "}";
  279. }
  280. String m = "BuildException compiling " + result.toLongString() + args
  281. + (null == failure ? "" : ": " + Util.renderException(failure));
  282. // debuglog System.err.println(m);
  283. errors.add(m);
  284. }
  285. javac.init(); // be nice to let go of classpath libraries...
  286. }
  287. return passed;
  288. }
  289. public boolean setupClasspath(Result result, Path classpath) { // XXX fix test access
  290. boolean hasLibraries = false;
  291. // required libraries
  292. for (Iterator iter = result.getLibJars().iterator(); iter.hasNext();) {
  293. File file = (File) iter.next();
  294. classpath.createPathElement().setLocation(file);
  295. if (!hasLibraries) {
  296. hasLibraries = true;
  297. }
  298. }
  299. // Westodo Kind kind = result.getKind();
  300. Result[] reqs = result.getRequired();
  301. // required modules and their exported libraries
  302. for (int i = 0; i < reqs.length; i++) {
  303. Result requiredResult = reqs[i];
  304. classpath.createPathElement().setLocation(requiredResult.getOutputFile());
  305. if (!hasLibraries) {
  306. hasLibraries = true;
  307. }
  308. // also put on classpath libraries exported from required module
  309. // XXX exported modules not supported
  310. for (Iterator iterator = requiredResult.getExportedLibJars().iterator(); iterator.hasNext();) {
  311. classpath.createPathElement().setLocation((File) iterator.next());
  312. }
  313. }
  314. return hasLibraries;
  315. }
  316. /**
  317. * Merge classes directory and any merge jars into module jar with any specified manifest file. META-INF directories are
  318. * excluded.
  319. */
  320. @Override
  321. protected boolean assemble(Result result, File classesDir, List<String> errors) {
  322. if (!buildingEnabled) {
  323. return false;
  324. }
  325. if (!result.outOfDate()) {
  326. return true;
  327. }
  328. // ---- zip result up
  329. Zip zip = new Zip();
  330. setupTask(zip, "zip");
  331. zip.setDestFile(result.getOutputFile());
  332. ZipFileSet zipfileset = null;
  333. // -- merge any resources in any of the src directories
  334. for (Iterator iter = result.getSrcDirs().iterator(); iter.hasNext();) {
  335. File srcDir = (File) iter.next();
  336. zipfileset = new ZipFileSet();
  337. zipfileset.setProject(project);
  338. zipfileset.setDir(srcDir);
  339. zipfileset.setIncludes(RESOURCE_PATTERN);
  340. zip.addZipfileset(zipfileset);
  341. }
  342. final Module module = result.getModule();
  343. File metaInfDir = new File(classesDir, "META-INF");
  344. Util.deleteContents(metaInfDir);
  345. // -- manifest
  346. File manifest = new File(module.moduleDir, module.name + ".mf.txt"); // XXXFileLiteral
  347. if (Util.canReadFile(manifest)) {
  348. if (Util.canReadDir(metaInfDir) || metaInfDir.mkdirs()) {
  349. // Jar spec requires a MANIFEST.MF not a manifest.mf
  350. copyFile(manifest, new File(metaInfDir, "MANIFEST.MF"), FILTER_ON); // XXXFileLiteral
  351. } else {
  352. errors.add("have manifest, but unable to create " + metaInfDir);
  353. return false;
  354. }
  355. }
  356. zipfileset = new ZipFileSet();
  357. zipfileset.setProject(project);
  358. zipfileset.setDir(classesDir);
  359. zipfileset.setIncludes("**/*");
  360. zip.addZipfileset(zipfileset);
  361. File[] contents = classesDir.listFiles();
  362. if ((null == contents) || (0 == contents.length)) {
  363. // *something* to zip up
  364. dumpMinFile(result, classesDir, errors);
  365. }
  366. try {
  367. handler.log("assemble " + module + " in " + result.getOutputFile());
  368. return executeTask(zip)
  369. // zip returns true when it doesn't create zipfile
  370. // because there are no entries to add, so verify done
  371. && Util.canReadFile(result.getOutputFile());
  372. } catch (BuildException e) {
  373. errors.add("BuildException zipping " + module + ": " + e.getMessage());
  374. return false;
  375. } finally {
  376. result.clearOutOfDate();
  377. }
  378. }
  379. /**
  380. * @see org.aspectj.internal.tools.build.Builder#buildAntecedants(Module)
  381. */
  382. protected Result[] getAntecedantResults(Result moduleResult) {
  383. Hashtable<String,Target> targets = new Hashtable<>();
  384. makeTargetsForResult(moduleResult, targets);
  385. String targetName = resultToTargetName(moduleResult);
  386. // bug: doc says topoSort returns String, but returns Target
  387. Collection<Target> result = project.topoSort(targetName, targets);
  388. // fyi, we don't rely on topoSort to detect cycles - see buildAll
  389. int size = result.size();
  390. if (0 == result.size()) {
  391. return new Result[0];
  392. }
  393. ArrayList<String> toReturn = new ArrayList<>();
  394. for (Iterator<Target> iter = result.iterator(); iter.hasNext();) {
  395. Target target = (Target) iter.next();
  396. String name = target.getName();
  397. if (null == name) {
  398. throw new Error("null name?");
  399. } else {
  400. toReturn.add(name);
  401. }
  402. }
  403. // topoSort always returns target name
  404. if ((1 == size) && targetName.equals(toReturn.get(0)) && !moduleResult.outOfDate()) {
  405. return new Result[0];
  406. }
  407. return Result.getResults((String[]) toReturn.toArray(new String[0]));
  408. }
  409. /**
  410. * Generate Module.assembledJar with merge of itself and all antecedants
  411. */
  412. protected boolean assembleAll(Result result, Messager handler) {
  413. if (!buildingEnabled) {
  414. return false;
  415. }
  416. if (!result.outOfDate()) {
  417. return true;
  418. }
  419. Util.iaxIfNull(result, "result");
  420. Util.iaxIfNull(handler, "handler");
  421. if (!result.getKind().isAssembly()) {
  422. throw new IllegalStateException("not assembly: " + result);
  423. }
  424. // ---- zip result up
  425. Zip zip = new Zip();
  426. setupTask(zip, "zip");
  427. zip.setDestFile(result.getOutputFile());
  428. ZipFileSet zipfileset = null;
  429. final Module module = result.getModule();
  430. List<File> known = result.findJarRequirements();
  431. removeLibraryFilesToSkip(module, known);
  432. // -- merge any antecedents, less any manifest
  433. for (File jarFile: known) {
  434. zipfileset = new ZipFileSet();
  435. zipfileset.setProject(project);
  436. zipfileset.setSrc(jarFile);
  437. zipfileset.setIncludes("**/*");
  438. String name = jarFile.getName();
  439. name = name.substring(0, name.length() - 4); // ".jar".length()
  440. // required includes self - exclude manifest from others
  441. if (!module.name.equals(name)) {
  442. zipfileset.setExcludes("META-INF/MANIFEST.MF"); // XXXFileLiteral
  443. zipfileset.setExcludes("META-INF/manifest.mf");
  444. zipfileset.setExcludes("meta-inf/manifest.mf");
  445. zipfileset.setExcludes("meta-inf/MANIFEST.MF");
  446. }
  447. zip.addZipfileset(zipfileset);
  448. }
  449. try {
  450. handler.log("assembling all " + module + " in " + result.getOutputFile());
  451. if (verbose) {
  452. handler.log("knownAntecedants: " + known);
  453. }
  454. return executeTask(zip);
  455. } catch (BuildException e) {
  456. handler.logException("BuildException zipping " + module, e);
  457. return false;
  458. } finally {
  459. result.clearOutOfDate();
  460. }
  461. }
  462. /**
  463. * @see org.aspectj.internal.tools.ant.taskdefs.Builder#buildInstaller(BuildSpec, String)
  464. */
  465. protected boolean buildInstaller(BuildSpec buildSpec, String targDirPath) {
  466. return false;
  467. }
  468. /** task.execute() and any advice */
  469. protected boolean executeTask(Task task) {
  470. if (!buildingEnabled) {
  471. return false;
  472. }
  473. task.execute();
  474. return true;
  475. }
  476. /**
  477. * Support for compiling basic AspectJ projects. Projects may only compile all (and only) their source directories; aspectpath,
  478. * inpath, etc. are not supported. To load the compiler, this assumes the user has either defined a project property
  479. * "aspectj.home" or that there exists <code>{module-dir}/lib/aspectj/lib/aspectj[tools|rt].jar</code>.
  480. */
  481. static class AspectJSupport {
  482. static final String AJCTASK = "org.aspectj.tools.ant.taskdefs.AjcTask";
  483. static final String ASPECTJRT_JAR_VARIABLE = "ASPECTJRT_LIB";
  484. static final String LIBASPECTJ_RPATH = "/lib/aspectj";
  485. static final Map nameToAspectjrtjar = new HashMap();
  486. static final String NONE = "NONE";
  487. /**
  488. * If this module should be compiled with AspectJ, return a task to do so.
  489. *
  490. * @param module the Module to compile
  491. * @param javac the Javac compile commands
  492. * @return javac or a Task to compile with AspectJ if needed
  493. */
  494. static Task wrapIfNeeded(Result result, Javac javac) {
  495. final Project project = javac.getProject();
  496. Path runtimeJar = null;
  497. final Module module = result.getModule();
  498. if (runtimeJarOnClasspath(result)) {
  499. // yes aspectjrt.jar on classpath
  500. } else if (result.getClasspathVariables().contains(ASPECTJRT_JAR_VARIABLE)) {
  501. // yes, in variables - find aspectjrt.jar to add to classpath
  502. runtimeJar = getAspectJLib(project, module, "aspectjrt.jar");
  503. } else {
  504. // no
  505. // System.out.println("javac " + result + " " + javac.getClasspath());
  506. return javac;
  507. }
  508. // System.out.println("aspectj " + result + " " + javac.getClasspath());
  509. Path aspectjtoolsJar = getAspectJLib(project, module, "aspectjtools.jar");
  510. return aspectJTask(javac, aspectjtoolsJar, runtimeJar);
  511. }
  512. /** @return true if aspectjrt.jar is on classpath */
  513. private static boolean runtimeJarOnClasspath(Result result) {
  514. for (File file: result.getLibJars()) {
  515. if ("aspectjrt.jar".equals(file.getName())) {
  516. return true;
  517. }
  518. }
  519. return false;
  520. }
  521. static Path getAspectJLib(Project project, Module module, String name) {
  522. Path result = null;
  523. String[] libDirNames = { "aspectj.home", "ASPECTJ_HOME", LIBASPECTJ_RPATH };
  524. String[] libDirs = new String[libDirNames.length];
  525. for (int i = 0; i < libDirNames.length; i++) {
  526. if (LIBASPECTJ_RPATH == libDirNames[i]) {
  527. libDirs[i] = module.getFullPath(LIBASPECTJ_RPATH);
  528. } else {
  529. libDirs[i] = project.getProperty(libDirNames[i]);
  530. }
  531. if (null != libDirs[i]) {
  532. libDirs[i] = Util.path(libDirs[i], "lib");
  533. result = new Path(project, Util.path(libDirs[i], name));
  534. String path = result.toString();
  535. if (new File(path).canRead()) {
  536. return result;
  537. }
  538. }
  539. }
  540. String m = "unable to find " + name + " in " + Arrays.asList(libDirs);
  541. throw new BuildException(m);
  542. }
  543. /**
  544. * Wrap AspectJ compiler as Task. Only works for javac-like source compilation of everything under srcDir. Written
  545. * reflectively to compile in the build module, which can't depend on the whole tree.
  546. *
  547. * @param javac the Javac specification
  548. * @param toolsJar the Path to the aspectjtools.jar
  549. * @param runtimeJar the Path to the aspectjrt.jar
  550. * @return javac or another Task invoking the AspectJ compiler
  551. */
  552. @SuppressWarnings("unchecked")
  553. static Task aspectJTask(Javac javac, Path toolsJar, Path runtimeJar) {
  554. Object task = null;
  555. String url = null;
  556. try {
  557. url = "file:" + toolsJar.toString().replace('\\', '/');
  558. URL[] cp = new URL[] { new URL(url) };
  559. ClassLoader parent = Task.class.getClassLoader();
  560. ClassLoader loader = new URLClassLoader(cp, parent);
  561. Class c = loader.loadClass(AJCTASK);
  562. task = c.newInstance();
  563. // Westodo Project project = javac.getProject();
  564. Method m = c.getMethod("setupAjc", new Class[] { Javac.class });
  565. m.invoke(task, new Object[] { javac });
  566. m = c.getMethod("setFork", new Class[] { boolean.class });
  567. m.invoke(task, new Object[] { Boolean.TRUE });
  568. m = c.getMethod("setForkclasspath", new Class[] { Path.class });
  569. m.invoke(task, new Object[] { toolsJar });
  570. m = c.getMethod("setSourceRoots", new Class[] { Path.class });
  571. m.invoke(task, new Object[] { javac.getSrcdir() });
  572. if (null != runtimeJar) {
  573. m = c.getMethod("setClasspath", new Class[] { Path.class });
  574. m.invoke(task, new Object[] { runtimeJar });
  575. }
  576. } catch (BuildException e) {
  577. throw e;
  578. } catch (Throwable t) {
  579. StringBuffer sb = new StringBuffer();
  580. sb.append("classpath=");
  581. sb.append(url);
  582. throw new BuildException(sb.toString(), t);
  583. }
  584. return (Task) task;
  585. }
  586. private AspectJSupport() {
  587. throw new Error("no instances");
  588. }
  589. }
  590. }
  591. // finally caught by failing to comply with proper ant initialization
  592. // /**
  593. // * Build a module that has a build script.
  594. // * @param buildSpec the module to build
  595. // * @param buildScript the script file
  596. // * @throws BuildException if build fails
  597. // */
  598. // private void buildByScript(BuildSpec buildSpec, File buildScript)
  599. // throws BuildException {
  600. // Ant ant = new Ant();
  601. // ant.setProject(getProject());
  602. // ant.setAntfile(buildScript.getAbsolutePath());
  603. // ant.setDescription("building module " + buildSpec.module);
  604. // ant.setDir(buildScript.getParentFile());
  605. // ant.setInheritAll(true);
  606. // ant.setInheritRefs(false);
  607. // ant.setLocation(getLocation());
  608. // ant.setOwningTarget(getOwningTarget());
  609. // // by convention, for build.xml, use module name to publish
  610. // ant.setTarget(buildSpec.module);
  611. // ant.setTaskName("ant");
  612. // loadAntProperties(ant, buildSpec);
  613. // ant.execute();
  614. // }
  615. //
  616. // /** override definitions */
  617. // private void loadAntProperties(Ant ant, BuildSpec buildSpec) {
  618. // Property property = ant.createProperty();
  619. // property.setName(BuildSpec.baseDir_NAME);
  620. // property.setFile(buildSpec.baseDir);
  621. // property = ant.createProperty();
  622. // property.setName(buildSpec.distDir_NAME);
  623. // property.setFile(buildSpec.distDir);
  624. // property = ant.createProperty();
  625. // property.setName(BuildSpec.tempDir_NAME);
  626. // property.setFile(buildSpec.tempDir);
  627. // property = ant.createProperty();
  628. // property.setName(BuildSpec.jarDir_NAME);
  629. // property.setFile(buildSpec.jarDir);
  630. // property = ant.createProperty();
  631. // property.setName(BuildSpec.stagingDir_NAME);
  632. // property.setFile(buildSpec.stagingDir);
  633. // }
  634. /**
  635. * Segregate product-building API's from module-building APIs for clarity. These are called by the superclass if the BuildSpec
  636. * warrants. XXX extremely brittle/arbitrary assumptions.
  637. *
  638. * @see BuildModule for assumptions
  639. */
  640. class ProductBuilder extends AntBuilder {
  641. private static String getProductInstallResourcesSrc(BuildSpec buildSpec) {
  642. final String resourcesName = "installer-resources"; // XXXFileLiteral
  643. File dir = buildSpec.productDir.getParentFile();
  644. if (null == dir) {
  645. return Util.path(new String[] { "..", "..", resourcesName });
  646. }
  647. dir = dir.getParentFile();
  648. if (null == dir) {
  649. return Util.path("..", resourcesName);
  650. } else {
  651. dir = new File(dir, resourcesName);
  652. return dir.getPath();
  653. }
  654. }
  655. private static String getProductInstallerFileName(BuildSpec buildSpec) { // XXXFileLiteral
  656. return "aspectj-" + buildSpec.productDir.getName() + "-" + Util.shortVersion(buildSpec.version) + ".jar";
  657. }
  658. /**
  659. * Calculate name of main, typically InitialCap, and hence installer class.
  660. *
  661. * @return $$installer$$.org.aspectj." + ProductName + "Installer"
  662. */
  663. private static String getProductInstallerMainClass(BuildSpec buildSpec) {
  664. String productName = buildSpec.productDir.getName();
  665. String initial = productName.substring(0, 1).toUpperCase();
  666. productName = initial + productName.substring(1);
  667. return "$installer$.org.aspectj." + productName + "Installer"; // XXXNameLiteral
  668. }
  669. /** @see Builder.getBuilder(String, Project, File) */
  670. ProductBuilder(Project project, File tempDir, boolean useEclipseCompiles, Messager handler) {
  671. super(project, tempDir, useEclipseCompiles, handler);
  672. }
  673. /**
  674. * Delegate for super.buildProduct(..) template method.
  675. */
  676. protected boolean copyBinaries(BuildSpec buildSpec, File distDir, File targDir, String excludes) {
  677. Copy copy = makeCopyTask(false);
  678. copy.setTodir(targDir);
  679. FileSet fileset = new FileSet();
  680. fileset.setDir(distDir);
  681. fileset.setIncludes(Builder.BINARY_SOURCE_PATTERN);
  682. if (null != excludes) {
  683. fileset.setExcludes(excludes);
  684. }
  685. copy.addFileset(fileset);
  686. return executeTask(copy);
  687. }
  688. /**
  689. * Delegate for super.buildProduct(..) template method.
  690. */
  691. protected boolean copyNonBinaries(BuildSpec buildSpec, File distDir, File targDir) {
  692. // filter-copy everything but the binaries
  693. Copy copy = makeCopyTask(true);
  694. copy.setTodir(targDir);
  695. Util.iaxIfNotCanReadDir(distDir, "product dist directory");
  696. FileSet fileset = new FileSet();
  697. fileset.setDir(distDir);
  698. fileset.setExcludes(Builder.BINARY_SOURCE_PATTERN);
  699. copy.addFileset(fileset);
  700. return executeTask(copy);
  701. }
  702. protected boolean buildInstaller(BuildSpec buildSpec, String targDirPath) {
  703. if (buildSpec.verbose) {
  704. handler.log("creating installer for " + buildSpec);
  705. }
  706. AJInstaller installer = new AJInstaller();
  707. setupTask(installer, "installer");
  708. installer.setBasedir(targDirPath);
  709. // installer.setCompress();
  710. File installSrcDir = new File(buildSpec.productDir, "install"); // XXXFileLiteral
  711. Util.iaxIfNotCanReadDir(installSrcDir, "installSrcDir");
  712. installer.setHtmlSrc(installSrcDir.getPath());
  713. String resourcePath = getProductInstallResourcesSrc(buildSpec);
  714. File resourceSrcDir = new File(resourcePath);
  715. Util.iaxIfNotCanReadDir(resourceSrcDir, "resourceSrcDir");
  716. installer.setResourcesSrc(resourcePath);
  717. String name = getProductInstallerFileName(buildSpec);
  718. File outFile = new File(buildSpec.jarDir, name);
  719. installer.setZipfile(outFile.getPath());
  720. installer.setMainclass(getProductInstallerMainClass(buildSpec));
  721. installer.setInstallerclassjar(getBuildJar(buildSpec));
  722. return executeTask(installer);
  723. // -- test installer XXX
  724. // create text setup file
  725. // run installer with setup file
  726. // cleanup installed product
  727. }
  728. private String getBuildJar(BuildSpec buildSpec) {
  729. return buildSpec.baseDir.getPath() + "/lib/build/build.jar"; // XXX
  730. }
  731. // private Module moduleForReplaceFile(File replaceFile, Modules modules) {
  732. // String jarName = moduleAliasFor(replaceFile.getName().toLowerCase());
  733. // if (jarName.endsWith(".jar") || jarName.endsWith(".zip")) { // XXXFileLiteral
  734. // jarName = jarName.substring(0, jarName.length()-4);
  735. // } else {
  736. // throw new IllegalArgumentException("can only replace .[jar|zip]");
  737. // }
  738. // boolean assembleAll = jarName.endsWith("-all");
  739. // String name = (!assembleAll ? jarName : jarName.substring(0, jarName.length()-4));
  740. // return modules.getModule(name);
  741. // }
  742. //
  743. }
  744. class ProjectMessager extends Messager {
  745. private final Project project;
  746. public ProjectMessager(Project project) {
  747. Util.iaxIfNull(project, "project");
  748. this.project = project;
  749. }
  750. public boolean log(String s) {
  751. project.log(s);
  752. return true;
  753. }
  754. public boolean error(String s) {
  755. project.log(s, Project.MSG_ERR);
  756. return true;
  757. }
  758. public boolean logException(String context, Throwable thrown) {
  759. project.log(context + Util.renderException(thrown), Project.MSG_ERR);
  760. return true;
  761. }
  762. }