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.

PathConvert.java 16 kB

11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511
  1. /*
  2. * Licensed to the Apache Software Foundation (ASF) under one or more
  3. * contributor license agreements. See the NOTICE file distributed with
  4. * this work for additional information regarding copyright ownership.
  5. * The ASF licenses this file to You under the Apache License, Version 2.0
  6. * (the "License"); you may not use this file except in compliance with
  7. * the License. You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. *
  17. */
  18. package org.apache.tools.ant.taskdefs;
  19. import java.io.File;
  20. import java.util.ArrayList;
  21. import java.util.Iterator;
  22. import java.util.List;
  23. import java.util.StringTokenizer;
  24. import java.util.Vector;
  25. import org.apache.tools.ant.BuildException;
  26. import org.apache.tools.ant.Project;
  27. import org.apache.tools.ant.Task;
  28. import org.apache.tools.ant.taskdefs.condition.Os;
  29. import org.apache.tools.ant.types.EnumeratedAttribute;
  30. import org.apache.tools.ant.types.Mapper;
  31. import org.apache.tools.ant.types.Path;
  32. import org.apache.tools.ant.types.Reference;
  33. import org.apache.tools.ant.types.Resource;
  34. import org.apache.tools.ant.types.ResourceCollection;
  35. import org.apache.tools.ant.types.resources.Resources;
  36. import org.apache.tools.ant.types.resources.Union;
  37. import org.apache.tools.ant.util.FileNameMapper;
  38. import org.apache.tools.ant.util.IdentityMapper;
  39. /**
  40. * Converts path and classpath information to a specific target OS
  41. * format. The resulting formatted path is placed into the specified property.
  42. *
  43. * @since Ant 1.4
  44. * @ant.task category="utility"
  45. */
  46. public class PathConvert extends Task {
  47. /**
  48. * Set if we're running on windows
  49. */
  50. private static boolean onWindows = Os.isFamily("dos");
  51. // Members
  52. /**
  53. * Path to be converted
  54. */
  55. private Resources path = null;
  56. /**
  57. * Reference to path/fileset to convert
  58. */
  59. private Reference refid = null;
  60. /**
  61. * The target OS type
  62. */
  63. private String targetOS = null;
  64. /**
  65. * Set when targetOS is set to windows
  66. */
  67. private boolean targetWindows = false;
  68. /**
  69. * Set if we should create a new property even if the result is empty
  70. */
  71. private boolean setonempty = true;
  72. /**
  73. * The property to receive the conversion
  74. */
  75. private String property = null;
  76. /**
  77. * Path prefix map
  78. */
  79. private Vector prefixMap = new Vector();
  80. /**
  81. * User override on path sep char
  82. */
  83. private String pathSep = null;
  84. /**
  85. * User override on directory sep char
  86. */
  87. private String dirSep = null;
  88. /** Filename mapper */
  89. private Mapper mapper = null;
  90. private boolean preserveDuplicates;
  91. /**
  92. * Construct a new instance of the PathConvert task.
  93. */
  94. public PathConvert() {
  95. }
  96. /**
  97. * Helper class, holds the nested <map> values. Elements will look like
  98. * this: <map from="d:" to="/foo"/>
  99. *
  100. * When running on windows, the prefix comparison will be case
  101. * insensitive.
  102. */
  103. public class MapEntry {
  104. // Members
  105. private String from = null;
  106. private String to = null;
  107. /**
  108. * Set the "from" attribute of the map entry.
  109. * @param from the prefix string to search for; required.
  110. * Note that this value is case-insensitive when the build is
  111. * running on a Windows platform and case-sensitive when running on
  112. * a Unix platform.
  113. */
  114. public void setFrom(String from) {
  115. this.from = from;
  116. }
  117. /**
  118. * Set the replacement text to use when from is matched; required.
  119. * @param to new prefix.
  120. */
  121. public void setTo(String to) {
  122. this.to = to;
  123. }
  124. /**
  125. * Apply this map entry to a given path element.
  126. *
  127. * @param elem Path element to process.
  128. * @return String Updated path element after mapping.
  129. */
  130. public String apply(String elem) {
  131. if (from == null || to == null) {
  132. throw new BuildException("Both 'from' and 'to' must be set "
  133. + "in a map entry");
  134. }
  135. // If we're on windows, then do the comparison ignoring case
  136. // and treat the two directory characters the same
  137. String cmpElem =
  138. onWindows ? elem.toLowerCase().replace('\\', '/') : elem;
  139. String cmpFrom =
  140. onWindows ? from.toLowerCase().replace('\\', '/') : from;
  141. // If the element starts with the configured prefix, then
  142. // convert the prefix to the configured 'to' value.
  143. return cmpElem.startsWith(cmpFrom)
  144. ? to + elem.substring(from.length()) : elem;
  145. }
  146. }
  147. /**
  148. * An enumeration of supported targets:
  149. * "windows", "unix", "netware", and "os/2".
  150. */
  151. public static class TargetOs extends EnumeratedAttribute {
  152. /**
  153. * @return the list of values for this enumerated attribute.
  154. */
  155. @Override
  156. public String[] getValues() {
  157. return new String[]{"windows", "unix", "netware", "os/2", "tandem"};
  158. }
  159. }
  160. /**
  161. * Create a nested path element.
  162. * @return a Path to be used by Ant reflection.
  163. */
  164. public Path createPath() {
  165. if (isReference()) {
  166. throw noChildrenAllowed();
  167. }
  168. Path result = new Path(getProject());
  169. add(result);
  170. return result;
  171. }
  172. /**
  173. * Add an arbitrary ResourceCollection.
  174. * @param rc the ResourceCollection to add.
  175. * @since Ant 1.7
  176. */
  177. public void add(ResourceCollection rc) {
  178. if (isReference()) {
  179. throw noChildrenAllowed();
  180. }
  181. getPath().add(rc);
  182. }
  183. private synchronized Resources getPath() {
  184. if (path == null) {
  185. path = new Resources(getProject());
  186. path.setCache(true);
  187. }
  188. return path;
  189. }
  190. /**
  191. * Create a nested MAP element.
  192. * @return a Map to configure.
  193. */
  194. public MapEntry createMap() {
  195. MapEntry entry = new MapEntry();
  196. prefixMap.addElement(entry);
  197. return entry;
  198. }
  199. /**
  200. * Set targetos to a platform to one of
  201. * "windows", "unix", "netware", or "os/2";
  202. * current platform settings are used by default.
  203. * @param target the target os.
  204. * @deprecated since 1.5.x.
  205. * Use the method taking a TargetOs argument instead.
  206. * @see #setTargetos(PathConvert.TargetOs)
  207. */
  208. @Deprecated
  209. public void setTargetos(String target) {
  210. TargetOs to = new TargetOs();
  211. to.setValue(target);
  212. setTargetos(to);
  213. }
  214. /**
  215. * Set targetos to a platform to one of
  216. * "windows", "unix", "netware", or "os/2";
  217. * current platform settings are used by default.
  218. * @param target the target os
  219. *
  220. * @since Ant 1.5
  221. */
  222. public void setTargetos(TargetOs target) {
  223. targetOS = target.getValue();
  224. // Currently, we deal with only two path formats: Unix and Windows
  225. // And Unix is everything that is not Windows
  226. // for NetWare and OS/2, piggy-back on Windows, since in the
  227. // validateSetup code, the same assumptions can be made as
  228. // with windows - that ; is the path separator
  229. targetWindows = !targetOS.equals("unix") && !targetOS.equals("tandem");
  230. }
  231. /**
  232. * Set whether the specified property will be set if the result
  233. * is the empty string.
  234. * @param setonempty true or false.
  235. *
  236. * @since Ant 1.5
  237. */
  238. public void setSetonempty(boolean setonempty) {
  239. this.setonempty = setonempty;
  240. }
  241. /**
  242. * Set the name of the property into which the converted path will be placed.
  243. * @param p the property name.
  244. */
  245. public void setProperty(String p) {
  246. property = p;
  247. }
  248. /**
  249. * Add a reference to a Path, FileSet, DirSet, or FileList defined elsewhere.
  250. * @param r the reference to a path, fileset, dirset or filelist.
  251. */
  252. public void setRefid(Reference r) {
  253. if (path != null) {
  254. throw noChildrenAllowed();
  255. }
  256. refid = r;
  257. }
  258. /**
  259. * Set the default path separator string; defaults to current JVM
  260. * {@link java.io.File#pathSeparator File.pathSeparator}.
  261. * @param sep path separator string.
  262. */
  263. public void setPathSep(String sep) {
  264. pathSep = sep;
  265. }
  266. /**
  267. * Set the default directory separator string;
  268. * defaults to current JVM {@link java.io.File#separator File.separator}.
  269. * @param sep directory separator string.
  270. */
  271. public void setDirSep(String sep) {
  272. dirSep = sep;
  273. }
  274. /**
  275. * Set the preserveDuplicates.
  276. * @param preserveDuplicates the boolean to set
  277. * @since Ant 1.8
  278. */
  279. public void setPreserveDuplicates(boolean preserveDuplicates) {
  280. this.preserveDuplicates = preserveDuplicates;
  281. }
  282. /**
  283. * Get the preserveDuplicates.
  284. * @return boolean
  285. * @since Ant 1.8
  286. */
  287. public boolean isPreserveDuplicates() {
  288. return preserveDuplicates;
  289. }
  290. /**
  291. * Learn whether the refid attribute of this element been set.
  292. * @return true if refid is valid.
  293. */
  294. public boolean isReference() {
  295. return refid != null;
  296. }
  297. /**
  298. * Do the execution.
  299. * @throws BuildException if something is invalid.
  300. */
  301. @Override
  302. public void execute() throws BuildException {
  303. Resources savedPath = path;
  304. String savedPathSep = pathSep; // may be altered in validateSetup
  305. String savedDirSep = dirSep; // may be altered in validateSetup
  306. try {
  307. // If we are a reference, create a Path from the reference
  308. if (isReference()) {
  309. Object o = refid.getReferencedObject(getProject());
  310. if (!(o instanceof ResourceCollection)) {
  311. throw new BuildException("refid '" + refid.getRefId()
  312. + "' does not refer to a resource collection.");
  313. }
  314. getPath().add((ResourceCollection) o);
  315. }
  316. validateSetup(); // validate our setup
  317. // Currently, we deal with only two path formats: Unix and Windows
  318. // And Unix is everything that is not Windows
  319. // (with the exception for NetWare and OS/2 below)
  320. // for NetWare and OS/2, piggy-back on Windows, since here and
  321. // in the apply code, the same assumptions can be made as with
  322. // windows - that \\ is an OK separator, and do comparisons
  323. // case-insensitive.
  324. String fromDirSep = onWindows ? "\\" : "/";
  325. StringBuffer rslt = new StringBuffer();
  326. ResourceCollection resources = isPreserveDuplicates() ? (ResourceCollection) path : new Union(path);
  327. List ret = new ArrayList();
  328. FileNameMapper mapperImpl = mapper == null ? new IdentityMapper() : mapper.getImplementation();
  329. for (Resource r : resources) {
  330. String[] mapped = mapperImpl.mapFileName(String.valueOf(r));
  331. for (int m = 0; mapped != null && m < mapped.length; ++m) {
  332. ret.add(mapped[m]);
  333. }
  334. }
  335. boolean first = true;
  336. for (Iterator mappedIter = ret.iterator(); mappedIter.hasNext();) {
  337. String elem = mapElement((String) mappedIter.next()); // Apply the path prefix map
  338. // Now convert the path and file separator characters from the
  339. // current os to the target os.
  340. if (!first) {
  341. rslt.append(pathSep);
  342. }
  343. first = false;
  344. StringTokenizer stDirectory = new StringTokenizer(elem, fromDirSep, true);
  345. while (stDirectory.hasMoreTokens()) {
  346. String token = stDirectory.nextToken();
  347. rslt.append(fromDirSep.equals(token) ? dirSep : token);
  348. }
  349. }
  350. // Place the result into the specified property,
  351. // unless setonempty == false
  352. if (setonempty || rslt.length() > 0) {
  353. String value = rslt.toString();
  354. if (property == null) {
  355. log(value);
  356. } else {
  357. log("Set property " + property + " = " + value, Project.MSG_VERBOSE);
  358. getProject().setNewProperty(property, value);
  359. }
  360. }
  361. } finally {
  362. path = savedPath;
  363. dirSep = savedDirSep;
  364. pathSep = savedPathSep;
  365. }
  366. }
  367. /**
  368. * Apply the configured map to a path element. The map is used to convert
  369. * between Windows drive letters and Unix paths. If no map is configured,
  370. * then the input string is returned unchanged.
  371. *
  372. * @param elem The path element to apply the map to.
  373. * @return String Updated element.
  374. */
  375. private String mapElement(String elem) {
  376. int size = prefixMap.size();
  377. if (size != 0) {
  378. // Iterate over the map entries and apply each one.
  379. // Stop when one of the entries actually changes the element.
  380. for (int i = 0; i < size; i++) {
  381. MapEntry entry = (MapEntry) prefixMap.elementAt(i);
  382. String newElem = entry.apply(elem);
  383. // Note I'm using "!=" to see if we got a new object back from
  384. // the apply method.
  385. if (newElem != elem) {
  386. elem = newElem;
  387. break; // We applied one, so we're done
  388. }
  389. }
  390. }
  391. return elem;
  392. }
  393. /**
  394. * Add a mapper to convert the file names.
  395. *
  396. * @param mapper a <code>Mapper</code> value.
  397. */
  398. public void addMapper(Mapper mapper) {
  399. if (this.mapper != null) {
  400. throw new BuildException(
  401. "Cannot define more than one mapper");
  402. }
  403. this.mapper = mapper;
  404. }
  405. /**
  406. * Add a nested filenamemapper.
  407. * @param fileNameMapper the mapper to add.
  408. * @since Ant 1.6.3
  409. */
  410. public void add(FileNameMapper fileNameMapper) {
  411. Mapper m = new Mapper(getProject());
  412. m.add(fileNameMapper);
  413. addMapper(m);
  414. }
  415. /**
  416. * Validate that all our parameters have been properly initialized.
  417. *
  418. * @throws BuildException if something is not set up properly.
  419. */
  420. private void validateSetup() throws BuildException {
  421. if (path == null) {
  422. throw new BuildException("You must specify a path to convert");
  423. }
  424. // Determine the separator strings. The dirsep and pathsep attributes
  425. // override the targetOS settings.
  426. String dsep = File.separator;
  427. String psep = File.pathSeparator;
  428. if (targetOS != null) {
  429. psep = targetWindows ? ";" : ":";
  430. dsep = targetWindows ? "\\" : "/";
  431. }
  432. if (pathSep != null) {
  433. // override with pathsep=
  434. psep = pathSep;
  435. }
  436. if (dirSep != null) {
  437. // override with dirsep=
  438. dsep = dirSep;
  439. }
  440. pathSep = psep;
  441. dirSep = dsep;
  442. }
  443. /**
  444. * Creates an exception that indicates that this XML element must not have
  445. * child elements if the refid attribute is set.
  446. * @return BuildException.
  447. */
  448. private BuildException noChildrenAllowed() {
  449. return new BuildException("You must not specify nested "
  450. + "elements when using the refid attribute.");
  451. }
  452. }