static-php-cli/src/SPC/toolchain/ToolchainManager.php

56 lines
1.7 KiB
PHP
Raw Normal View History

2025-06-29 16:00:17 +08:00
<?php
declare(strict_types=1);
namespace SPC\toolchain;
use SPC\builder\linux\SystemUtil;
use SPC\exception\WrongUsageException;
use SPC\util\GlobalEnvManager;
class ToolchainManager
{
public const array OS_DEFAULT_TOOLCHAIN = [
2025-07-01 14:01:48 +07:00
'Linux' => ZigToolchain::class,
2025-06-29 16:00:17 +08:00
'Windows' => MSVCToolchain::class,
'Darwin' => ClangNativeToolchain::class,
'BSD' => ClangNativeToolchain::class,
];
2025-07-01 14:01:48 +07:00
public static function getToolchainClass(): string
2025-06-29 16:00:17 +08:00
{
$libc = getenv('SPC_LIBC');
if ($libc !== false) {
2025-07-01 14:01:48 +07:00
logger()->warning('SPC_LIBC is deprecated, please use SPC_TARGET instead.');
return match ($libc) {
2025-06-29 16:00:17 +08:00
'musl' => SystemUtil::isMuslDist() ? GccNativeToolchain::class : MuslToolchain::class,
2025-07-01 14:01:48 +07:00
'glibc' => !SystemUtil::isMuslDist() ? GccNativeToolchain::class : throw new WrongUsageException('SPC_TARGET must be musl for musl dist.'),
2025-06-29 16:00:17 +08:00
default => throw new WrongUsageException('Unsupported SPC_LIBC value: ' . $libc),
};
}
2025-07-01 14:01:48 +07:00
return self::OS_DEFAULT_TOOLCHAIN[PHP_OS_FAMILY];
}
/**
* @throws WrongUsageException
*/
public static function initToolchain(): void
{
$toolchainClass = self::getToolchainClass();
2025-06-29 16:00:17 +08:00
/* @var ToolchainInterface $toolchainClass */
(new $toolchainClass())->initEnv();
2025-07-01 14:01:48 +07:00
GlobalEnvManager::putenv("SPC_TOOLCHAIN={$toolchainClass}");
2025-06-29 16:00:17 +08:00
}
public static function afterInitToolchain(): void
{
if (!getenv('SPC_TOOLCHAIN')) {
throw new WrongUsageException('SPC_TOOLCHAIN not set');
}
$toolchain = getenv('SPC_TOOLCHAIN');
/* @var ToolchainInterface $toolchain */
(new $toolchain())->afterInit();
}
}