Refactor all (except command) modules using new exceptions

This commit is contained in:
crazywhalecc
2025-08-06 20:43:23 +08:00
committed by Jerry Ma
parent 722bb31815
commit f68f060be2
47 changed files with 335 additions and 291 deletions

View File

@@ -5,9 +5,8 @@ declare(strict_types=1);
namespace SPC\store;
use SPC\exception\DownloaderException;
use SPC\exception\FileSystemException;
use SPC\exception\RuntimeException;
use SPC\exception\WrongUsageException;
use SPC\exception\InterruptException;
use SPC\exception\SPCException;
use SPC\store\pkg\CustomPackage;
use SPC\store\source\CustomSourceBase;
use SPC\util\SPCTarget;
@@ -201,9 +200,9 @@ class Downloader
unlink(FileSystem::convertPath(DOWNLOAD_PATH . '/' . $filename));
}
};
self::registerCancelEvent($cancel_func);
keyboard_interrupt_register($cancel_func);
self::curlDown(url: $url, path: FileSystem::convertPath(DOWNLOAD_PATH . "/{$filename}"), headers: $headers, hooks: $hooks, retries: self::getRetryAttempts());
self::unregisterCancelEvent();
keyboard_interrupt_unregister();
logger()->debug("Locking {$filename}");
if ($download_as === SPC_DOWNLOAD_PRE_BUILT) {
$name = self::getPreBuiltLockName($name);
@@ -248,12 +247,12 @@ class Downloader
f_passthru("cd \"{$download_path}\" && {$git} submodule update --init " . escapeshellarg($submodule));
}
}
} catch (RuntimeException $e) {
} catch (SPCException $e) {
if (is_dir($download_path)) {
FileSystem::removeDir($download_path);
}
if ($e->getCode() === 2 || $e->getCode() === -1073741510) {
throw new WrongUsageException('Keyboard interrupted, download failed !');
throw new InterruptException('Keyboard interrupted, download failed !');
}
if ($retries > 0) {
self::downloadGit($name, $url, $branch, $submodules, $move_path, $retries - 1, $lock_as);
@@ -385,7 +384,7 @@ class Downloader
default:
throw new DownloaderException('unknown source type: ' . $pkg['type']);
}
} catch (RuntimeException $e) {
} catch (\Throwable $e) {
// Because sometimes files downloaded through the command line are not automatically deleted after a failure.
// Here we need to manually delete the file if it is detected to exist.
if (isset($filename) && file_exists(DOWNLOAD_PATH . '/' . $filename)) {
@@ -503,7 +502,7 @@ class Downloader
default:
throw new DownloaderException('unknown source type: ' . $source['type']);
}
} catch (RuntimeException $e) {
} catch (\Throwable $e) {
// Because sometimes files downloaded through the command line are not automatically deleted after a failure.
// Here we need to manually delete the file if it is detected to exist.
if (isset($filename) && file_exists(DOWNLOAD_PATH . '/' . $filename)) {
@@ -551,7 +550,7 @@ class Downloader
}
f_exec($cmd, $output, $ret);
if ($ret === 2 || $ret === -1073741510) {
throw new RuntimeException(sprintf('Failed to fetch "%s"', $url));
throw new InterruptException(sprintf('Canceled fetching "%s"', $url));
}
if ($ret !== 0) {
throw new DownloaderException(sprintf('Failed to fetch "%s"', $url));
@@ -563,7 +562,7 @@ class Downloader
}
f_exec($cmd, $output, $ret);
if ($ret === 2 || $ret === -1073741510) {
throw new RuntimeException(sprintf('Failed to fetch "%s"', $url));
throw new InterruptException(sprintf('Canceled fetching "%s"', $url));
}
if ($ret !== 0) {
throw new DownloaderException(sprintf('Failed to fetch "%s"', $url));
@@ -599,9 +598,9 @@ class Downloader
$cmd = SPC_CURL_EXEC . " -{$check}fSL {$retry} -o \"{$path}\" {$methodArg} {$headerArg} \"{$url}\"";
try {
f_passthru($cmd);
} catch (RuntimeException $e) {
} catch (\Throwable $e) {
if ($e->getCode() === 2 || $e->getCode() === -1073741510) {
throw new WrongUsageException('Keyboard interrupted, download failed !');
throw new InterruptException('Keyboard interrupted, download failed !');
}
throw $e;
}
@@ -639,11 +638,11 @@ class Downloader
$url = "https://dl.static-php.dev/static-php-cli/deps/spc-download-mirror/{$source_name}/?format=json";
$json = json_decode(Downloader::curlExec(url: $url, retries: intval(getenv('SPC_DOWNLOAD_RETRIES') ?: 0)), true);
if (!is_array($json)) {
throw new RuntimeException('failed http fetch');
throw new DownloaderException('failed http fetch');
}
$item = $json[0] ?? null;
if ($item === null) {
throw new RuntimeException('failed to parse json');
throw new DownloaderException('failed to parse json');
}
$full_url = 'https://dl.static-php.dev' . $item['full_path'];
$filename = basename($item['full_path']);

View File

@@ -5,7 +5,7 @@ declare(strict_types=1);
namespace SPC\store;
use SPC\exception\FileSystemException;
use SPC\exception\RuntimeException;
use SPC\exception\SPCException;
class FileSystem
{
@@ -147,6 +147,7 @@ class FileSystem
*/
public static function copyDir(string $from, string $to): void
{
logger()->debug("Copying directory from {$from} to {$to}");
$dst_path = FileSystem::convertPath($to);
$src_path = FileSystem::convertPath($from);
switch (PHP_OS_FAMILY) {
@@ -161,6 +162,23 @@ class FileSystem
}
}
/**
* Copy file from one location to another.
* This method will throw an exception if the copy operation fails.
*
* @param string $from Source file path
* @param string $to Destination file path
*/
public static function copy(string $from, string $to): void
{
logger()->debug("Copying file from {$from} to {$to}");
$dst_path = FileSystem::convertPath($to);
$src_path = FileSystem::convertPath($from);
if (!copy($src_path, $dst_path)) {
throw new FileSystemException('Cannot copy file from ' . $src_path . ' to ' . $dst_path);
}
}
/**
* Extract package archive to specified directory
*
@@ -187,13 +205,13 @@ class FileSystem
try {
// extract wrapper command
self::extractWithType($source_type, $filename, $extract_path);
} catch (RuntimeException $e) {
} catch (SPCException $e) {
if (PHP_OS_FAMILY === 'Windows') {
f_passthru('rmdir /s /q ' . $target);
} else {
f_passthru('rm -rf ' . $target);
}
throw new FileSystemException('Cannot extract package ' . $name, $e->getCode(), $e);
throw new FileSystemException("Cannot extract package {$name}", $e->getCode(), $e);
}
}
@@ -223,7 +241,7 @@ class FileSystem
try {
self::extractWithType($source_type, $filename, $move_path);
self::emitSourceExtractHook($name, $target);
} catch (RuntimeException $e) {
} catch (SPCException $e) {
if (PHP_OS_FAMILY === 'Windows') {
f_passthru('rmdir /s /q ' . $target);
} else {
@@ -505,7 +523,7 @@ class FileSystem
public static function restoreBackupFile(string $path): void
{
if (!file_exists($path . '.bak')) {
throw new RuntimeException('Cannot find bak file for ' . $path);
throw new FileSystemException("Backup restore failed: Cannot find bak file for {$path}");
}
copy($path . '.bak', $path);
unlink($path . '.bak');

View File

@@ -4,8 +4,7 @@ declare(strict_types=1);
namespace SPC\store;
use SPC\exception\FileSystemException;
use SPC\exception\RuntimeException;
use SPC\exception\SPCInternalException;
use SPC\exception\WrongUsageException;
class LockFile
@@ -128,10 +127,10 @@ class LockFile
SPC_SOURCE_ARCHIVE => sha1_file(DOWNLOAD_PATH . '/' . $lock_options['filename']),
SPC_SOURCE_GIT => exec('cd ' . escapeshellarg(DOWNLOAD_PATH . '/' . $lock_options['dirname']) . ' && ' . SPC_GIT_EXEC . ' rev-parse HEAD'),
SPC_SOURCE_LOCAL => 'LOCAL HASH IS ALWAYS DIFFERENT',
default => filter_var(getenv('SPC_IGNORE_BAD_HASH'), FILTER_VALIDATE_BOOLEAN) ? '' : throw new RuntimeException("Unknown source type: {$lock_options['source_type']}"),
default => filter_var(getenv('SPC_IGNORE_BAD_HASH'), FILTER_VALIDATE_BOOLEAN) ? '' : throw new SPCInternalException("Unknown source type: {$lock_options['source_type']}"),
};
if ($result === false && !filter_var(getenv('SPC_IGNORE_BAD_HASH'), FILTER_VALIDATE_BOOLEAN)) {
throw new RuntimeException("Failed to get hash for source: {$lock_options['source_type']}");
throw new SPCInternalException("Failed to get hash for source: {$lock_options['source_type']}");
}
return $result ?: '';
}
@@ -182,7 +181,7 @@ class LockFile
$file_content = file_get_contents(self::LOCK_FILE);
self::$lock_file_content = json_decode($file_content, true);
if (self::$lock_file_content === null) {
throw new \RuntimeException('Failed to decode lock file: ' . self::LOCK_FILE);
throw new SPCInternalException('Failed to decode lock file: ' . self::LOCK_FILE);
}
}
}

View File

@@ -9,8 +9,7 @@ use SPC\builder\linux\SystemUtil;
use SPC\builder\unix\UnixBuilderBase;
use SPC\builder\windows\WindowsBuilder;
use SPC\exception\FileSystemException;
use SPC\exception\RuntimeException;
use SPC\exception\WrongUsageException;
use SPC\exception\PatchException;
use SPC\util\SPCTarget;
class SourcePatcher
@@ -171,7 +170,7 @@ class SourcePatcher
$patches[] = "sapi/micro/patches/{$patchName}_{$tryMajMin}.patch";
continue 2;
}
throw new RuntimeException("failed finding patch {$patchName}");
throw new PatchException('phpmicro patches', "Failed finding patch file or versioned file {$patchName} !");
}
foreach ($patches as $patch) {
@@ -202,7 +201,7 @@ class SourcePatcher
$patch_str = FileSystem::convertPath($patch_file);
if (!file_exists($patch_str)) {
throw new RuntimeException("Patch file [{$patch_str}] does not exist");
throw new PatchException($patch_name, "Patch file [{$patch_str}] does not exist");
}
// Copy patch from phar
@@ -524,7 +523,7 @@ class SourcePatcher
++$line_num;
}
if ($found === false) {
throw new RuntimeException('Cannot patch windows CLI Makefile!');
throw new PatchException('Windows Makefile patching for php.exe target', 'Cannot patch windows CLI Makefile, Makefile does not contain "$(BUILD_DIR)\php.exe:" line');
}
$lines[$line_num] = '$(BUILD_DIR)\php.exe: generated_files $(DEPS_CLI) $(PHP_GLOBAL_OBJS) $(CLI_GLOBAL_OBJS) $(STATIC_EXT_OBJS) $(ASM_OBJS) $(BUILD_DIR)\php.exe.res $(BUILD_DIR)\php.exe.manifest';
$lines[$line_num + 1] = "\t" . '"$(LINK)" /nologo $(PHP_GLOBAL_OBJS_RESP) $(CLI_GLOBAL_OBJS_RESP) $(STATIC_EXT_OBJS_RESP) $(STATIC_EXT_LIBS) $(ASM_OBJS) $(LIBS) $(LIBS_CLI) $(BUILD_DIR)\php.exe.res /out:$(BUILD_DIR)\php.exe $(LDFLAGS) $(LDFLAGS_CLI) /ltcg /nodefaultlib:msvcrt /nodefaultlib:msvcrtd /ignore:4286';

View File

@@ -4,7 +4,7 @@ declare(strict_types=1);
namespace SPC\store\pkg;
use SPC\exception\RuntimeException;
use SPC\exception\DownloaderException;
use SPC\exception\WrongUsageException;
use SPC\store\CurlHook;
use SPC\store\Downloader;
@@ -77,14 +77,14 @@ class Zig extends CustomPackage
}
if (!$latest_version) {
throw new RuntimeException('Could not determine latest Zig version');
throw new DownloaderException('Could not determine latest Zig version');
}
logger()->info("Installing Zig version {$latest_version}");
$platform_key = "{$zig_arch}-{$zig_os}";
if (!isset($index_json[$latest_version][$platform_key])) {
throw new RuntimeException("No download available for {$platform_key} in Zig version {$latest_version}");
throw new DownloaderException("No download available for {$platform_key} in Zig version {$latest_version}");
}
$download_info = $index_json[$latest_version][$platform_key];