CopyTask.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458
  1. <?php
  2. /*
  3. * $Id: CopyTask.php 905 2010-10-05 16:28:03Z mrook $
  4. *
  5. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  6. * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  7. * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  8. * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  9. * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  10. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  11. * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  12. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  13. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  14. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  15. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  16. *
  17. * This software consists of voluntary contributions made by many individuals
  18. * and is licensed under the LGPL. For more information please see
  19. * <http://phing.info>.
  20. */
  21. require_once 'phing/Task.php';
  22. include_once 'phing/system/io/PhingFile.php';
  23. include_once 'phing/util/FileUtils.php';
  24. include_once 'phing/util/SourceFileScanner.php';
  25. include_once 'phing/mappers/IdentityMapper.php';
  26. include_once 'phing/mappers/FlattenMapper.php';
  27. /**
  28. * A phing copy task. Copies a file or directory to a new file
  29. * or directory. Files are only copied if the source file is newer
  30. * than the destination file, or when the destination file does not
  31. * exist. It is possible to explictly overwrite existing files.
  32. *
  33. * @author Andreas Aderhold, andi@binarycloud.com
  34. * @version $Revision: 905 $ $Date: 2010-10-05 18:28:03 +0200 (Tue, 05 Oct 2010) $
  35. * @package phing.tasks.system
  36. */
  37. class CopyTask extends Task {
  38. protected $file = null; // the source file (from xml attribute)
  39. protected $destFile = null; // the destiantion file (from xml attribute)
  40. protected $destDir = null; // the destination dir (from xml attribute)
  41. protected $overwrite = false; // overwrite destination (from xml attribute)
  42. protected $preserveLMT = false; // sync timestamps (from xml attribute)
  43. protected $includeEmpty = true; // include empty dirs? (from XML)
  44. protected $flatten = false; // apply the FlattenMapper right way (from XML)
  45. protected $mapperElement = null;
  46. protected $fileCopyMap = array(); // asoc array containing mapped file names
  47. protected $dirCopyMap = array(); // asoc array containing mapped file names
  48. protected $completeDirMap= array(); // asoc array containing complete dir names
  49. protected $fileUtils = null; // a instance of fileutils
  50. protected $filesets = array(); // all fileset objects assigned to this task
  51. protected $filelists = array(); // all filelist objects assigned to this task
  52. protected $filterChains = array(); // all filterchains objects assigned to this task
  53. protected $verbosity = Project::MSG_VERBOSE;
  54. protected $mode = 0755; // mode to create directories with
  55. /**
  56. * Sets up this object internal stuff. i.e. the Fileutils instance
  57. *
  58. * @return object The CopyTask instnace
  59. * @access public
  60. */
  61. function __construct() {
  62. $this->fileUtils = new FileUtils();
  63. }
  64. /**
  65. * Set the overwrite flag. IntrospectionHelper takes care of
  66. * booleans in set* methods so we can assume that the right
  67. * value (boolean primitive) is coming in here.
  68. *
  69. * @param boolean Overwrite the destination file(s) if it/they already exist
  70. * @return void
  71. * @access public
  72. */
  73. function setOverwrite($bool) {
  74. $this->overwrite = (boolean) $bool;
  75. }
  76. /**
  77. * Used to force listing of all names of copied files.
  78. * @param boolean $verbosity
  79. */
  80. function setVerbose($verbosity) {
  81. if ($verbosity) {
  82. $this->verbosity = Project::MSG_INFO;
  83. } else {
  84. $this->verbosity = Project::MSG_VERBOSE;
  85. }
  86. }
  87. /**
  88. * @see CopyTask::setPreserveLastModified
  89. */
  90. function setTstamp($bool) {
  91. $this->setPreserveLastModified($bool);
  92. }
  93. /**
  94. * Set the preserve timestamp flag. IntrospectionHelper takes care of
  95. * booleans in set* methods so we can assume that the right
  96. * value (boolean primitive) is coming in here.
  97. *
  98. * @param boolean Preserve the timestamp on the destination file
  99. * @return void
  100. * @access public
  101. */
  102. function setPreserveLastModified($bool) {
  103. $this->preserveLMT = (boolean) $bool;
  104. }
  105. /**
  106. * Set the include empty dirs flag. IntrospectionHelper takes care of
  107. * booleans in set* methods so we can assume that the right
  108. * value (boolean primitive) is coming in here.
  109. *
  110. * @param boolean Flag if empty dirs should be cpoied too
  111. * @return void
  112. * @access public
  113. */
  114. function setIncludeEmptyDirs($bool) {
  115. $this->includeEmpty = (boolean) $bool;
  116. }
  117. /**
  118. * Set the file. We have to manually take care of the
  119. * type that is coming due to limited type support in php
  120. * in and convert it manually if neccessary.
  121. *
  122. * @param string/object The source file. Either a string or an PhingFile object
  123. * @return void
  124. * @access public
  125. */
  126. function setFile(PhingFile $file) {
  127. $this->file = $file;
  128. }
  129. /**
  130. * Set the toFile. We have to manually take care of the
  131. * type that is coming due to limited type support in php
  132. * in and convert it manually if neccessary.
  133. *
  134. * @param string/object The dest file. Either a string or an PhingFile object
  135. * @return void
  136. * @access public
  137. */
  138. function setTofile(PhingFile $file) {
  139. $this->destFile = $file;
  140. }
  141. /**
  142. * Sets the mode to create destination directories with (ignored on Windows).
  143. * Default mode is 0755.
  144. *
  145. * @param integer Octal mode
  146. * @return void
  147. * @access public
  148. */
  149. function setMode($mode) {
  150. $this->mode = (int) base_convert($mode, 8, 10);
  151. }
  152. /**
  153. * Set the toDir. We have to manually take care of the
  154. * type that is coming due to limited type support in php
  155. * in and convert it manually if neccessary.
  156. *
  157. * @param string/object The directory, either a string or an PhingFile object
  158. * @return void
  159. * @access public
  160. */
  161. function setTodir(PhingFile $dir) {
  162. $this->destDir = $dir;
  163. }
  164. /**
  165. * Nested creator, creates a FileSet for this task
  166. *
  167. * @access public
  168. * @return object The created fileset object
  169. */
  170. function createFileSet() {
  171. $num = array_push($this->filesets, new FileSet());
  172. return $this->filesets[$num-1];
  173. }
  174. /**
  175. * Nested creator, adds a set of files (nested fileset attribute).
  176. *
  177. * @access public
  178. * @return object The created filelist object
  179. */
  180. function createFileList() {
  181. $num = array_push($this->filelists, new FileList());
  182. return $this->filelists[$num-1];
  183. }
  184. /**
  185. * Creates a filterchain
  186. *
  187. * @access public
  188. * @return object The created filterchain object
  189. */
  190. function createFilterChain() {
  191. $num = array_push($this->filterChains, new FilterChain($this->project));
  192. return $this->filterChains[$num-1];
  193. }
  194. /**
  195. * Nested creator, creates one Mapper for this task
  196. *
  197. * @access public
  198. * @return object The created Mapper type object
  199. * @throws BuildException
  200. */
  201. function createMapper() {
  202. if ($this->mapperElement !== null) {
  203. throw new BuildException("Cannot define more than one mapper", $this->location);
  204. }
  205. $this->mapperElement = new Mapper($this->project);
  206. return $this->mapperElement;
  207. }
  208. /**
  209. * The main entry point where everything gets in motion.
  210. *
  211. * @access public
  212. * @return true on success
  213. * @throws BuildException
  214. */
  215. function main() {
  216. $this->validateAttributes();
  217. if ($this->file !== null) {
  218. if ($this->file->exists()) {
  219. if ($this->destFile === null) {
  220. $this->destFile = new PhingFile($this->destDir, (string) $this->file->getName());
  221. }
  222. if ($this->overwrite === true || ($this->file->lastModified() > $this->destFile->lastModified())) {
  223. $this->fileCopyMap[$this->file->getAbsolutePath()] = $this->destFile->getAbsolutePath();
  224. } else {
  225. $this->log($this->file->getName()." omitted, is up to date");
  226. }
  227. } else {
  228. // terminate build
  229. throw new BuildException("Could not find file " . $this->file->__toString() . " to copy.");
  230. }
  231. }
  232. $project = $this->getProject();
  233. // process filelists
  234. foreach($this->filelists as $fl) {
  235. $fromDir = $fl->getDir($project);
  236. $srcFiles = $fl->getFiles($project);
  237. $srcDirs = array($fl->getDir($project));
  238. if (!$this->flatten && $this->mapperElement === null)
  239. {
  240. $this->completeDirMap[$fromDir->getAbsolutePath()] = $this->destDir->getAbsolutePath();
  241. }
  242. $this->_scan($fromDir, $this->destDir, $srcFiles, $srcDirs);
  243. }
  244. // process filesets
  245. foreach($this->filesets as $fs) {
  246. $ds = $fs->getDirectoryScanner($project);
  247. $fromDir = $fs->getDir($project);
  248. $srcFiles = $ds->getIncludedFiles();
  249. $srcDirs = $ds->getIncludedDirectories();
  250. if (!$this->flatten && $this->mapperElement === null)
  251. {
  252. $this->completeDirMap[$fromDir->getAbsolutePath()] = $this->destDir->getAbsolutePath();
  253. }
  254. $this->_scan($fromDir, $this->destDir, $srcFiles, $srcDirs);
  255. }
  256. // go and copy the stuff
  257. $this->doWork();
  258. if ($this->destFile !== null) {
  259. $this->destDir = null;
  260. }
  261. }
  262. /**
  263. * Validates attributes coming in from XML
  264. *
  265. * @access private
  266. * @return void
  267. * @throws BuildException
  268. */
  269. protected function validateAttributes() {
  270. if ($this->file === null && count($this->filesets) === 0 && count($this->filelists) === 0) {
  271. throw new BuildException("CopyTask. Specify at least one source - a file, fileset or filelist.");
  272. }
  273. if ($this->destFile !== null && $this->destDir !== null) {
  274. throw new BuildException("Only one of destfile and destdir may be set.");
  275. }
  276. if ($this->destFile === null && $this->destDir === null) {
  277. throw new BuildException("One of destfile or destdir must be set.");
  278. }
  279. if ($this->file !== null && $this->file->exists() && $this->file->isDirectory()) {
  280. throw new BuildException("Use a fileset to copy directories.");
  281. }
  282. if ($this->destFile !== null && count($this->filesets) > 0) {
  283. throw new BuildException("Cannot concatenate multple files into a single file.");
  284. }
  285. if ($this->destFile !== null) {
  286. $this->destDir = new PhingFile($this->destFile->getParent());
  287. }
  288. }
  289. /**
  290. * Compares source files to destination files to see if they
  291. * should be copied.
  292. *
  293. * @access private
  294. * @return void
  295. */
  296. private function _scan(&$fromDir, &$toDir, &$files, &$dirs) {
  297. /* mappers should be generic, so we get the mappers here and
  298. pass them on to builMap. This method is not redundan like it seems */
  299. $mapper = null;
  300. if ($this->mapperElement !== null) {
  301. $mapper = $this->mapperElement->getImplementation();
  302. } else if ($this->flatten) {
  303. $mapper = new FlattenMapper();
  304. } else {
  305. $mapper = new IdentityMapper();
  306. }
  307. $this->buildMap($fromDir, $toDir, $files, $mapper, $this->fileCopyMap);
  308. $this->buildMap($fromDir, $toDir, $dirs, $mapper, $this->dirCopyMap);
  309. }
  310. /**
  311. * Builds a map of filenames (from->to) that should be copied
  312. *
  313. * @access private
  314. * @return void
  315. */
  316. private function buildMap(&$fromDir, &$toDir, &$names, &$mapper, &$map) {
  317. $toCopy = null;
  318. if ($this->overwrite) {
  319. $v = array();
  320. foreach($names as $name) {
  321. $result = $mapper->main($name);
  322. if ($result !== null) {
  323. $v[] = $name;
  324. }
  325. }
  326. $toCopy = $v;
  327. } else {
  328. $ds = new SourceFileScanner($this);
  329. $toCopy = $ds->restrict($names, $fromDir, $toDir, $mapper);
  330. }
  331. for ($i=0,$_i=count($toCopy); $i < $_i; $i++) {
  332. $src = new PhingFile($fromDir, $toCopy[$i]);
  333. $mapped = $mapper->main($toCopy[$i]);
  334. $dest = new PhingFile($toDir, $mapped[0]);
  335. $map[$src->getAbsolutePath()] = $dest->getAbsolutePath();
  336. }
  337. }
  338. /**
  339. * Actually copies the files
  340. *
  341. * @access private
  342. * @return void
  343. * @throws BuildException
  344. */
  345. protected function doWork() {
  346. // These "slots" allow filters to retrieve information about the currently-being-process files
  347. $fromSlot = $this->getRegisterSlot("currentFromFile");
  348. $fromBasenameSlot = $this->getRegisterSlot("currentFromFile.basename");
  349. $toSlot = $this->getRegisterSlot("currentToFile");
  350. $toBasenameSlot = $this->getRegisterSlot("currentToFile.basename");
  351. $mapSize = count($this->fileCopyMap);
  352. $total = $mapSize;
  353. // handle empty dirs if appropriate
  354. if ($this->includeEmpty) {
  355. $count = 0;
  356. foreach ($this->dirCopyMap as $srcdir => $destdir) {
  357. $s = new PhingFile((string) $srcdir);
  358. $d = new PhingFile((string) $destdir);
  359. if (!$d->exists()) {
  360. if (!$d->mkdirs()) {
  361. $this->log("Unable to create directory " . $d->__toString(), Project::MSG_ERR);
  362. } else {
  363. if ($this->preserveLMT) {
  364. $d->setLastModified($s->lastModified());
  365. }
  366. $count++;
  367. }
  368. }
  369. }
  370. if ($count > 0) {
  371. $this->log("Created ".$count." empty director" . ($count == 1 ? "y" : "ies") . " in " . $this->destDir->getAbsolutePath());
  372. }
  373. }
  374. if ($mapSize > 0) {
  375. $this->log("Copying ".$mapSize." file".(($mapSize) === 1 ? '' : 's')." to ". $this->destDir->getAbsolutePath());
  376. // walks the map and actually copies the files
  377. $count=0;
  378. foreach($this->fileCopyMap as $from => $to) {
  379. if ($from === $to) {
  380. $this->log("Skipping self-copy of " . $from, $this->verbosity);
  381. $total--;
  382. continue;
  383. }
  384. $this->log("From ".$from." to ".$to, $this->verbosity);
  385. try { // try to copy file
  386. $fromFile = new PhingFile($from);
  387. $toFile = new PhingFile($to);
  388. $fromSlot->setValue($fromFile->getPath());
  389. $fromBasenameSlot->setValue($fromFile->getName());
  390. $toSlot->setValue($toFile->getPath());
  391. $toBasenameSlot->setValue($toFile->getName());
  392. $this->fileUtils->copyFile($fromFile, $toFile, $this->overwrite, $this->preserveLMT, $this->filterChains, $this->getProject(), $this->mode);
  393. $count++;
  394. } catch (IOException $ioe) {
  395. $this->log("Failed to copy " . $from . " to " . $to . ": " . $ioe->getMessage(), Project::MSG_ERR);
  396. }
  397. }
  398. }
  399. }
  400. }