Filesystem.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361
  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. } else {
  145. // We do not use PHP's "rename" function here since it does not support
  146. // the case where $source, and $target are located on different partitions.
  147. $command = sprintf('mv %s %s', escapeshellarg($source), escapeshellarg($target));
  148. $result = $this->processExecutor->execute($command, $output);
  149. // clear stat cache because external processes aren't tracked by the php stat cache
  150. clearstatcache();
  151. if (0 === $result) {
  152. return;
  153. }
  154. }
  155. return $this->copyThenRemove($source, $target);
  156. }
  157. /**
  158. * Returns the shortest path from $from to $to
  159. *
  160. * @param string $from
  161. * @param string $to
  162. * @param bool $directories if true, the source/target are considered to be directories
  163. * @throws \InvalidArgumentException
  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. * @throws \InvalidArgumentException
  198. * @return string
  199. */
  200. public function findShortestPathCode($from, $to, $directories = false)
  201. {
  202. if (!$this->isAbsolutePath($from) || !$this->isAbsolutePath($to)) {
  203. throw new \InvalidArgumentException(sprintf('$from (%s) and $to (%s) must be absolute paths.', $from, $to));
  204. }
  205. $from = lcfirst($this->normalizePath($from));
  206. $to = lcfirst($this->normalizePath($to));
  207. if ($from === $to) {
  208. return $directories ? '__DIR__' : '__FILE__';
  209. }
  210. $commonPath = $to.'/';
  211. while (strpos($from, $commonPath) !== 0 && '/' !== $commonPath && !preg_match('{^[a-z]:/?$}i', $commonPath) && '.' !== $commonPath) {
  212. $commonPath = strtr(dirname($commonPath), '\\', '/');
  213. }
  214. if (0 !== strpos($from, $commonPath) || '/' === $commonPath || '.' === $commonPath) {
  215. return var_export($to, true);
  216. }
  217. $commonPath = rtrim($commonPath, '/') . '/';
  218. if (strpos($to, $from.'/') === 0) {
  219. return '__DIR__ . '.var_export(substr($to, strlen($from)), true);
  220. }
  221. $sourcePathDepth = substr_count(substr($from, strlen($commonPath)), '/') + $directories;
  222. $commonPathCode = str_repeat('dirname(', $sourcePathDepth).'__DIR__'.str_repeat(')', $sourcePathDepth);
  223. $relTarget = substr($to, strlen($commonPath));
  224. return $commonPathCode . (strlen($relTarget) ? '.' . var_export('/' . $relTarget, true) : '');
  225. }
  226. /**
  227. * Checks if the given path is absolute
  228. *
  229. * @param string $path
  230. * @return bool
  231. */
  232. public function isAbsolutePath($path)
  233. {
  234. return substr($path, 0, 1) === '/' || substr($path, 1, 1) === ':';
  235. }
  236. /**
  237. * Returns size of a file or directory specified by path. If a directory is
  238. * given, it's size will be computed recursively.
  239. *
  240. * @param string $path Path to the file or directory
  241. * @throws \RuntimeException
  242. * @return int
  243. */
  244. public function size($path)
  245. {
  246. if (!file_exists($path)) {
  247. throw new \RuntimeException("$path does not exist.");
  248. }
  249. if (is_dir($path)) {
  250. return $this->directorySize($path);
  251. }
  252. return filesize($path);
  253. }
  254. /**
  255. * Normalize a path. This replaces backslashes with slashes, removes ending
  256. * slash and collapses redundant separators and up-level references.
  257. *
  258. * @param string $path Path to the file or directory
  259. * @return string
  260. */
  261. public function normalizePath($path)
  262. {
  263. $parts = array();
  264. $path = strtr($path, '\\', '/');
  265. $prefix = '';
  266. $absolute = false;
  267. if (preg_match('{^([0-9a-z]+:(?://(?:[a-z]:)?)?)}i', $path, $match)) {
  268. $prefix = $match[1];
  269. $path = substr($path, strlen($prefix));
  270. }
  271. if (substr($path, 0, 1) === '/') {
  272. $absolute = true;
  273. $path = substr($path, 1);
  274. }
  275. $up = false;
  276. foreach (explode('/', $path) as $chunk) {
  277. if ('..' === $chunk && ($absolute || $up)) {
  278. array_pop($parts);
  279. $up = !(empty($parts) || '..' === end($parts));
  280. } elseif ('.' !== $chunk && '' !== $chunk) {
  281. $parts[] = $chunk;
  282. $up = '..' !== $chunk;
  283. }
  284. }
  285. return $prefix.($absolute ? '/' : '').implode('/', $parts);
  286. }
  287. protected function directorySize($directory)
  288. {
  289. $it = new RecursiveDirectoryIterator($directory, RecursiveDirectoryIterator::SKIP_DOTS);
  290. $ri = new RecursiveIteratorIterator($it, RecursiveIteratorIterator::CHILD_FIRST);
  291. $size = 0;
  292. foreach ($ri as $file) {
  293. if ($file->isFile()) {
  294. $size += $file->getSize();
  295. }
  296. }
  297. return $size;
  298. }
  299. protected function getProcess()
  300. {
  301. return new ProcessExecutor;
  302. }
  303. }