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.

Tar.java 34 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966
  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.BufferedOutputStream;
  20. import java.io.File;
  21. import java.io.FileOutputStream;
  22. import java.io.IOException;
  23. import java.io.InputStream;
  24. import java.io.OutputStream;
  25. import java.util.Enumeration;
  26. import java.util.HashMap;
  27. import java.util.HashSet;
  28. import java.util.Iterator;
  29. import java.util.Vector;
  30. import java.util.zip.GZIPOutputStream;
  31. import org.apache.tools.ant.BuildException;
  32. import org.apache.tools.ant.DirectoryScanner;
  33. import org.apache.tools.ant.Project;
  34. import org.apache.tools.ant.types.ArchiveFileSet;
  35. import org.apache.tools.ant.types.EnumeratedAttribute;
  36. import org.apache.tools.ant.types.FileSet;
  37. import org.apache.tools.ant.types.Resource;
  38. import org.apache.tools.ant.types.ResourceCollection;
  39. import org.apache.tools.ant.types.resources.ArchiveResource;
  40. import org.apache.tools.ant.types.resources.FileProvider;
  41. import org.apache.tools.ant.types.resources.FileResource;
  42. import org.apache.tools.ant.types.selectors.SelectorUtils;
  43. import org.apache.tools.ant.types.resources.TarResource;
  44. import org.apache.tools.ant.util.FileUtils;
  45. import org.apache.tools.ant.util.MergingMapper;
  46. import org.apache.tools.ant.util.ResourceUtils;
  47. import org.apache.tools.ant.util.SourceFileScanner;
  48. import org.apache.tools.bzip2.CBZip2OutputStream;
  49. import org.apache.tools.tar.TarConstants;
  50. import org.apache.tools.tar.TarEntry;
  51. import org.apache.tools.tar.TarOutputStream;
  52. /**
  53. * Creates a tar archive.
  54. *
  55. * @since Ant 1.1
  56. *
  57. * @ant.task category="packaging"
  58. */
  59. public class Tar extends MatchingTask {
  60. private static final int BUFFER_SIZE = 8 * 1024;
  61. /**
  62. * @deprecated since 1.5.x.
  63. * Tar.WARN is deprecated and is replaced with
  64. * Tar.TarLongFileMode.WARN
  65. */
  66. public static final String WARN = "warn";
  67. /**
  68. * @deprecated since 1.5.x.
  69. * Tar.FAIL is deprecated and is replaced with
  70. * Tar.TarLongFileMode.FAIL
  71. */
  72. public static final String FAIL = "fail";
  73. /**
  74. * @deprecated since 1.5.x.
  75. * Tar.TRUNCATE is deprecated and is replaced with
  76. * Tar.TarLongFileMode.TRUNCATE
  77. */
  78. public static final String TRUNCATE = "truncate";
  79. /**
  80. * @deprecated since 1.5.x.
  81. * Tar.GNU is deprecated and is replaced with
  82. * Tar.TarLongFileMode.GNU
  83. */
  84. public static final String GNU = "gnu";
  85. /**
  86. * @deprecated since 1.5.x.
  87. * Tar.OMIT is deprecated and is replaced with
  88. * Tar.TarLongFileMode.OMIT
  89. */
  90. public static final String OMIT = "omit";
  91. // CheckStyle:VisibilityModifier OFF - bc
  92. File tarFile;
  93. File baseDir;
  94. private TarLongFileMode longFileMode = new TarLongFileMode();
  95. // need to keep the package private version for backwards compatibility
  96. Vector filesets = new Vector();
  97. // we must keep two lists since other classes may modify the
  98. // filesets Vector (it is package private) without us noticing
  99. private Vector resourceCollections = new Vector();
  100. Vector fileSetFiles = new Vector();
  101. // CheckStyle:VisibilityModifier ON
  102. /**
  103. * Indicates whether the user has been warned about long files already.
  104. */
  105. private boolean longWarningGiven = false;
  106. private TarCompressionMethod compression = new TarCompressionMethod();
  107. /**
  108. * Add a new fileset with the option to specify permissions
  109. * @return the tar fileset to be used as the nested element.
  110. */
  111. public TarFileSet createTarFileSet() {
  112. TarFileSet fs = new TarFileSet();
  113. fs.setProject(getProject());
  114. filesets.addElement(fs);
  115. return fs;
  116. }
  117. /**
  118. * Add a collection of resources to archive.
  119. * @param res a resource collection to archive.
  120. * @since Ant 1.7
  121. */
  122. public void add(ResourceCollection res) {
  123. resourceCollections.add(res);
  124. }
  125. /**
  126. * Set is the name/location of where to create the tar file.
  127. * @param tarFile the location of the tar file.
  128. * @deprecated since 1.5.x.
  129. * For consistency with other tasks, please use setDestFile().
  130. */
  131. public void setTarfile(File tarFile) {
  132. this.tarFile = tarFile;
  133. }
  134. /**
  135. * Set is the name/location of where to create the tar file.
  136. * @since Ant 1.5
  137. * @param destFile The output of the tar
  138. */
  139. public void setDestFile(File destFile) {
  140. this.tarFile = destFile;
  141. }
  142. /**
  143. * This is the base directory to look in for things to tar.
  144. * @param baseDir the base directory.
  145. */
  146. public void setBasedir(File baseDir) {
  147. this.baseDir = baseDir;
  148. }
  149. /**
  150. * Set how to handle long files, those with a path>100 chars.
  151. * Optional, default=warn.
  152. * <p>
  153. * Allowable values are
  154. * <ul>
  155. * <li> truncate - paths are truncated to the maximum length
  156. * <li> fail - paths greater than the maximum cause a build exception
  157. * <li> warn - paths greater than the maximum cause a warning and GNU is used
  158. * <li> gnu - GNU extensions are used for any paths greater than the maximum.
  159. * <li> omit - paths greater than the maximum are omitted from the archive
  160. * </ul>
  161. * @param mode the mode string to handle long files.
  162. * @deprecated since 1.5.x.
  163. * setLongFile(String) is deprecated and is replaced with
  164. * setLongFile(Tar.TarLongFileMode) to make Ant's Introspection
  165. * mechanism do the work and also to encapsulate operations on
  166. * the mode in its own class.
  167. */
  168. public void setLongfile(String mode) {
  169. log("DEPRECATED - The setLongfile(String) method has been deprecated."
  170. + " Use setLongfile(Tar.TarLongFileMode) instead.");
  171. this.longFileMode = new TarLongFileMode();
  172. longFileMode.setValue(mode);
  173. }
  174. /**
  175. * Set how to handle long files, those with a path&gt;100 chars.
  176. * Optional, default=warn.
  177. * <p>
  178. * Allowable values are
  179. * <ul>
  180. * <li> truncate - paths are truncated to the maximum length
  181. * <li> fail - paths greater than the maximum cause a build exception
  182. * <li> warn - paths greater than the maximum cause a warning and GNU is used
  183. * <li> gnu - GNU extensions are used for any paths greater than the maximum.
  184. * <li> omit - paths greater than the maximum are omitted from the archive
  185. * </ul>
  186. * @param mode the mode to handle long file names.
  187. */
  188. public void setLongfile(TarLongFileMode mode) {
  189. this.longFileMode = mode;
  190. }
  191. /**
  192. * Set compression method.
  193. * Allowable values are
  194. * <ul>
  195. * <li> none - no compression
  196. * <li> gzip - Gzip compression
  197. * <li> bzip2 - Bzip2 compression
  198. * </ul>
  199. * @param mode the compression method.
  200. */
  201. public void setCompression(TarCompressionMethod mode) {
  202. this.compression = mode;
  203. }
  204. /**
  205. * do the business
  206. * @throws BuildException on error
  207. */
  208. public void execute() throws BuildException {
  209. if (tarFile == null) {
  210. throw new BuildException("tarfile attribute must be set!",
  211. getLocation());
  212. }
  213. if (tarFile.exists() && tarFile.isDirectory()) {
  214. throw new BuildException("tarfile is a directory!",
  215. getLocation());
  216. }
  217. if (tarFile.exists() && !tarFile.canWrite()) {
  218. throw new BuildException("Can not write to the specified tarfile!",
  219. getLocation());
  220. }
  221. Vector savedFileSets = (Vector) filesets.clone();
  222. try {
  223. if (baseDir != null) {
  224. if (!baseDir.exists()) {
  225. throw new BuildException("basedir does not exist!",
  226. getLocation());
  227. }
  228. // add the main fileset to the list of filesets to process.
  229. TarFileSet mainFileSet = new TarFileSet(fileset);
  230. mainFileSet.setDir(baseDir);
  231. filesets.addElement(mainFileSet);
  232. }
  233. if (filesets.size() == 0 && resourceCollections.size() == 0) {
  234. throw new BuildException("You must supply either a basedir "
  235. + "attribute or some nested resource"
  236. + " collections.",
  237. getLocation());
  238. }
  239. // check if tar is out of date with respect to each
  240. // fileset
  241. boolean upToDate = true;
  242. for (Enumeration e = filesets.elements(); e.hasMoreElements();) {
  243. upToDate &= check((TarFileSet) e.nextElement());
  244. }
  245. for (Enumeration e = resourceCollections.elements();
  246. e.hasMoreElements();) {
  247. upToDate &= check((ResourceCollection) e.nextElement());
  248. }
  249. if (upToDate) {
  250. log("Nothing to do: " + tarFile.getAbsolutePath()
  251. + " is up to date.", Project.MSG_INFO);
  252. return;
  253. }
  254. File parent = tarFile.getParentFile();
  255. if (parent != null && !parent.isDirectory() && !parent.mkdirs()) {
  256. throw new BuildException("Failed to create missing parent"
  257. + " directory for " + tarFile);
  258. }
  259. log("Building tar: " + tarFile.getAbsolutePath(), Project.MSG_INFO);
  260. TarOutputStream tOut = null;
  261. try {
  262. tOut = new TarOutputStream(
  263. compression.compress(
  264. new BufferedOutputStream(
  265. new FileOutputStream(tarFile))));
  266. tOut.setDebug(true);
  267. if (longFileMode.isTruncateMode()) {
  268. tOut.setLongFileMode(TarOutputStream.LONGFILE_TRUNCATE);
  269. } else if (longFileMode.isFailMode()
  270. || longFileMode.isOmitMode()) {
  271. tOut.setLongFileMode(TarOutputStream.LONGFILE_ERROR);
  272. } else {
  273. // warn or GNU
  274. tOut.setLongFileMode(TarOutputStream.LONGFILE_GNU);
  275. }
  276. longWarningGiven = false;
  277. for (Enumeration e = filesets.elements();
  278. e.hasMoreElements();) {
  279. tar((TarFileSet) e.nextElement(), tOut);
  280. }
  281. for (Enumeration e = resourceCollections.elements();
  282. e.hasMoreElements();) {
  283. tar((ResourceCollection) e.nextElement(), tOut);
  284. }
  285. } catch (IOException ioe) {
  286. String msg = "Problem creating TAR: " + ioe.getMessage();
  287. throw new BuildException(msg, ioe, getLocation());
  288. } finally {
  289. FileUtils.close(tOut);
  290. }
  291. } finally {
  292. filesets = savedFileSets;
  293. }
  294. }
  295. /**
  296. * tar a file
  297. * @param file the file to tar
  298. * @param tOut the output stream
  299. * @param vPath the path name of the file to tar
  300. * @param tarFileSet the fileset that the file came from.
  301. * @throws IOException on error
  302. */
  303. protected void tarFile(File file, TarOutputStream tOut, String vPath,
  304. TarFileSet tarFileSet)
  305. throws IOException {
  306. if (file.equals(tarFile)) {
  307. // If the archive is built for the first time and it is
  308. // matched by a resource collection, then it hasn't been
  309. // found in check (it hasn't been there) but will be
  310. // included now.
  311. //
  312. // for some strange reason the old code would simply skip
  313. // the entry and not fail, do the same now for backwards
  314. // compatibility reasons. Without this, the which4j build
  315. // fails in Gump
  316. return;
  317. }
  318. tarResource(new FileResource(file), tOut, vPath, tarFileSet);
  319. }
  320. /**
  321. * tar a resource
  322. * @param r the resource to tar
  323. * @param tOut the output stream
  324. * @param vPath the path name of the file to tar
  325. * @param tarFileSet the fileset that the file came from, may be null.
  326. * @throws IOException on error
  327. * @since Ant 1.7
  328. */
  329. protected void tarResource(Resource r, TarOutputStream tOut, String vPath,
  330. TarFileSet tarFileSet)
  331. throws IOException {
  332. if (!r.isExists()) {
  333. return;
  334. }
  335. boolean preserveLeadingSlashes = false;
  336. if (tarFileSet != null) {
  337. String fullpath = tarFileSet.getFullpath(this.getProject());
  338. if (fullpath.length() > 0) {
  339. vPath = fullpath;
  340. } else {
  341. // don't add "" to the archive
  342. if (vPath.length() <= 0) {
  343. return;
  344. }
  345. String prefix = tarFileSet.getPrefix(this.getProject());
  346. // '/' is appended for compatibility with the zip task.
  347. if (prefix.length() > 0 && !prefix.endsWith("/")) {
  348. prefix = prefix + "/";
  349. }
  350. vPath = prefix + vPath;
  351. }
  352. preserveLeadingSlashes = tarFileSet.getPreserveLeadingSlashes();
  353. if (vPath.startsWith("/") && !preserveLeadingSlashes) {
  354. int l = vPath.length();
  355. if (l <= 1) {
  356. // we would end up adding "" to the archive
  357. return;
  358. }
  359. vPath = vPath.substring(1, l);
  360. }
  361. }
  362. if (r.isDirectory() && !vPath.endsWith("/")) {
  363. vPath += "/";
  364. }
  365. if (vPath.length() >= TarConstants.NAMELEN) {
  366. if (longFileMode.isOmitMode()) {
  367. log("Omitting: " + vPath, Project.MSG_INFO);
  368. return;
  369. } else if (longFileMode.isWarnMode()) {
  370. log("Entry: " + vPath + " longer than "
  371. + TarConstants.NAMELEN + " characters.",
  372. Project.MSG_WARN);
  373. if (!longWarningGiven) {
  374. log("Resulting tar file can only be processed "
  375. + "successfully by GNU compatible tar commands",
  376. Project.MSG_WARN);
  377. longWarningGiven = true;
  378. }
  379. } else if (longFileMode.isFailMode()) {
  380. throw new BuildException("Entry: " + vPath
  381. + " longer than " + TarConstants.NAMELEN
  382. + "characters.", getLocation());
  383. }
  384. }
  385. TarEntry te = new TarEntry(vPath, preserveLeadingSlashes);
  386. te.setModTime(r.getLastModified());
  387. // preserve permissions
  388. if (r instanceof ArchiveResource) {
  389. ArchiveResource ar = (ArchiveResource) r;
  390. te.setMode(ar.getMode());
  391. if (r instanceof TarResource) {
  392. TarResource tr = (TarResource) r;
  393. te.setUserName(tr.getUserName());
  394. te.setUserId(tr.getUid());
  395. te.setGroupName(tr.getGroup());
  396. te.setGroupId(tr.getGid());
  397. }
  398. }
  399. if (!r.isDirectory()) {
  400. if (r.size() > TarConstants.MAXSIZE) {
  401. throw new BuildException(
  402. "Resource: " + r + " larger than "
  403. + TarConstants.MAXSIZE + " bytes.");
  404. }
  405. te.setSize(r.getSize());
  406. // override permissions if set explicitly
  407. if (tarFileSet != null && tarFileSet.hasFileModeBeenSet()) {
  408. te.setMode(tarFileSet.getMode());
  409. }
  410. } else if (tarFileSet != null && tarFileSet.hasDirModeBeenSet()) {
  411. // override permissions if set explicitly
  412. te.setMode(tarFileSet.getDirMode(this.getProject()));
  413. }
  414. if (tarFileSet != null) {
  415. // only override permissions if set explicitly
  416. if (tarFileSet.hasUserNameBeenSet()) {
  417. te.setUserName(tarFileSet.getUserName());
  418. }
  419. if (tarFileSet.hasGroupBeenSet()) {
  420. te.setGroupName(tarFileSet.getGroup());
  421. }
  422. if (tarFileSet.hasUserIdBeenSet()) {
  423. te.setUserId(tarFileSet.getUid());
  424. }
  425. if (tarFileSet.hasGroupIdBeenSet()) {
  426. te.setGroupId(tarFileSet.getGid());
  427. }
  428. }
  429. InputStream in = null;
  430. try {
  431. tOut.putNextEntry(te);
  432. if (!r.isDirectory()) {
  433. in = r.getInputStream();
  434. byte[] buffer = new byte[BUFFER_SIZE];
  435. int count = 0;
  436. do {
  437. tOut.write(buffer, 0, count);
  438. count = in.read(buffer, 0, buffer.length);
  439. } while (count != -1);
  440. }
  441. tOut.closeEntry();
  442. } finally {
  443. FileUtils.close(in);
  444. }
  445. }
  446. /**
  447. * Is the archive up to date in relationship to a list of files.
  448. * @param files the files to check
  449. * @return true if the archive is up to date.
  450. * @deprecated since 1.5.x.
  451. * use the two-arg version instead.
  452. */
  453. protected boolean archiveIsUpToDate(String[] files) {
  454. return archiveIsUpToDate(files, baseDir);
  455. }
  456. /**
  457. * Is the archive up to date in relationship to a list of files.
  458. * @param files the files to check
  459. * @param dir the base directory for the files.
  460. * @return true if the archive is up to date.
  461. * @since Ant 1.5.2
  462. */
  463. protected boolean archiveIsUpToDate(String[] files, File dir) {
  464. SourceFileScanner sfs = new SourceFileScanner(this);
  465. MergingMapper mm = new MergingMapper();
  466. mm.setTo(tarFile.getAbsolutePath());
  467. return sfs.restrict(files, dir, null, mm).length == 0;
  468. }
  469. /**
  470. * Is the archive up to date in relationship to a list of files.
  471. * @param r the files to check
  472. * @return true if the archive is up to date.
  473. * @since Ant 1.7
  474. */
  475. protected boolean archiveIsUpToDate(Resource r) {
  476. return SelectorUtils.isOutOfDate(new FileResource(tarFile), r,
  477. FileUtils.getFileUtils()
  478. .getFileTimestampGranularity());
  479. }
  480. /**
  481. * Whether this task can deal with non-file resources.
  482. *
  483. * <p>This implementation returns true only if this task is
  484. * &lt;tar&gt;. Any subclass of this class that also wants to
  485. * support non-file resources needs to override this method. We
  486. * need to do so for backwards compatibility reasons since we
  487. * can't expect subclasses to support resources.</p>
  488. * @return true for this task.
  489. * @since Ant 1.7
  490. */
  491. protected boolean supportsNonFileResources() {
  492. return getClass().equals(Tar.class);
  493. }
  494. /**
  495. * Checks whether the archive is out-of-date with respect to the resources
  496. * of the given collection.
  497. *
  498. * <p>Also checks that either all collections only contain file
  499. * resources or this class supports non-file collections.</p>
  500. *
  501. * <p>And - in case of file-collections - ensures that the archive won't
  502. * contain itself.</p>
  503. *
  504. * @param rc the resource collection to check
  505. * @return whether the archive is up-to-date
  506. * @since Ant 1.7
  507. */
  508. protected boolean check(ResourceCollection rc) {
  509. boolean upToDate = true;
  510. if (isFileFileSet(rc)) {
  511. FileSet fs = (FileSet) rc;
  512. upToDate = check(fs.getDir(getProject()), getFileNames(fs));
  513. } else if (!rc.isFilesystemOnly() && !supportsNonFileResources()) {
  514. throw new BuildException("only filesystem resources are supported");
  515. } else if (rc.isFilesystemOnly()) {
  516. HashSet basedirs = new HashSet();
  517. HashMap basedirToFilesMap = new HashMap();
  518. Iterator iter = rc.iterator();
  519. while (iter.hasNext()) {
  520. Resource res = (Resource) iter.next();
  521. FileResource r = ResourceUtils
  522. .asFileResource((FileProvider) res.as(FileProvider.class));
  523. File base = r.getBaseDir();
  524. if (base == null) {
  525. base = Copy.NULL_FILE_PLACEHOLDER;
  526. }
  527. basedirs.add(base);
  528. Vector files = (Vector) basedirToFilesMap.get(base);
  529. if (files == null) {
  530. files = new Vector();
  531. basedirToFilesMap.put(base, files);
  532. }
  533. if (base == Copy.NULL_FILE_PLACEHOLDER) {
  534. files.add(r.getFile().getAbsolutePath());
  535. } else {
  536. files.add(r.getName());
  537. }
  538. }
  539. iter = basedirs.iterator();
  540. while (iter.hasNext()) {
  541. File base = (File) iter.next();
  542. Vector f = (Vector) basedirToFilesMap.get(base);
  543. String[] files = (String[]) f.toArray(new String[f.size()]);
  544. upToDate &=
  545. check(base == Copy.NULL_FILE_PLACEHOLDER ? null : base,
  546. files);
  547. }
  548. } else { // non-file resources
  549. Iterator iter = rc.iterator();
  550. while (upToDate && iter.hasNext()) {
  551. Resource r = (Resource) iter.next();
  552. upToDate = archiveIsUpToDate(r);
  553. }
  554. }
  555. return upToDate;
  556. }
  557. /**
  558. * Checks whether the archive is out-of-date with respect to the
  559. * given files, ensures that the archive won't contain itself.</p>
  560. *
  561. * @param basedir base directory for file names
  562. * @param files array of relative file names
  563. * @return whether the archive is up-to-date
  564. * @since Ant 1.7
  565. */
  566. protected boolean check(File basedir, String[] files) {
  567. boolean upToDate = true;
  568. if (!archiveIsUpToDate(files, basedir)) {
  569. upToDate = false;
  570. }
  571. for (int i = 0; i < files.length; ++i) {
  572. if (tarFile.equals(new File(basedir, files[i]))) {
  573. throw new BuildException("A tar file cannot include "
  574. + "itself", getLocation());
  575. }
  576. }
  577. return upToDate;
  578. }
  579. /**
  580. * Adds the resources contained in this collection to the archive.
  581. *
  582. * <p>Uses the file based methods for file resources for backwards
  583. * compatibility.</p>
  584. *
  585. * @param rc the collection containing resources to add
  586. * @param tOut stream writing to the archive.
  587. * @throws IOException on error.
  588. * @since Ant 1.7
  589. */
  590. protected void tar(ResourceCollection rc, TarOutputStream tOut)
  591. throws IOException {
  592. ArchiveFileSet afs = null;
  593. if (rc instanceof ArchiveFileSet) {
  594. afs = (ArchiveFileSet) rc;
  595. }
  596. if (afs != null && afs.size() > 1
  597. && afs.getFullpath(this.getProject()).length() > 0) {
  598. throw new BuildException("fullpath attribute may only "
  599. + "be specified for "
  600. + "filesets that specify a "
  601. + "single file.");
  602. }
  603. TarFileSet tfs = asTarFileSet(afs);
  604. if (isFileFileSet(rc)) {
  605. FileSet fs = (FileSet) rc;
  606. String[] files = getFileNames(fs);
  607. for (int i = 0; i < files.length; i++) {
  608. File f = new File(fs.getDir(getProject()), files[i]);
  609. String name = files[i].replace(File.separatorChar, '/');
  610. tarFile(f, tOut, name, tfs);
  611. }
  612. } else if (rc.isFilesystemOnly()) {
  613. Iterator iter = rc.iterator();
  614. while (iter.hasNext()) {
  615. Resource r = (Resource) iter.next();
  616. File f = ((FileProvider) r.as(FileProvider.class)).getFile();
  617. tarFile(f, tOut, f.getName(), tfs);
  618. }
  619. } else { // non-file resources
  620. Iterator iter = rc.iterator();
  621. while (iter.hasNext()) {
  622. Resource r = (Resource) iter.next();
  623. tarResource(r, tOut, r.getName(), tfs);
  624. }
  625. }
  626. }
  627. /**
  628. * whether the given resource collection is a (subclass of)
  629. * FileSet that only contains file system resources.
  630. * @param rc the resource collection to check.
  631. * @return true if the collection is a fileset.
  632. * @since Ant 1.7
  633. */
  634. protected static boolean isFileFileSet(ResourceCollection rc) {
  635. return rc instanceof FileSet && rc.isFilesystemOnly();
  636. }
  637. /**
  638. * Grabs all included files and directors from the FileSet and
  639. * returns them as an array of (relative) file names.
  640. * @param fs the fileset to operate on.
  641. * @return a list of the filenames.
  642. * @since Ant 1.7
  643. */
  644. protected static String[] getFileNames(FileSet fs) {
  645. DirectoryScanner ds = fs.getDirectoryScanner(fs.getProject());
  646. String[] directories = ds.getIncludedDirectories();
  647. String[] filesPerSe = ds.getIncludedFiles();
  648. String[] files = new String [directories.length + filesPerSe.length];
  649. System.arraycopy(directories, 0, files, 0, directories.length);
  650. System.arraycopy(filesPerSe, 0, files, directories.length,
  651. filesPerSe.length);
  652. return files;
  653. }
  654. /**
  655. * Copies fullpath, prefix and permission attributes from the
  656. * ArchiveFileSet to a new TarFileSet (or returns it unchanged if
  657. * it already is a TarFileSet).
  658. *
  659. * @param archiveFileSet fileset to copy attributes from, may be null
  660. * @return a new TarFileSet.
  661. * @since Ant 1.7
  662. */
  663. protected TarFileSet asTarFileSet(ArchiveFileSet archiveFileSet) {
  664. TarFileSet tfs = null;
  665. if (archiveFileSet != null && archiveFileSet instanceof TarFileSet) {
  666. tfs = (TarFileSet) archiveFileSet;
  667. } else {
  668. tfs = new TarFileSet();
  669. tfs.setProject(getProject());
  670. if (archiveFileSet != null) {
  671. tfs.setPrefix(archiveFileSet.getPrefix(getProject()));
  672. tfs.setFullpath(archiveFileSet.getFullpath(getProject()));
  673. if (archiveFileSet.hasFileModeBeenSet()) {
  674. tfs.integerSetFileMode(archiveFileSet
  675. .getFileMode(getProject()));
  676. }
  677. if (archiveFileSet.hasDirModeBeenSet()) {
  678. tfs.integerSetDirMode(archiveFileSet
  679. .getDirMode(getProject()));
  680. }
  681. if (archiveFileSet
  682. instanceof org.apache.tools.ant.types.TarFileSet) {
  683. org.apache.tools.ant.types.TarFileSet t =
  684. (org.apache.tools.ant.types.TarFileSet) archiveFileSet;
  685. if (t.hasUserNameBeenSet()) {
  686. tfs.setUserName(t.getUserName());
  687. }
  688. if (t.hasGroupBeenSet()) {
  689. tfs.setGroup(t.getGroup());
  690. }
  691. if (t.hasUserIdBeenSet()) {
  692. tfs.setUid(t.getUid());
  693. }
  694. if (t.hasGroupIdBeenSet()) {
  695. tfs.setGid(t.getGid());
  696. }
  697. }
  698. }
  699. }
  700. return tfs;
  701. }
  702. /**
  703. * This is a FileSet with the option to specify permissions
  704. * and other attributes.
  705. */
  706. public static class TarFileSet
  707. extends org.apache.tools.ant.types.TarFileSet {
  708. private String[] files = null;
  709. private boolean preserveLeadingSlashes = false;
  710. /**
  711. * Creates a new <code>TarFileSet</code> instance.
  712. * Using a fileset as a constructor argument.
  713. *
  714. * @param fileset a <code>FileSet</code> value
  715. */
  716. public TarFileSet(FileSet fileset) {
  717. super(fileset);
  718. }
  719. /**
  720. * Creates a new <code>TarFileSet</code> instance.
  721. *
  722. */
  723. public TarFileSet() {
  724. super();
  725. }
  726. /**
  727. * Get a list of files and directories specified in the fileset.
  728. * @param p the current project.
  729. * @return a list of file and directory names, relative to
  730. * the baseDir for the project.
  731. */
  732. public String[] getFiles(Project p) {
  733. if (files == null) {
  734. files = getFileNames(this);
  735. }
  736. return files;
  737. }
  738. /**
  739. * A 3 digit octal string, specify the user, group and
  740. * other modes in the standard Unix fashion;
  741. * optional, default=0644
  742. * @param octalString a 3 digit octal string.
  743. */
  744. public void setMode(String octalString) {
  745. setFileMode(octalString);
  746. }
  747. /**
  748. * @return the current mode.
  749. */
  750. public int getMode() {
  751. return getFileMode(this.getProject());
  752. }
  753. /**
  754. * Flag to indicates whether leading `/'s should
  755. * be preserved in the file names.
  756. * Optional, default is <code>false</code>.
  757. * @param b the leading slashes flag.
  758. */
  759. public void setPreserveLeadingSlashes(boolean b) {
  760. this.preserveLeadingSlashes = b;
  761. }
  762. /**
  763. * @return the leading slashes flag.
  764. */
  765. public boolean getPreserveLeadingSlashes() {
  766. return preserveLeadingSlashes;
  767. }
  768. }
  769. /**
  770. * Set of options for long file handling in the task.
  771. *
  772. */
  773. public static class TarLongFileMode extends EnumeratedAttribute {
  774. /** permissible values for longfile attribute */
  775. public static final String
  776. WARN = "warn",
  777. FAIL = "fail",
  778. TRUNCATE = "truncate",
  779. GNU = "gnu",
  780. OMIT = "omit";
  781. private final String[] validModes = {WARN, FAIL, TRUNCATE, GNU, OMIT};
  782. /** Constructor, defaults to "warn" */
  783. public TarLongFileMode() {
  784. super();
  785. setValue(WARN);
  786. }
  787. /**
  788. * @return the possible values for this enumerated type.
  789. */
  790. public String[] getValues() {
  791. return validModes;
  792. }
  793. /**
  794. * @return true if value is "truncate".
  795. */
  796. public boolean isTruncateMode() {
  797. return TRUNCATE.equalsIgnoreCase(getValue());
  798. }
  799. /**
  800. * @return true if value is "warn".
  801. */
  802. public boolean isWarnMode() {
  803. return WARN.equalsIgnoreCase(getValue());
  804. }
  805. /**
  806. * @return true if value is "gnu".
  807. */
  808. public boolean isGnuMode() {
  809. return GNU.equalsIgnoreCase(getValue());
  810. }
  811. /**
  812. * @return true if value is "fail".
  813. */
  814. public boolean isFailMode() {
  815. return FAIL.equalsIgnoreCase(getValue());
  816. }
  817. /**
  818. * @return true if value is "omit".
  819. */
  820. public boolean isOmitMode() {
  821. return OMIT.equalsIgnoreCase(getValue());
  822. }
  823. }
  824. /**
  825. * Valid Modes for Compression attribute to Tar Task
  826. *
  827. */
  828. public static final class TarCompressionMethod extends EnumeratedAttribute {
  829. // permissible values for compression attribute
  830. /**
  831. * No compression
  832. */
  833. private static final String NONE = "none";
  834. /**
  835. * GZIP compression
  836. */
  837. private static final String GZIP = "gzip";
  838. /**
  839. * BZIP2 compression
  840. */
  841. private static final String BZIP2 = "bzip2";
  842. /**
  843. * Default constructor
  844. */
  845. public TarCompressionMethod() {
  846. super();
  847. setValue(NONE);
  848. }
  849. /**
  850. * Get valid enumeration values.
  851. * @return valid enumeration values
  852. */
  853. public String[] getValues() {
  854. return new String[] {NONE, GZIP, BZIP2 };
  855. }
  856. /**
  857. * This method wraps the output stream with the
  858. * corresponding compression method
  859. *
  860. * @param ostream output stream
  861. * @return output stream with on-the-fly compression
  862. * @exception IOException thrown if file is not writable
  863. */
  864. private OutputStream compress(final OutputStream ostream)
  865. throws IOException {
  866. final String v = getValue();
  867. if (GZIP.equals(v)) {
  868. return new GZIPOutputStream(ostream);
  869. } else {
  870. if (BZIP2.equals(v)) {
  871. ostream.write('B');
  872. ostream.write('Z');
  873. return new CBZip2OutputStream(ostream);
  874. }
  875. }
  876. return ostream;
  877. }
  878. }
  879. }