Filesystem.php 13 KB

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