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.

script.html 16 KiB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  1. <!DOCTYPE html>
  2. <!--
  3. Licensed to the Apache Software Foundation (ASF) under one or more
  4. contributor license agreements. See the NOTICE file distributed with
  5. this work for additional information regarding copyright ownership.
  6. The ASF licenses this file to You under the Apache License, Version 2.0
  7. (the "License"); you may not use this file except in compliance with
  8. the License. You may obtain a copy of the License at
  9. https://www.apache.org/licenses/LICENSE-2.0
  10. Unless required by applicable law or agreed to in writing, software
  11. distributed under the License is distributed on an "AS IS" BASIS,
  12. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. See the License for the specific language governing permissions and
  14. limitations under the License.
  15. -->
  16. <html lang="en">
  17. <head>
  18. <link rel="stylesheet" type="text/css" href="../stylesheets/style.css">
  19. <title>Script Task</title>
  20. </head>
  21. <body>
  22. <h2 id="script">Script</h2>
  23. <h3>Description</h3>
  24. <p>Execute a script in a <a href="https://jakarta.apache.org/bsf" target="_top">Apache BSF</a>
  25. or <a href="https://jcp.org/aboutJava/communityprocess/maintenance/jsr223/223ChangeLog.html"
  26. target="_top">JSR 223</a> supported language.
  27. </p>
  28. <p><strong>Note</strong>: This task depends on external libraries not included in the Apache Ant
  29. distribution. See <a href="../install.html#librarydependencies">Library Dependencies</a> for more
  30. information.</p>
  31. <p>The task may use the BSF scripting manager or the JSR 223 manager that is included in JDK 6 and
  32. higher. This is controlled by the <var>manager</var> attribute. The JSR 223 scripting manager is
  33. indicated by <q>javax</q>.</p>
  34. <p>All items (tasks, targets, etc) of the running project are accessible from the script, using
  35. either their <var>name</var> or <var>id</var> attributes (as long as their names are considered
  36. valid Java identifiers, that is). This is controlled by the <var>setbeans</var> attribute of the
  37. task. The name <code class="code">project</code> is a pre-defined reference to the Project, which
  38. can be used instead of the project name. The name <code class="code">self</code> is a pre-defined
  39. reference to the actual <code>&lt;script&gt;</code>-Task instance.<br/>From these objects you have
  40. access to the Ant Java API, see the <a href="../api/index.html">JavaDoc</a> (especially
  41. for <a href="../api/org/apache/tools/ant/Project.html">Project</a>
  42. and <a href="../api/org/apache/tools/ant/taskdefs/optional/Script.html">Script</a>) for more
  43. information.</p>
  44. <p>If you are using JavaScript under BSF, a good resource
  45. is <a href="https://www.mozilla.org/rhino/doc.html"
  46. target="_top">https://www.mozilla.org/rhino/doc.html</a> as we are using their JavaScript
  47. interpreter.</p>
  48. <p>Scripts can do almost anything a task written in Java could do.</p>
  49. <p>Rhino provides a special construct&mdash;the <code>JavaAdapter</code>. With that you can create
  50. an object which implements several interfaces, extends classes and for which you can overwrite
  51. methods. Because this is an undocumented feature (yet), here is the link to an
  52. explanation: <a href="https://groups.google.com/forum/#!msg/netscape.public.mozilla.jseng/YlRQE0OvM8c/F8Mvq-XkpxcJ"
  53. target="_top">Google Groups: "Rhino, enum.js, JavaAdapter?"</a> by Norris Boyd in the
  54. newsgroup <em>netscape.public.mozilla.jseng</em>.</p>
  55. <p>If you are creating Targets programmatically, make sure you set the Location to a useful value.
  56. In particular all targets should have different location values.</p>
  57. <h3>Parameters</h3>
  58. <table class="attr">
  59. <tr>
  60. <th scope="col">Attribute</th>
  61. <th scope="col">Description</th>
  62. <th scope="col">Required</th>
  63. </tr>
  64. <tr>
  65. <td>language</td>
  66. <td>The programming language the script is written in. Must be a supported Apache BSF or JSR
  67. 223 language</td>
  68. <td>Yes</td>
  69. </tr>
  70. <tr>
  71. <td>manager</td>
  72. <td>
  73. <em>Since Ant 1.7</em>. The script engine manager to use. This can have one of three
  74. values: <q>auto</q>, <q>bsf</q> or <q>javax</q>.
  75. <ul>
  76. <li><q>bsf</q> use the BSF scripting manager to run the language.</li>
  77. <li><q>javax</q> use the <code>javax.scripting</code> manager to run the language. (This
  78. will only work for JDK 6 and higher).</li>
  79. <li><q>auto</q> use the BSF engine if it exists, otherwise use
  80. the <code>javax.scripting</code> manager.</li>
  81. </ul>
  82. </td>
  83. <td>No; default is <q>auto</q></td>
  84. </tr>
  85. <tr>
  86. <td>src</td>
  87. <td>The location of the script as a file, if not inline</td>
  88. <td>No</td>
  89. </tr>
  90. <tr>
  91. <td>encoding</td>
  92. <td>The encoding of the script as a file. <em>Since Ant 1.10.2</em>.</td>
  93. <td>No; defaults to default JVM character encoding</td>
  94. </tr>
  95. <tr>
  96. <td>setbeans</td>
  97. <td>This attribute controls whether to set variables for all properties, references and targets
  98. in the running script. If this attribute is <q>false</q>, only the the <code>project</code>
  99. and <code>self</code> variables are set. If this attribute is <q>true</q> all the variables
  100. are set. <em>Since Ant 1.7</em></td>
  101. <td>No; defaults to <q>true</q></td>
  102. </tr>
  103. <tr>
  104. <td>classpath</td>
  105. <td>The classpath to pass into the script. <em>Since Ant 1.7</em></td>
  106. <td>No</td>
  107. </tr>
  108. <tr>
  109. <td>classpathref</td>
  110. <td>The classpath to use, given as a <a href="../using.html#references">reference</a> to a path
  111. defined elsewhere.
  112. <em>Since Ant 1.7</em></td>
  113. <td>No</td>
  114. </tr>
  115. </table>
  116. <h3>Parameters specified as nested elements</h3>
  117. <h4>classpath</h4>
  118. <p><em>Since Ant 1.7</em></p>
  119. <p><code>Script</code>'s <var>classpath</var> attribute is a <a href="../using.html#path">path-like
  120. structure</a> and can also be set via a nested <code>&lt;classpath&gt;</code> element.
  121. </p>
  122. <p>If a classpath is set, it will be used as the current thread context classloader, and as the
  123. classloader given to the BSF manager. This means that it can be used to specify the classpath
  124. containing the language implementation for BSF or for JSR 223 managers. This can be useful if one
  125. wants to keep <samp>${user.home}/.ant/lib</samp> free of lots of scripting language specific jar
  126. files.</p>
  127. <p><strong>Note</strong>: (<em>since Ant 1.7.1</em>) This classpath <em>can</em> be used to specify
  128. the location of the BSF jar file and/or languages that have engines in the BSF jar file. This
  129. includes the <q>javascript</q>, <q>jython</q>, <q>netrexx</q> and <q>jacl</q> languages.</p>
  130. <h3>Examples</h3>
  131. <p>The following snippet shows use of five different languages:</p>
  132. <pre>
  133. &lt;property name="message" value="Hello world"/&gt;
  134. &lt;script language="groovy"&gt;
  135. println("message is " + message)
  136. &lt;/script&gt;
  137. &lt;script language="beanshell"&gt;
  138. System.out.println("message is " + message);
  139. &lt;/script&gt;
  140. &lt;script language="judoscript"&gt;
  141. println 'message is ', message
  142. &lt;/script&gt;
  143. &lt;script language="ruby"&gt;
  144. print 'message is ', $message, "\n"
  145. &lt;/script&gt;
  146. &lt;script language="jython"&gt;
  147. print "message is %s" % message
  148. &lt;/script&gt;</pre>
  149. <p>Note that for the <q>jython</q> example, the script contents <strong>must</strong> start on the
  150. first column.</p>
  151. <p>Note also that for the <q>ruby</q> example, the names of the set variables are prefixed by
  152. a <q>$</q>.</p>
  153. <p>The following script shows a little more complicated JRuby example:</p>
  154. <pre>
  155. &lt;script language="ruby"&gt;
  156. xmlfiles = Dir.new(".").entries.delete_if { |i| ! (i =~ /\.xml$/) }
  157. xmlfiles.sort.each { |i| $self.log(i) }
  158. &lt;/script&gt;</pre>
  159. <p>The same example in Groovy is:</p>
  160. <pre>
  161. &lt;script language="groovy"&gt;
  162. xmlfiles = new java.io.File(".").listFiles().findAll{ it =~ "\.xml$"}
  163. xmlfiles.sort().each { self.log(it.toString()) }
  164. &lt;/script&gt;</pre>
  165. <p>The following example shows the use of classpath to specify the location of the beanshell jar
  166. file.</p>
  167. <pre>
  168. &lt;script language="beanshell" setbeans="true"&gt;
  169. &lt;classpath&gt;
  170. &lt;fileset dir="${user.home}/lang/beanshell" includes="*.jar"/&gt;
  171. &lt;/classpath&gt;
  172. System.out.println("Hello world");
  173. &lt;/script&gt;</pre>
  174. <p>The following script uses JavaScript to create a number of <code>echo</code> tasks and execute
  175. them.</p>
  176. <pre>
  177. &lt;project name=&quot;squares&quot; default=&quot;main&quot; basedir=&quot;.&quot;&gt;
  178. &lt;target name=&quot;main&quot;&gt;
  179. &lt;script language=&quot;javascript&quot;&gt; &lt;![CDATA[
  180. for (i = 1; i &lt;= 10; i++) {
  181. echo = squares.createTask(&quot;echo&quot;);
  182. echo.setMessage(i*i);
  183. echo.perform();
  184. }
  185. ]]&gt; &lt;/script&gt;
  186. &lt;/target&gt;
  187. &lt;/project&gt;</pre>
  188. <p>generates</p>
  189. <pre>
  190. main:
  191. 1
  192. 4
  193. 9
  194. 16
  195. 25
  196. 36
  197. 49
  198. 64
  199. 81
  200. 100
  201. BUILD SUCCESSFUL</pre>
  202. <p>Now a more complex example using the Java API and the Ant API. The goal is to list the file sizes
  203. of all files a <code>&lt;fileset/&gt;</code> caught.</p>
  204. <pre>
  205. &lt;?xml version="1.0" encoding="UTF-8"?&gt;
  206. &lt;project name="<span style="color:blue">MyProject</span>" basedir="." default="main"&gt;
  207. &lt;property name="fs.dir" value="src"/&gt;
  208. &lt;property name="fs.includes" value="**/*.txt"/&gt;
  209. &lt;property name="fs.excludes" value="**/*.tmp"/&gt;
  210. &lt;target name="main"&gt;
  211. &lt;script language="javascript"&gt; &lt;![CDATA[
  212. // import statements
  213. <span style="color:blue">// importPackage(java.io)</span>;
  214. <span style="color:blue">importClass(java.io.File)</span>;
  215. // Nashorn syntax
  216. // <span style="color:blue">load("nashorn:mozilla_compat.js");</span>
  217. // or
  218. // <span style="color:blue">var File = Java.type('java.io.File');</span>
  219. // Access to Ant-Properties by their names
  220. dir = <span style="color:blue">project</span>.getProperty("fs.dir");
  221. includes = <span style="color:blue">MyProject</span>.getProperty("fs.includes");
  222. excludes = <span style="color:blue">self.getProject()</span>.<span style="color:blue">getProperty("fs.excludes")</span>;
  223. // Create a &lt;fileset dir="" includes=""/&gt;
  224. fs = project.<span style="color:blue">createDataType("fileset")</span>;
  225. fs.setDir(new File(dir));
  226. <span style="color:blue">fs.setIncludes(includes)</span>;
  227. fs.setExcludes(excludes);
  228. // Get the files (array) of that fileset
  229. ds = fs.getDirectoryScanner(project);
  230. srcFiles = ds.getIncludedFiles();
  231. // iterate over that array
  232. for (i = 0; i &lt; srcFiles.length; i++) {
  233. // get the values via Java API
  234. var basedir = fs.getDir(project);
  235. var filename = srcFiles[i];
  236. var file = <span style="color:blue">new File(basedir, filename)</span>;
  237. var size = file.length();
  238. // create and use a Task via Ant API
  239. echo = MyProject.<span style="color:blue">createTask("echo")</span>;
  240. echo.setMessage(filename + ": " + size + " byte");
  241. echo.<span style="color:blue">perform()</span>;
  242. }
  243. ]]&gt;&lt;/script&gt;
  244. &lt;/target&gt;
  245. &lt;/project&gt;</pre>
  246. <p>We want to use the Java API. Because we don't want always typing the package signature we do an
  247. import. Rhino knows two different methods for import statements: one for packages and one for a
  248. single class. By default only the <code>java</code> packages are available,
  249. so <code class="code">java.lang.System</code> can be directly imported
  250. with <code>importClass</code>/<code>importPackage</code>. For other packages you have to prefix the
  251. full classified name with <strong>Packages</strong>. For example
  252. Ant's <code class="code">FileUtils</code> class can be imported
  253. with <code class="code">importClass(<strong>Packages</strong>.org.apache.tools.ant.util.FileUtils)</code></p>
  254. <p>In Java 8 up until Java 14, you may use the built-in Nashorn JavaScript engine rather than Rhino (which is
  255. available in Java 7 runtime). Then, use <code>Java.type</code> as import statement for any Java
  256. class
  257. or <a href="https://docs.oracle.com/javase/8/docs/technotes/guides/scripting/prog_guide/javascript.html#A1147207">the
  258. compatibility script</a>: <code>load("nashorn:mozilla_compat.js");</code>.</p>
  259. <p>Starting with Java 15 Nashorn has been removed again and you need
  260. to provide an external JavaScript engine. Your best option probably
  261. is <a href="https://github.com/graalvm/graaljs">GraalVM
  262. JavaScript</a> which requires you to add a lot of extra jars. For
  263. GraalVM JavaScript 20.1 you'll
  264. need <code>org.graalvm.js:js</code>, <code>org.graalvm.js:js-engine</code>
  265. which in turn
  266. require <code>org.graalvm.regex:regex</code>, <code>org.graalvm.truffle:truffle-api</code>, <code>org.graalvm.sdk:graal-sdk</code>,
  267. and <code>com.ibm.icu:icu4j</code>. GraalVM JavaScript is not a
  268. drop-in replacement for Nashorn, see
  269. Graal's <a href="https://github.com/graalvm/graaljs/blob/master/docs/user/NashornMigrationGuide.md">Nashorn
  270. Migration Guide</a> for more details.</p>
  271. <p>When using GraalVM JavaScript Ant will enable the
  272. feature <code>polyglot.js.allowAllAccess</code> in order to allow
  273. scripts to use Ant objects. By default it will also enable Nashorn
  274. compatibility mode, but you can disable this by setting the magic
  275. Ant property <code>ant.disable.graal.nashorn.compat</code>
  276. to <code>true</code>.</p>
  277. <p>The <code>&lt;script&gt;</code> task populates the Project instance under the
  278. name <code class="code">project</code>, so we can use that reference. Another way is to use its
  279. given name or getting its reference from the task itself. The Project provides methods for accessing
  280. and setting properties, creating DataTypes and Tasks and much more.<br/>After creating a FileSet
  281. object we initialize that by calling its set-methods. Then we can use that object like a normal Ant
  282. task (<code>&lt;copy&gt;</code> for example).<br/>For getting the size of a file we instantiate
  283. a <code class="code">java.io.File</code>. So we are using normal Java API here.<br/>Finally we use
  284. the <code>&lt;echo&gt;</code> task for producing the output. The task is not executed by
  285. its <code class="code">execute()</code> method, because the <code class="code">perform()</code>
  286. method (implemented in Task itself) does the appropriate logging before and after
  287. invoking <code class="code">execute()</code>.</p>
  288. <p>Here is an example of using beanshell to create an Ant task. This task will add filesets and
  289. paths to a referenced path. If the path does not exist, it will be created.</p>
  290. <pre>
  291. &lt;!--
  292. Define addtopath task
  293. --&gt;
  294. &lt;script language="beanshell"&gt;
  295. import org.apache.tools.ant.Task;
  296. import org.apache.tools.ant.types.Path;
  297. import org.apache.tools.ant.types.FileSet;
  298. public class AddToPath extends Task {
  299. private Path path;
  300. public void setRefId(String id) {
  301. path = getProject().getReference(id);
  302. if (path == null) {
  303. path = new Path(getProject());
  304. getProject().addReference(id, path);
  305. }
  306. }
  307. public void add(Path c) {
  308. path.add(c);
  309. }
  310. public void add(FileSet c) {
  311. path.add(c);
  312. }
  313. public void execute() {
  314. // Do nothing
  315. }
  316. }
  317. project.addTaskDefinition("addtopath", AddToPath.class);
  318. &lt;/script&gt;</pre>
  319. <p>An example of using this task to create a path from a list of directories (using
  320. Ant-Contrib's <a href="http://ant-contrib.sourceforge.net/tasks/tasks/for.html"
  321. target="_top">&lt;for&gt;</a> task) follows:</p>
  322. <pre>
  323. &lt;path id="main.path"&gt;
  324. &lt;fileset dir="build/classes"/&gt;
  325. &lt;/path&gt;
  326. &lt;ac:for param="ref" list="commons,fw,lps"
  327. xmlns:ac="antlib:net.sf.antcontrib"&gt;
  328. &lt;sequential&gt;
  329. &lt;addtopath refid="main.path"&gt;
  330. &lt;fileset dir="${dist.dir}/@{ref}/main"
  331. includes="**/*.jar"/&gt;
  332. &lt;/addtopath&gt;
  333. &lt;/sequential&gt;
  334. &lt;/ac:for&gt;</pre>
  335. </body>
  336. </html>