Filesystem: Use ErrorToExceptionHandler to improve error output

This commit is contained in:
Dylan K. Taylor 2022-01-09 16:26:42 +00:00
parent a323fb7bb5
commit fd880d8465
No known key found for this signature in database
GPG Key ID: 8927471A91CAFD3D

View File

@ -23,6 +23,7 @@ declare(strict_types=1);
namespace pocketmine\utils; namespace pocketmine\utils;
use pocketmine\errorhandler\ErrorToExceptionHandler;
use Webmozart\PathUtil\Path; use Webmozart\PathUtil\Path;
use function copy; use function copy;
use function dirname; use function dirname;
@ -111,8 +112,12 @@ final class Filesystem{
//if the parent dir doesn't exist, the user most likely made a mistake //if the parent dir doesn't exist, the user most likely made a mistake
throw new \RuntimeException("The parent directory of $destination does not exist, or is not a directory"); throw new \RuntimeException("The parent directory of $destination does not exist, or is not a directory");
} }
if(!@mkdir($destination) && !is_dir($destination)){ try{
throw new \RuntimeException("Failed to create output directory $destination (permission denied?)"); ErrorToExceptionHandler::trap(fn() => mkdir($destination));
}catch(\ErrorException $e){
if(!is_dir($destination)){
throw new \RuntimeException("Failed to create output directory $destination: " . $e->getMessage());
}
} }
} }
self::recursiveCopyInternal($origin, $destination); self::recursiveCopyInternal($origin, $destination);
@ -263,8 +268,6 @@ final class Filesystem{
throw new \RuntimeException("Failed to write to temporary file $temporaryFileName (possibly out of free disk space)"); throw new \RuntimeException("Failed to write to temporary file $temporaryFileName (possibly out of free disk space)");
} }
//TODO: the @ prevents us receiving the actual error message, but right now it's necessary since we can't assume
//that the error handler has been set :(
$renameTemporaryFileResult = $context !== null ? $renameTemporaryFileResult = $context !== null ?
@rename($temporaryFileName, $fileName, $context) : @rename($temporaryFileName, $fileName, $context) :
@rename($temporaryFileName, $fileName); @rename($temporaryFileName, $fileName);
@ -283,11 +286,13 @@ final class Filesystem{
* } * }
* } * }
*/ */
$copyTemporaryFileResult = $context !== null ? try{
copy($temporaryFileName, $fileName, $context) : ErrorToExceptionHandler::trap(fn() => $context !== null ?
copy($temporaryFileName, $fileName); copy($temporaryFileName, $fileName, $context) :
if(!$copyTemporaryFileResult){ copy($temporaryFileName, $fileName)
throw new \RuntimeException("Failed to move temporary file contents into target file"); );
}catch(\ErrorException $copyException){
throw new \RuntimeException("Failed to move temporary file contents into target file: " . $copyException->getMessage(), 0, $copyException);
} }
@unlink($temporaryFileName); @unlink($temporaryFileName);
} }