Filesystem.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  1. <?php
  2. /*
  3. * This file is part of Composer.
  4. *
  5. * (c) Nils Adermann <naderman@naderman.de>
  6. * Jordi Boggiano <j.boggiano@seld.be>
  7. *
  8. * For the full copyright and license information, please view the LICENSE
  9. * file that was distributed with this source code.
  10. */
  11. namespace Composer\Util;
  12. use RecursiveDirectoryIterator;
  13. use RecursiveIteratorIterator;
  14. /**
  15. * @author Jordi Boggiano <j.boggiano@seld.be>
  16. * @author Johannes M. Schmitt <schmittjoh@gmail.com>
  17. */
  18. class Filesystem
  19. {
  20. private $processExecutor;
  21. public function __construct(ProcessExecutor $executor = null)
  22. {
  23. $this->processExecutor = $executor ?: new ProcessExecutor();
  24. }
  25. public function remove($file)
  26. {
  27. if (is_dir($file)) {
  28. return $this->removeDirectory($file);
  29. }
  30. if (file_exists($file)) {
  31. return unlink($file);
  32. }
  33. return false;
  34. }
  35. /**
  36. * Recursively remove a directory
  37. *
  38. * Uses the process component if proc_open is enabled on the PHP
  39. * installation.
  40. *
  41. * @param string $directory
  42. * @return bool
  43. */
  44. public function removeDirectory($directory)
  45. {
  46. if (!is_dir($directory)) {
  47. return true;
  48. }
  49. if (!function_exists('proc_open')) {
  50. return $this->removeDirectoryPhp($directory);
  51. }
  52. if (defined('PHP_WINDOWS_VERSION_BUILD')) {
  53. $cmd = sprintf('rmdir /S /Q %s', escapeshellarg(realpath($directory)));
  54. } else {
  55. $cmd = sprintf('rm -rf %s', escapeshellarg($directory));
  56. }
  57. $result = $this->getProcess()->execute($cmd, $output) === 0;
  58. // clear stat cache because external processes aren't tracked by the php stat cache
  59. clearstatcache();
  60. return $result && !is_dir($directory);
  61. }
  62. /**
  63. * Recursively delete directory using PHP iterators.
  64. *
  65. * Uses a CHILD_FIRST RecursiveIteratorIterator to sort files
  66. * before directories, creating a single non-recursive loop
  67. * to delete files/directories in the correct order.
  68. *
  69. * @param string $directory
  70. * @return bool
  71. */
  72. public function removeDirectoryPhp($directory)
  73. {
  74. $it = new RecursiveDirectoryIterator($directory, RecursiveDirectoryIterator::SKIP_DOTS);
  75. $ri = new RecursiveIteratorIterator($it, RecursiveIteratorIterator::CHILD_FIRST);
  76. foreach ($ri as $file) {
  77. if ($file->isDir()) {
  78. rmdir($file->getPathname());
  79. } else {
  80. unlink($file->getPathname());
  81. }
  82. }
  83. return rmdir($directory);
  84. }
  85. public function ensureDirectoryExists($directory)
  86. {
  87. if (!is_dir($directory)) {
  88. if (file_exists($directory)) {
  89. throw new \RuntimeException(
  90. $directory.' exists and is not a directory.'
  91. );
  92. }
  93. if (!@mkdir($directory, 0777, true)) {
  94. throw new \RuntimeException(
  95. $directory.' does not exist and could not be created.'
  96. );
  97. }
  98. }
  99. }
  100. /**
  101. * Copy then delete is a non-atomic version of {@link rename}.
  102. *
  103. * Some systems can't rename and also don't have proc_open,
  104. * which requires this solution.
  105. *
  106. * @param string $source
  107. * @param string $target
  108. */
  109. public function copyThenRemove($source, $target)
  110. {
  111. $it = new RecursiveDirectoryIterator($source, RecursiveDirectoryIterator::SKIP_DOTS);
  112. $ri = new RecursiveIteratorIterator($it, RecursiveIteratorIterator::SELF_FIRST);
  113. if (!file_exists($target)) {
  114. mkdir($target, 0777, true);
  115. }
  116. foreach ($ri as $file) {
  117. $targetPath = $target . DIRECTORY_SEPARATOR . $ri->getSubPathName();
  118. if ($file->isDir()) {
  119. mkdir($targetPath);
  120. } else {
  121. copy($file->getPathname(), $targetPath);
  122. }
  123. }
  124. $this->removeDirectoryPhp($source);
  125. }
  126. public function rename($source, $target)
  127. {
  128. if (true === @rename($source, $target)) {
  129. return;
  130. }
  131. if (!function_exists('proc_open')) {
  132. return $this->copyThenRemove($source, $target);
  133. }
  134. if (defined('PHP_WINDOWS_VERSION_BUILD')) {
  135. // Try to copy & delete - this is a workaround for random "Access denied" errors.
  136. $command = sprintf('xcopy %s %s /E /I /Q', escapeshellarg($source), escapeshellarg($target));
  137. $result = $this->processExecutor->execute($command, $output);
  138. // clear stat cache because external processes aren't tracked by the php stat cache
  139. clearstatcache();
  140. if (0 === $result) {
  141. $this->remove($source);
  142. return;
  143. }
  144. return $this->copyThenRemove($source, $target);
  145. } else {
  146. // We do not use PHP's "rename" function here since it does not support
  147. // the case where $source, and $target are located on different partitions.
  148. $command = sprintf('mv %s %s', escapeshellarg($source), escapeshellarg($target));
  149. $result = $this->processExecutor->execute($command, $output);
  150. // clear stat cache because external processes aren't tracked by the php stat cache
  151. clearstatcache();
  152. if (0 === $result) {
  153. return;
  154. }
  155. }
  156. throw new \RuntimeException(sprintf('Could not rename "%s" to "%s".', $source, $target));
  157. }
  158. /**
  159. * Returns the shortest path from $from to $to
  160. *
  161. * @param string $from
  162. * @param string $to
  163. * @param bool $directories if true, the source/target are considered to be directories
  164. * @return string
  165. */
  166. public function findShortestPath($from, $to, $directories = false)
  167. {
  168. if (!$this->isAbsolutePath($from) || !$this->isAbsolutePath($to)) {
  169. throw new \InvalidArgumentException(sprintf('$from (%s) and $to (%s) must be absolute paths.', $from, $to));
  170. }
  171. $from = lcfirst($this->normalizePath($from));
  172. $to = lcfirst($this->normalizePath($to));
  173. if ($directories) {
  174. $from .= '/dummy_file';
  175. }
  176. if (dirname($from) === dirname($to)) {
  177. return './'.basename($to);
  178. }
  179. $commonPath = $to;
  180. while (strpos($from, $commonPath) !== 0 && '/' !== $commonPath && !preg_match('{^[a-z]:/?$}i', $commonPath) && '.' !== $commonPath) {
  181. $commonPath = strtr(dirname($commonPath), '\\', '/');
  182. }
  183. if (0 !== strpos($from, $commonPath) || '/' === $commonPath || '.' === $commonPath) {
  184. return $to;
  185. }
  186. $commonPath = rtrim($commonPath, '/') . '/';
  187. $sourcePathDepth = substr_count(substr($from, strlen($commonPath)), '/');
  188. $commonPathCode = str_repeat('../', $sourcePathDepth);
  189. return ($commonPathCode . substr($to, strlen($commonPath))) ?: './';
  190. }
  191. /**
  192. * Returns PHP code that, when executed in $from, will return the path to $to
  193. *
  194. * @param string $from
  195. * @param string $to
  196. * @param bool $directories if true, the source/target are considered to be directories
  197. * @return string
  198. */
  199. public function findShortestPathCode($from, $to, $directories = false)
  200. {
  201. if (!$this->isAbsolutePath($from) || !$this->isAbsolutePath($to)) {
  202. throw new \InvalidArgumentException(sprintf('$from (%s) and $to (%s) must be absolute paths.', $from, $to));
  203. }
  204. $from = lcfirst($this->normalizePath($from));
  205. $to = lcfirst($this->normalizePath($to));
  206. if ($from === $to) {
  207. return $directories ? '__DIR__' : '__FILE__';
  208. }
  209. $commonPath = $to;
  210. while (strpos($from, $commonPath) !== 0 && '/' !== $commonPath && !preg_match('{^[a-z]:/?$}i', $commonPath) && '.' !== $commonPath) {
  211. $commonPath = strtr(dirname($commonPath), '\\', '/');
  212. }
  213. if (0 !== strpos($from, $commonPath) || '/' === $commonPath || '.' === $commonPath) {
  214. return var_export($to, true);
  215. }
  216. $commonPath = rtrim($commonPath, '/') . '/';
  217. if (strpos($to, $from.'/') === 0) {
  218. return '__DIR__ . '.var_export(substr($to, strlen($from)), true);
  219. }
  220. $sourcePathDepth = substr_count(substr($from, strlen($commonPath)), '/') + $directories;
  221. $commonPathCode = str_repeat('dirname(', $sourcePathDepth).'__DIR__'.str_repeat(')', $sourcePathDepth);
  222. $relTarget = substr($to, strlen($commonPath));
  223. return $commonPathCode . (strlen($relTarget) ? '.' . var_export('/' . $relTarget, true) : '');
  224. }
  225. /**
  226. * Checks if the given path is absolute
  227. *
  228. * @param string $path
  229. * @return bool
  230. */
  231. public function isAbsolutePath($path)
  232. {
  233. return substr($path, 0, 1) === '/' || substr($path, 1, 1) === ':';
  234. }
  235. /**
  236. * Returns size of a file or directory specified by path. If a directory is
  237. * given, it's size will be computed recursively.
  238. *
  239. * @param string $path Path to the file or directory
  240. * @return int
  241. */
  242. public function size($path)
  243. {
  244. if (!file_exists($path)) {
  245. throw new \RuntimeException("$path does not exist.");
  246. }
  247. if (is_dir($path)) {
  248. return $this->directorySize($path);
  249. }
  250. return filesize($path);
  251. }
  252. /**
  253. * Normalize a path. This replaces backslashes with slashes, removes ending
  254. * slash and collapses redundant separators and up-level references.
  255. *
  256. * @param string $path Path to the file or directory
  257. * @return string
  258. */
  259. public function normalizePath($path)
  260. {
  261. $parts = array();
  262. $path = strtr($path, '\\', '/');
  263. $prefix = '';
  264. if (preg_match('{^((?:[0-9a-z]+://)?(?:[a-z]:)?/)}i', $path, $match)) {
  265. $prefix = $match[1];
  266. $path = substr($path, strlen($prefix));
  267. }
  268. foreach (explode('/', $path) as $chunk) {
  269. if ('..' === $chunk) {
  270. array_pop($parts);
  271. } elseif ('.' !== $chunk && '' !== $chunk) {
  272. $parts[] = $chunk;
  273. }
  274. }
  275. return $prefix.implode('/', $parts);
  276. }
  277. protected function directorySize($directory)
  278. {
  279. $it = new RecursiveDirectoryIterator($directory, RecursiveDirectoryIterator::SKIP_DOTS);
  280. $ri = new RecursiveIteratorIterator($it, RecursiveIteratorIterator::CHILD_FIRST);
  281. $size = 0;
  282. foreach ($ri as $file) {
  283. if ($file->isFile()) {
  284. $size += $file->getSize();
  285. }
  286. }
  287. return $size;
  288. }
  289. protected function getProcess()
  290. {
  291. return new ProcessExecutor;
  292. }
  293. }