Compare commits

...

13 Commits

Author SHA1 Message Date
crazywhalecc
64d9650f88 Fix compiler extra appending 2026-05-09 17:23:01 +08:00
crazywhalecc
e63d49ec13 Disable pdo pgsql hook for swow temporarily 2026-05-09 16:30:57 +08:00
Jerry Ma
9dbb178bf3 Potential fix for pull request finding
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
2026-05-09 16:11:26 +08:00
crazywhalecc
6ad4b6a4af Add concurrency settings to GitHub Actions workflow 2026-05-09 16:07:22 +08:00
crazywhalecc
270f131f54 Add label event 2026-05-09 16:01:44 +08:00
crazywhalecc
ceade306b8 phpstan fix 2026-05-09 15:55:55 +08:00
crazywhalecc
629b5b6b2d Add test-bot 2026-05-09 15:54:01 +08:00
crazywhalecc
7b79767355 Add retry mechanism to Git clone and GitHub release fetching methods 2026-05-09 14:13:47 +08:00
crazywhalecc
2ed4b10260 Make brotli and zstd as dep 2026-05-09 14:13:09 +08:00
crazywhalecc
184a091fd9 Implicitly define swow dependencies (due to extension generating and windows swow curl bug) 2026-05-09 14:12:50 +08:00
crazywhalecc
e6642459b8 Fix opentelemetry strict flag 2026-05-09 12:16:48 +08:00
crazywhalecc
af3c6a6d08 Move build command here 2026-05-09 11:05:28 +08:00
crazywhalecc
e930873e60 Add tier 2 support for actions runner test 2026-05-09 11:00:26 +08:00
15 changed files with 533 additions and 133 deletions

View File

@@ -1,9 +1,9 @@
name: Tests
name: v3 Tests
on:
pull_request:
branches: [ "main", "v3" ]
types: [ opened, synchronize, reopened ]
branches: [ "v3" ]
types: [ opened, synchronize, reopened, labeled, unlabeled ]
paths:
- 'src/**'
- 'config/**'
@@ -15,6 +15,10 @@ on:
permissions: read-all
concurrency:
group: ${{ github.workflow }}-${{ github.event.pull_request.number }}
cancel-in-progress: true
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
@@ -103,114 +107,167 @@ jobs:
run: composer install -q --no-ansi --no-interaction --no-scripts --no-progress --prefer-dist
- name: "Run PHPUnit Tests"
run: SPC_LIBC=glibc vendor/bin/phpunit tests/ --no-coverage
run: vendor/bin/phpunit tests/ --no-coverage
define-matrix:
if: false # TODO: enable when refactoring workflows
name: "Define Matrix"
check-gate:
name: "Check: need-test label"
runs-on: ubuntu-latest
outputs:
php: ${{ steps.gendef.outputs.php }}
os: ${{ steps.gendef.outputs.os }}
enabled: ${{ steps.gate.outputs.enabled }}
steps:
- name: "Checkout"
uses: actions/checkout@v4
- name: "Setup PHP"
uses: shivammathur/setup-php@v2
with:
php-version: 8.4
extensions: curl, openssl, mbstring
- name: Define
id: gendef
- name: Check label
id: gate
run: |
PHP_VERSIONS=$(php src/globals/test-extensions.php php)
OS_VERSIONS=$(php src/globals/test-extensions.php os)
echo 'php='"$PHP_VERSIONS" >> "$GITHUB_OUTPUT"
echo 'os='"$OS_VERSIONS" >> "$GITHUB_OUTPUT"
LABELS='${{ toJSON(github.event.pull_request.labels.*.name) }}'
if echo "$LABELS" | grep -q '"need-test"'; then
echo "enabled=true" >> "$GITHUB_OUTPUT"
else
echo "enabled=false" >> "$GITHUB_OUTPUT"
fi
build:
if: false
name: "Build PHP Test (PHP ${{ matrix.php }} ${{ matrix.os }})"
runs-on: ${{ matrix.os }}
needs: [define-matrix, php-cs-fixer, phpstan, phpunit]
timeout-minutes: 120
strategy:
matrix:
php: ${{ fromJSON(needs.define-matrix.outputs.php) }}
os: ${{ fromJSON(needs.define-matrix.outputs.os) }}
fail-fast: false
test-bot:
name: "Test Bot: analyze PR"
needs: check-gate
if: needs.check-gate.outputs.enabled == 'true'
runs-on: ubuntu-latest
permissions:
pull-requests: write
contents: read
outputs:
need_test: ${{ steps.bot.outputs.need_test }}
gen_matrix_args: ${{ steps.bot.outputs.gen_matrix_args }}
gen_matrix_args_tier2: ${{ steps.bot.outputs.gen_matrix_args_tier2 }}
php_versions: ${{ steps.bot.outputs.php_versions }}
tier2: ${{ steps.bot.outputs.tier2 }}
steps:
- name: "Update runner packages"
if: ${{ startsWith(matrix.os, 'ubuntu-') }}
run: sudo apt-get update && sudo apt-get install -y ca-certificates
- uses: actions/checkout@v4
- name: "Checkout"
uses: actions/checkout@v4
- name: "Setup PHP"
- name: Setup PHP
uses: shivammathur/setup-php@v2
with:
php-version: 8.4
tools: pecl, composer
php-version: '8.4'
extensions: curl, openssl, mbstring
ini-values: memory_limit=-1
tools: composer
- name: Install dependencies
run: composer install -q --no-ansi --no-interaction --no-scripts --no-progress --prefer-dist --no-dev
- name: Run dev:test-bot
id: bot
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
BOT_JSON=$(php -d opcache.enable_cli=0 bin/spc dev:test-bot \
--pr=${{ github.event.pull_request.number }} \
--repo=${{ github.repository }} 2>/dev/null)
echo "need_test=$(echo "$BOT_JSON" | jq -r '.need_test')" >> "$GITHUB_OUTPUT"
echo "gen_matrix_args=$(echo "$BOT_JSON" | jq -r '.gen_matrix_args')" >> "$GITHUB_OUTPUT"
echo "gen_matrix_args_tier2=$(echo "$BOT_JSON" | jq -r '.gen_matrix_args_tier2')" >> "$GITHUB_OUTPUT"
echo "php_versions=$(echo "$BOT_JSON" | jq -c '.php_versions')" >> "$GITHUB_OUTPUT"
echo "tier2=$(echo "$BOT_JSON" | jq -r '.tier2')" >> "$GITHUB_OUTPUT"
COMMENT_BODY=$(echo "$BOT_JSON" | jq -r '.comment_body')
MARKER="<!-- spc-test-bot -->"
# Find existing bot comment id
EXISTING_ID=$(gh api \
repos/${{ github.repository }}/issues/${{ github.event.pull_request.number }}/comments \
--jq "[.[] | select(.body | startswith(\"$MARKER\")) | .id] | first // empty")
if [ -n "$EXISTING_ID" ]; then
gh api --method PATCH \
repos/${{ github.repository }}/issues/comments/"$EXISTING_ID" \
-f body="$COMMENT_BODY"
else
gh pr comment ${{ github.event.pull_request.number }} \
--repo ${{ github.repository }} \
--body "$COMMENT_BODY"
fi
gen-matrix:
name: "Generate test matrix"
needs: test-bot
if: needs.test-bot.outputs.need_test == 'true'
runs-on: ubuntu-latest
outputs:
matrix: ${{ steps.build.outputs.matrix }}
steps:
- uses: actions/checkout@v4
- name: Setup PHP
uses: shivammathur/setup-php@v2
with:
php-version: '8.4'
extensions: curl, openssl, mbstring
ini-values: memory_limit=-1
tools: composer
- name: Install dependencies
run: composer install -q --no-ansi --no-interaction --no-scripts --no-progress --prefer-dist --no-dev
- name: Build matrix
id: build
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
GEN_MATRIX_ARGS: ${{ needs.test-bot.outputs.gen_matrix_args }}
GEN_MATRIX_ARGS_TIER2: ${{ needs.test-bot.outputs.gen_matrix_args_tier2 }}
PHP_VERSIONS: ${{ needs.test-bot.outputs.php_versions }}
TIER2: ${{ needs.test-bot.outputs.tier2 }}
run: |
# Tier1 matrix
MATRIX1=$(bin/spc dev:gen-ext-test-matrix $GEN_MATRIX_ARGS 2>/dev/null)
# Merge Tier2 if requested
if [ "$TIER2" = "true" ] && [ -n "$GEN_MATRIX_ARGS_TIER2" ]; then
MATRIX2=$(bin/spc dev:gen-ext-test-matrix $GEN_MATRIX_ARGS_TIER2 2>/dev/null)
COMBINED=$(jq -n --argjson m1 "$MATRIX1" --argjson m2 "$MATRIX2" '$m1 + $m2')
else
COMBINED=$MATRIX1
fi
# Expand PHP versions: cartesian product of entries × php_versions
FINAL=$(echo "$COMBINED" | jq --argjson versions "$PHP_VERSIONS" \
'[.[] | . as $entry | $versions[] | $entry + {"php-version": .}]')
echo "matrix=$(echo "$FINAL" | jq -c '{"combo": .}')" >> "$GITHUB_OUTPUT"
ext-test:
name: "Ext test: ${{ matrix.combo.extension }} (PHP ${{ matrix.combo.php-version }} · ${{ matrix.combo.os }}-${{ matrix.combo.arch }})"
needs: gen-matrix
runs-on: ${{ matrix.combo.runner }}
timeout-minutes: 120
strategy:
fail-fast: false
matrix: ${{ fromJSON(needs.gen-matrix.outputs.matrix) }}
steps:
- uses: actions/checkout@v4
- name: Setup PHP
uses: shivammathur/setup-php@v2
with:
php-version: 8.4
extensions: curl, openssl, mbstring
ini-values: memory_limit=-1
tools: composer
env:
phpts: nts
- name: "Cache composer packages"
id: composer-cache
uses: actions/cache@v4
with:
path: vendor
key: ${{ runner.os }}-php-${{ hashFiles('**/composer.lock') }}
restore-keys: |
${{ runner.os }}-php-
- name: Install dependencies
run: composer install -q --no-ansi --no-interaction --no-scripts --no-progress --prefer-dist --no-dev
# Cache downloaded source
- id: cache-download
uses: actions/cache@v4
with:
path: downloads
key: php-dependencies-${{ matrix.os }}
- name: "Install Dependencies"
run: composer update -vvv --no-ansi --no-interaction --no-scripts --no-progress --prefer-dist --no-plugins
- name: "Run Build Tests (doctor)"
run: php src/globals/test-extensions.php doctor_cmd ${{ matrix.os }} ${{ matrix.php }}
- name: "Prepare UPX for Windows"
if: ${{ startsWith(matrix.os, 'windows-') }}
- name: Build
env:
SPC_USE_SUDO: "yes"
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
php src/globals/test-extensions.php install_upx_cmd ${{ matrix.os }} ${{ matrix.php }}
echo "UPX_CMD=$(php src/globals/test-extensions.php upx)" >> $env:GITHUB_ENV
./bin/spc doctor --auto-fix
${{ matrix.combo.build-args }} --dl-with-php=${{ matrix.combo.php-version }}
- name: "Prepare UPX for Linux"
if: ${{ startsWith(matrix.os, 'ubuntu-') }}
run: |
php src/globals/test-extensions.php install_upx_cmd ${{ matrix.os }} ${{ matrix.php }}
echo "UPX_CMD=$(php src/globals/test-extensions.php upx)" >> $GITHUB_ENV
- name: "Run Build Tests (download)"
run: php src/globals/test-extensions.php download_cmd ${{ matrix.os }} ${{ matrix.php }}
- name: "Run Build Tests (build)"
run: php src/globals/test-extensions.php build_cmd ${{ matrix.os }} ${{ matrix.php }}
- name: "Run Build Tests (build - embed for non-windows)"
if: ${{ !startsWith(matrix.os, 'windows-') }}
run: php src/globals/test-extensions.php build_embed_cmd ${{ matrix.os }} ${{ matrix.php }}
- name: "Upload logs"
if: ${{ always() && hashFiles('log/**') != '' }}
uses: actions/upload-artifact@v7
- name: Upload logs
if: always() && hashFiles('log/**') != ''
uses: actions/upload-artifact@v4
with:
name: build-logs-${{ matrix.os }}-${{ matrix.php }}
name: logs-${{ matrix.combo.os }}-${{ matrix.combo.arch }}-${{ matrix.combo.extension }}-php${{ matrix.combo.php-version }}
path: log
# - name: Setup tmate session
# if: ${{ failure() }}
# uses: mxschmitt/action-tmate@v3

View File

@@ -9,10 +9,5 @@ ext-swow:
metadata:
license: Apache-2.0
license-files: [LICENSE]
suggests:
- openssl
- curl
- ext-openssl
- ext-curl
php-extension:
arg-type: custom

View File

@@ -16,6 +16,8 @@ curl:
- zlib
- libssh2
- nghttp2
- brotli
- zstd
suggests@unix:
- libssh2
- brotli
@@ -27,9 +29,6 @@ curl:
- ldap
- idn2
- krb5
suggests@windows:
- brotli
- zstd
frameworks:
- CoreFoundation
- CoreServices

View File

@@ -23,13 +23,13 @@ class go_win
$pkgroot = PKG_ROOT_PATH;
// get version
[$version] = explode("\n", default_shell()->executeCurl('https://go.dev/VERSION?m=text') ?: '');
[$version] = explode("\n", default_shell()->executeCurl('https://go.dev/VERSION?m=text', retries: $downloader->getRetry()) ?: '');
if ($version === '') {
throw new DownloaderException('Failed to get latest Go version from https://go.dev/VERSION?m=text');
}
// find SHA256 hash from download page
$page = default_shell()->executeCurl('https://go.dev/dl/');
$page = default_shell()->executeCurl('https://go.dev/dl/', retries: $downloader->getRetry());
if ($page === '' || $page === false) {
throw new DownloaderException('Failed to get Go download page from https://go.dev/dl/');
}

View File

@@ -39,11 +39,11 @@ class go_xcaddy
};
// get version and hash
[$version] = explode("\n", default_shell()->executeCurl('https://go.dev/VERSION?m=text') ?: '');
[$version] = explode("\n", default_shell()->executeCurl('https://go.dev/VERSION?m=text', retries: $downloader->getRetry()) ?: '');
if ($version === '') {
throw new DownloaderException('Failed to get latest Go version from https://go.dev/VERSION?m=text');
}
$page = default_shell()->executeCurl('https://go.dev/dl/');
$page = default_shell()->executeCurl('https://go.dev/dl/', retries: $downloader->getRetry());
if ($page === '' || $page === false) {
throw new DownloaderException('Failed to get Go download page from https://go.dev/dl/');
}

View File

@@ -7,15 +7,21 @@ namespace Package\Extension;
use Package\Target\php;
use StaticPHP\Attribute\Package\BeforeStage;
use StaticPHP\Attribute\Package\Extension;
use StaticPHP\Toolchain\Interface\ToolchainInterface;
use StaticPHP\Toolchain\ZigToolchain;
use StaticPHP\Util\GlobalEnvManager;
#[Extension('opentelemetry')]
class opentelemetry
{
#[BeforeStage('php', [php::class, 'makeForUnix'], 'ext-opentelemetry')]
public function patchBeforeMake(): void
public function patchBeforeMake(ToolchainInterface $toolchain): void
{
// add -Wno-strict-prototypes
GlobalEnvManager::putenv('SPC_CMD_VAR_PHP_MAKE_EXTRA_CFLAGS=' . getenv('SPC_CMD_VAR_PHP_MAKE_EXTRA_CFLAGS') . ' -Wno-strict-prototypes');
$extra_cflags = getenv('SPC_CMD_VAR_PHP_MAKE_EXTRA_CFLAGS') ?: '';
$extra_cflags .= ' -Wno-strict-prototypes';
if ($toolchain instanceof ZigToolchain) {
$extra_cflags .= ' -Wno-unknown-warning-option';
}
GlobalEnvManager::putenv('SPC_CMD_VAR_PHP_MAKE_EXTRA_CFLAGS=' . trim($extra_cflags));
}
}

View File

@@ -20,7 +20,7 @@ class swow extends PhpExtensionPackage
#[CustomPhpConfigureArg('Windows')]
public function configureArg(PackageInstaller $installer): string
{
$arg = '--enable-swow';
$arg = '--enable-swow --disable-swow-pdo-pgsql';
$arg .= $installer->getLibraryPackage('openssl') ? ' --enable-swow-ssl' : ' --disable-swow-ssl';
$arg .= $installer->getLibraryPackage('curl') ? ' --enable-swow-curl' : ' --disable-swow-curl';
return $arg;

View File

@@ -22,6 +22,7 @@ use StaticPHP\Runtime\SystemTarget;
use StaticPHP\Toolchain\Interface\ToolchainInterface;
use StaticPHP\Util\DirDiff;
use StaticPHP\Util\FileSystem;
use StaticPHP\Util\GlobalEnvManager;
use StaticPHP\Util\InteractiveTerm;
use StaticPHP\Util\SourcePatcher;
use StaticPHP\Util\SPCConfigUtil;
@@ -93,7 +94,8 @@ trait unix
// disable undefined behavior sanitizer when opcache JIT is enabled (Linux only)
if (SystemTarget::getTargetOS() === 'Linux' && !$package->getBuildOption('disable-opcache-jit', false)) {
if ($version_id >= 80500 || $installer->isPackageResolved('ext-opcache')) {
f_putenv('SPC_COMPILER_EXTRA=-fno-sanitize=undefined');
$compiler_extra = getenv('SPC_COMPILER_EXTRA') ?: '';
GlobalEnvManager::putenv('SPC_COMPILER_EXTRA=' . trim($compiler_extra . ' -fno-sanitize=undefined'));
}
}
// PHP JSON extension is built-in since PHP 8.0

View File

@@ -20,7 +20,7 @@ class Git implements DownloadTypeInterface, CheckUpdateInterface
// direct branch clone
if (isset($config['rev'])) {
default_shell()->executeGitClone($config['url'], $config['rev'], $path, $shallow, $config['submodules'] ?? null);
default_shell()->executeGitClone($config['url'], $config['rev'], $path, $shallow, $config['submodules'] ?? null, $downloader->getRetry());
$shell = PHP_OS_FAMILY === 'Windows' ? cmd(false) : shell(false);
$hash_result = $shell->execWithResult(SPC_GIT_EXEC . ' -C ' . escapeshellarg($path) . ' rev-parse --short HEAD');
$hash = ($hash_result[0] === 0 && !empty($hash_result[1])) ? trim($hash_result[1][0]) : '';
@@ -66,7 +66,7 @@ class Git implements DownloadTypeInterface, CheckUpdateInterface
$version = array_key_first($matched_version_branch);
$branch = $matched_version_branch[$version];
logger()->info("Matched version {$version} from branch {$branch} for {$name}");
default_shell()->executeGitClone($config['url'], $branch, $path, $shallow, $config['submodules'] ?? null);
default_shell()->executeGitClone($config['url'], $branch, $path, $shallow, $config['submodules'] ?? null, $downloader->getRetry());
return DownloadResult::git($name, $config, extract: $config['extract'] ?? null, version: $version, downloader: static::class);
}
throw new DownloaderException("No matching branch found for regex {$config['regex']} (checked {$matched_count} branches).");

View File

@@ -21,13 +21,13 @@ class GitHubRelease implements DownloadTypeInterface, ValidatorInterface, CheckU
private ?string $version = null;
public function getGitHubReleases(string $name, string $repo, bool $prefer_stable = true, ?string $query = null): array
public function getGitHubReleases(string $name, string $repo, bool $prefer_stable = true, ?string $query = null, int $retries = 0): array
{
logger()->debug("Fetching {$name} GitHub releases from {$repo}");
$url = str_replace('{repo}', $repo, self::API_URL);
$url .= ($query ?? '');
$headers = $this->getGitHubTokenHeaders();
$data2 = default_shell()->executeCurl($url, headers: $headers);
$data2 = default_shell()->executeCurl($url, headers: $headers, retries: $retries);
$data = json_decode($data2 ?: '', true);
if (!is_array($data)) {
throw new DownloaderException("Failed to get GitHub release API info for {$repo} from {$url}");
@@ -46,13 +46,13 @@ class GitHubRelease implements DownloadTypeInterface, ValidatorInterface, CheckU
* Get the latest GitHub release assets for a given repository.
* match_asset is provided, only return the asset that matches the regex.
*/
public function getLatestGitHubRelease(string $name, string $repo, bool $prefer_stable, string $match_asset, ?string $query = null): array
public function getLatestGitHubRelease(string $name, string $repo, bool $prefer_stable, string $match_asset, ?string $query = null, int $retries = 0): array
{
logger()->debug("Fetching {$name} GitHub release from {$repo}");
$url = str_replace('{repo}', $repo, self::API_URL);
$url .= ($query ?? '');
$headers = $this->getGitHubTokenHeaders();
$data2 = default_shell()->executeCurl($url, headers: $headers);
$data2 = default_shell()->executeCurl($url, headers: $headers, retries: $retries);
$data = json_decode($data2 ?: '', true);
if (!is_array($data)) {
throw new DownloaderException("Failed to get GitHub release API info for {$repo} from {$url}");
@@ -84,7 +84,7 @@ class GitHubRelease implements DownloadTypeInterface, ValidatorInterface, CheckU
if (!isset($config['match'])) {
throw new DownloaderException("GitHubRelease downloader requires 'match' config for {$name}");
}
$rel = $this->getLatestGitHubRelease($name, $config['repo'], $config['prefer-stable'] ?? true, $config['match'], $config['query'] ?? null);
$rel = $this->getLatestGitHubRelease($name, $config['repo'], $config['prefer-stable'] ?? true, $config['match'], $config['query'] ?? null, $downloader->getRetry());
// download file using curl
$asset_url = str_replace(['{repo}', '{id}'], [$config['repo'], $rel['id']], self::ASSET_URL);
@@ -124,7 +124,7 @@ class GitHubRelease implements DownloadTypeInterface, ValidatorInterface, CheckU
if (!isset($config['match'])) {
throw new DownloaderException("GitHubRelease downloader requires 'match' config for {$name}");
}
$this->getLatestGitHubRelease($name, $config['repo'], $config['prefer-stable'] ?? true, $config['match'], $config['query'] ?? null);
$this->getLatestGitHubRelease($name, $config['repo'], $config['prefer-stable'] ?? true, $config['match'], $config['query'] ?? null, $downloader->getRetry());
$new_version = $this->version ?? $old_version ?? '';
return new CheckUpdateResult(
old: $old_version,

View File

@@ -22,11 +22,11 @@ class GitHubTarball implements DownloadTypeInterface, CheckUpdateInterface
* Get the GitHub tarball URL for a given repository and release type.
* If match_url is provided, only return the tarball that matches the regex.
*/
public function getGitHubTarballInfo(string $name, string $repo, string $rel_type, bool $prefer_stable = true, ?string $match_url = null, ?string $basename = null, ?string $query = null): array
public function getGitHubTarballInfo(string $name, string $repo, string $rel_type, bool $prefer_stable = true, ?string $match_url = null, ?string $basename = null, ?string $query = null, int $retries = 0): array
{
if ($rel_type === 'releases' && $match_url === null && $query === null && $prefer_stable) {
$api_url = str_replace(['{repo}', '{rel_type}'], [$repo, 'releases/latest'], self::API_URL);
$data = default_shell()->executeCurl($api_url, headers: $this->getGitHubTokenHeaders());
$data = default_shell()->executeCurl($api_url, headers: $this->getGitHubTokenHeaders(), retries: $retries);
$data = json_decode($data ?: '', true);
if (!is_array($data) || empty($data['tarball_url'])) {
throw new DownloaderException("Failed to get GitHub latest release for {$repo} from {$api_url}");
@@ -36,7 +36,7 @@ class GitHubTarball implements DownloadTypeInterface, CheckUpdateInterface
} else {
$api_url = str_replace(['{repo}', '{rel_type}'], [$repo, $rel_type], self::API_URL);
$api_url .= ($query ?? '');
$data = default_shell()->executeCurl($api_url, headers: $this->getGitHubTokenHeaders());
$data = default_shell()->executeCurl($api_url, headers: $this->getGitHubTokenHeaders(), retries: $retries);
$data = json_decode($data ?: '', true);
if (!is_array($data)) {
throw new DownloaderException("Failed to get GitHub tarball URL for {$repo} from {$api_url}");
@@ -65,7 +65,7 @@ class GitHubTarball implements DownloadTypeInterface, CheckUpdateInterface
}
$this->version = $version ?? null;
}
$head = default_shell()->executeCurl($rel_url, 'HEAD', headers: $this->getGitHubTokenHeaders()) ?: '';
$head = default_shell()->executeCurl($rel_url, 'HEAD', headers: $this->getGitHubTokenHeaders(), retries: $retries) ?: '';
preg_match('/^content-disposition:\s+attachment;\s*filename=("?)(?<filename>.+\.tar\.gz)\1/im', $head, $matches);
if ($matches) {
$filename = $matches['filename'];
@@ -84,9 +84,9 @@ class GitHubTarball implements DownloadTypeInterface, CheckUpdateInterface
'ghtagtar' => 'tags',
default => throw new DownloaderException("Invalid GitHubTarball type for {$name}"),
};
[$url, $filename] = $this->getGitHubTarballInfo($name, $config['repo'], $rel_type, $config['prefer-stable'] ?? true, $config['match'] ?? null, $name, $config['query'] ?? null);
[$url, $filename] = $this->getGitHubTarballInfo($name, $config['repo'], $rel_type, $config['prefer-stable'] ?? true, $config['match'] ?? null, $name, $config['query'] ?? null, $downloader->getRetry());
$path = DOWNLOAD_PATH . "/{$filename}";
default_shell()->executeCurlDownload($url, $path, headers: $this->getGitHubTokenHeaders());
default_shell()->executeCurlDownload($url, $path, headers: $this->getGitHubTokenHeaders(), retries: $downloader->getRetry());
return DownloadResult::archive($filename, $config, $config['extract'] ?? null, version: $this->version, downloader: static::class);
}
@@ -97,7 +97,7 @@ class GitHubTarball implements DownloadTypeInterface, CheckUpdateInterface
'ghtagtar' => 'tags',
default => throw new DownloaderException("Invalid GitHubTarball type for {$name}"),
};
$this->getGitHubTarballInfo($name, $config['repo'], $rel_type, $config['prefer-stable'] ?? true, $config['match'] ?? null, $name, $config['query'] ?? null);
$this->getGitHubTarballInfo($name, $config['repo'], $rel_type, $config['prefer-stable'] ?? true, $config['match'] ?? null, $name, $config['query'] ?? null, $downloader->getRetry());
$new_version = $this->version ?? $old_version ?? '';
return new CheckUpdateResult(
old: $old_version,

View File

@@ -12,7 +12,7 @@ use Symfony\Component\Console\Input\InputOption;
#[AsCommand('dev:gen-ext-test-matrix', 'Generate GitHub Actions extension test matrix JSON', [], true)]
class GenExtTestMatrixCommand extends BaseCommand
{
private const string BUILD_TARGETS = '--build-cli --build-cgi --build-micro';
private const string BUILD_TARGETS = '--build-cli --build-cgi --build-micro --with-suggests -vvv';
private const array OS_RUNNERS = [
'linux' => ['arch' => 'x86_64', 'runner' => 'ubuntu-latest', 'os_key' => 'Linux'],
@@ -20,6 +20,14 @@ class GenExtTestMatrixCommand extends BaseCommand
'macos' => ['arch' => 'aarch64', 'runner' => 'macos-15', 'os_key' => 'Darwin'],
];
/**
* Tier 2 runners: Linux aarch64 + macOS x86_64, no Windows.
*/
private const array OS_RUNNERS_TIER2 = [
'linux' => ['arch' => 'aarch64', 'runner' => 'ubuntu-24.04-arm', 'os_key' => 'Linux'],
'macos' => ['arch' => 'x86_64', 'runner' => 'macos-15-intel', 'os_key' => 'Darwin'],
];
/**
* Extensions excluded from specific OS matrix entries.
*/
@@ -65,7 +73,8 @@ class GenExtTestMatrixCommand extends BaseCommand
{
$this->addOption('for-extensions', null, InputOption::VALUE_OPTIONAL, 'Filter by extension display names, comma-separated', '')
->addOption('for-libs', null, InputOption::VALUE_OPTIONAL, 'Filter by lib names (depends+suggests), comma-separated', '')
->addOption('os', null, InputOption::VALUE_OPTIONAL, 'Filter by OS (Linux/Darwin/Windows), comma-separated', '');
->addOption('os', null, InputOption::VALUE_OPTIONAL, 'Filter by OS (Linux/Darwin/Windows), comma-separated', '')
->addOption('tier2', null, InputOption::VALUE_NONE, 'Use Tier 2 runners (Linux aarch64 + macOS x86_64, no Windows)');
}
public function handle(): int
@@ -79,6 +88,9 @@ class GenExtTestMatrixCommand extends BaseCommand
$filter_extensions = $parse_option('for-extensions');
$filter_libs = $parse_option('for-libs');
$filter_os_keys = $parse_option('os');
$tier2 = (bool) $this->input->getOption('tier2');
$base_runners = $tier2 ? self::OS_RUNNERS_TIER2 : self::OS_RUNNERS;
$all = PackageConfig::getAll();
@@ -100,8 +112,8 @@ class GenExtTestMatrixCommand extends BaseCommand
}
$os_runners = empty($filter_os_keys)
? self::OS_RUNNERS
: array_filter(self::OS_RUNNERS, fn ($info) => in_array($info['os_key'], $filter_os_keys, true));
? $base_runners
: array_filter($base_runners, fn ($info) => in_array($info['os_key'], $filter_os_keys, true));
$entries = [];
$all_ext_lib_deps = [];
@@ -198,7 +210,7 @@ class GenExtTestMatrixCommand extends BaseCommand
'os' => $os,
'arch' => $os_info['arch'],
'extension' => $group,
'build-args' => '"' . $group . '" ' . self::BUILD_TARGETS . ($extra !== '' ? ' ' . $extra : ''),
'build-args' => './bin/spc build "' . $group . '" ' . self::BUILD_TARGETS . ($extra !== '' ? ' ' . $extra : ''),
];
}
}

View File

@@ -0,0 +1,313 @@
<?php
declare(strict_types=1);
namespace StaticPHP\Command\Dev;
use StaticPHP\Artifact\Downloader\Type\GitHubTokenSetupTrait;
use StaticPHP\Command\BaseCommand;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Input\InputOption;
#[AsCommand('dev:test-bot', 'Analyze PR changes and labels, output test-bot metadata JSON', [], true)]
class TestBotCommand extends BaseCommand
{
use GitHubTokenSetupTrait;
private const string API_BASE = 'https://api.github.com';
/** Platform labels → os_key used by dev:gen-ext-test-matrix --os= */
private const array PLATFORM_LABELS = [
'test/linux' => 'Linux',
'test/windows' => 'Windows',
'test/macos' => 'Darwin',
];
private const string TIER2_LABEL = 'test/tier2';
/** PHP version labels → version string (8.5 is always included as default) */
private const array PHP_VERSION_LABELS = [
'test/php-83' => '8.3',
'test/php-84' => '8.4',
];
private const string DEFAULT_PHP_VERSION = '8.5';
protected bool $no_motd = true;
public function configure(): void
{
$this->addOption('pr', null, InputOption::VALUE_REQUIRED, 'Pull request number')
->addOption('repo', null, InputOption::VALUE_REQUIRED, 'Repository in owner/repo format (e.g. owner/repo)')
->addOption('mock-files', null, InputOption::VALUE_REQUIRED, 'Comma-separated file paths to simulate PR changed files (skips GitHub API, for local testing)', '')
->addOption('mock-labels', null, InputOption::VALUE_REQUIRED, 'Comma-separated labels to simulate PR labels (skips GitHub API, for local testing)', '');
}
public function handle(): int
{
$mock_files_raw = (string) $this->input->getOption('mock-files');
$mock_labels_raw = (string) $this->input->getOption('mock-labels');
$is_mock = $mock_files_raw !== '' || $mock_labels_raw !== '';
if ($is_mock) {
// Local testing mode: skip all GitHub API calls
$changed_files = array_map(
fn ($f) => ['filename' => trim($f)],
array_filter(explode(',', $mock_files_raw))
);
$label_names = array_map('trim', array_filter(explode(',', $mock_labels_raw)));
} else {
$pr = (int) $this->input->getOption('pr');
$repo = (string) $this->input->getOption('repo');
if ($pr <= 0 || $repo === '') {
$this->output->writeln('<error>Either --mock-files/--mock-labels (local test) or --pr and --repo (live) are required.</error>');
return static::USER_ERROR;
}
$headers = array_merge(
$this->getGitHubTokenHeaders(),
['Accept: application/vnd.github+json', 'X-GitHub-Api-Version: 2022-11-28'],
);
// Fetch changed files (paginated, up to 300)
$changed_files = $this->fetchPaginatedFiles($repo, $pr, $headers);
// Fetch current labels on the PR/issue
$labels_raw = $this->apiGet(
sprintf('%s/repos/%s/issues/%d/labels', self::API_BASE, $repo, $pr),
$headers
);
$label_names = array_column($labels_raw ?? [], 'name');
}
// Analyze changed files → extensions, libs, targets
[$extensions, $libs, $targets] = $this->analyzeChangedFiles($changed_files);
// Resolve active platform OS keys (used as filters, not as trigger)
$os_keys = [];
foreach (self::PLATFORM_LABELS as $label => $os_key) {
if (in_array($label, $label_names, true)) {
$os_keys[] = $os_key;
}
}
$tier2 = in_array(self::TIER2_LABEL, $label_names, true);
$need_test = in_array('need-test', $label_names, true);
// Resolve PHP versions (default always included)
$php_versions = [self::DEFAULT_PHP_VERSION];
foreach (self::PHP_VERSION_LABELS as $label => $version) {
if (in_array($label, $label_names, true)) {
$php_versions[] = $version;
}
}
$php_versions = array_unique($php_versions);
sort($php_versions);
// Build gen_matrix_args whenever need-test is set.
// Platform labels narrow the OS scope; absent = no --os filter (all platforms).
$gen_matrix_args = '';
$gen_matrix_args_tier2 = '';
if ($need_test) {
$flag_parts = [];
if (!empty($extensions)) {
$flag_parts[] = '--for-extensions=' . implode(',', $extensions);
}
if (!empty($libs)) {
$flag_parts[] = '--for-libs=' . implode(',', $libs);
}
if (!empty($os_keys)) {
$flag_parts[] = '--os=' . implode(',', $os_keys);
}
$gen_matrix_args = implode(' ', $flag_parts);
if ($tier2) {
// Tier2 covers Linux + macOS only (never Windows)
$tier2_os = array_values(array_filter(
!empty($os_keys) ? $os_keys : ['Linux', 'Darwin'],
fn ($k) => $k !== 'Windows'
));
if (!empty($tier2_os)) {
$tier2_parts = array_values(array_filter($flag_parts, fn ($f) => !str_starts_with($f, '--os=')));
$tier2_parts[] = '--os=' . implode(',', $tier2_os);
$tier2_parts[] = '--tier2';
$gen_matrix_args_tier2 = implode(' ', $tier2_parts);
}
}
}
$comment_body = $this->buildCommentBody(
$extensions,
$libs,
$targets,
$label_names,
$os_keys,
$tier2,
$php_versions,
$need_test,
);
$result = [
'need_test' => $need_test,
'extensions' => array_values($extensions),
'libs' => array_values($libs),
'targets' => array_values($targets),
'gen_matrix_args' => $gen_matrix_args,
'gen_matrix_args_tier2' => $gen_matrix_args_tier2,
'php_versions' => array_values($php_versions),
'tier2' => $tier2,
'comment_body' => $comment_body,
];
$this->output->write(json_encode($result, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE));
return static::SUCCESS;
}
/**
* Fetch all changed files for a PR across up to 3 pages (max 300 files).
*/
private function fetchPaginatedFiles(string $repo, int $pr, array $headers): array
{
$files = [];
for ($page = 1; $page <= 3; ++$page) {
$url = sprintf('%s/repos/%s/pulls/%d/files?per_page=100&page=%d', self::API_BASE, $repo, $pr, $page);
$batch = $this->apiGet($url, $headers);
if (empty($batch)) {
break;
}
$files = array_merge($files, $batch);
if (count($batch) < 100) {
break;
}
}
return $files;
}
/**
* Perform a GET request and return decoded JSON array, or null on failure.
*/
private function apiGet(string $url, array $headers): ?array
{
$data = default_shell()->executeCurl($url, headers: $headers);
$decoded = json_decode($data ?: '', true);
return is_array($decoded) ? $decoded : null;
}
/**
* Analyze changed file paths and classify them into extensions, libs, and targets.
*
* @return array{string[], string[], string[]}
*/
private function analyzeChangedFiles(array $files): array
{
$extensions = [];
$libs = [];
$targets = [];
foreach ($files as $file) {
$path = $file['filename'] ?? '';
if (preg_match('#^src/Package/Extension/([^/]+)\.php$#', $path, $m)) {
$name = strtolower($m[1]);
$extensions[$name] = $name;
} elseif (preg_match('#^config/pkg/ext/ext-([^/]+)\.yml$#', $path, $m)) {
$extensions[$m[1]] = $m[1];
} elseif (preg_match('#^src/Package/Library/([^/]+)\.php$#', $path, $m)) {
$name = strtolower($m[1]);
$libs[$name] = $name;
} elseif (preg_match('#^config/pkg/lib/([^/]+)\.yml$#', $path, $m)) {
$libs[$m[1]] = $m[1];
} elseif (preg_match('#^src/Package/Target/([^/]+)\.php$#', $path, $m)) {
$name = strtolower($m[1]);
$targets[$name] = $name;
} elseif (preg_match('#^config/pkg/target/([^/]+)\.yml$#', $path, $m)) {
$targets[$m[1]] = $m[1];
}
}
sort($extensions);
sort($libs);
sort($targets);
return [$extensions, $libs, $targets];
}
private function buildCommentBody(
array $extensions,
array $libs,
array $targets,
array $label_names,
array $os_keys,
bool $tier2,
array $php_versions,
bool $need_test,
): string {
$fmt = static fn (array $items): string => !empty($items)
? '`' . implode('`, `', $items) . '`'
: '_none_';
$detected = sprintf(
'**Detected**: Extensions: %s | Libraries: %s | Targets: %s',
$fmt($extensions),
$fmt($libs),
$fmt($targets),
);
// Case 1: need-test absent → invite the author to add it
if (!$need_test) {
return implode("\n", [
'<!-- spc-test-bot -->',
'**StaticPHP Test Bot**',
'',
$detected,
'',
'To trigger extension build tests on this PR, add the `need-test` label:',
'',
'**Gate**: `need-test`',
'**Platform filter** (optional, default all): `test/linux` `test/windows` `test/macos` · `test/tier2`',
'**PHP version** (optional, default 8.5): `test/php-83` `test/php-84`',
]);
}
// Case 2: need-test present → show what will run
// os_keys empty = no filter = all platforms
$effective_os = !empty($os_keys)
? $os_keys
: array_values(self::PLATFORM_LABELS); // all OS keys
$platform_parts = [];
foreach (self::PLATFORM_LABELS as $_label => $os_key) {
if (!in_array($os_key, $effective_os, true)) {
continue;
}
$platform_parts[] = match ($os_key) {
'Linux' => 'Linux x86_64',
'Darwin' => 'macOS arm64',
/* @phpstan-ignore-next-line */
'Windows' => 'Windows x86_64',
default => $os_key,
};
}
if ($tier2) {
if (in_array('Linux', $effective_os, true)) {
$platform_parts[] = 'Linux aarch64 (Tier2)';
}
if (in_array('Darwin', $effective_os, true)) {
$platform_parts[] = 'macOS x86_64 (Tier2)';
}
}
$php_str = implode(', ', array_map(fn ($v) => "PHP {$v}", $php_versions)) . ' NTS';
$active_test_labels = array_values(array_filter($label_names, fn ($l) => str_starts_with($l, 'test/')));
$labels_str = !empty($active_test_labels) ? '`' . implode('`, `', $active_test_labels) . '`' : '_none_';
return implode("\n", [
'<!-- spc-test-bot -->',
'**StaticPHP Test Bot**',
'',
$detected,
'**Active labels**: ' . $labels_str,
'**Config**: ' . implode(' + ', $platform_parts) . ' | ' . $php_str,
]);
}
}

View File

@@ -19,6 +19,7 @@ use StaticPHP\Command\Dev\LintConfigCommand;
use StaticPHP\Command\Dev\PackageInfoCommand;
use StaticPHP\Command\Dev\PackLibCommand;
use StaticPHP\Command\Dev\ShellCommand;
use StaticPHP\Command\Dev\TestBotCommand;
use StaticPHP\Command\DoctorCommand;
use StaticPHP\Command\DownloadCommand;
use StaticPHP\Command\DumpExtensionsCommand;
@@ -87,6 +88,7 @@ class ConsoleApplication extends Application
new GenExtDocsCommand(),
new GenDepsDataCommand(),
new GenExtTestMatrixCommand(),
new TestBotCommand(),
]);
// add additional commands from registries

View File

@@ -84,7 +84,7 @@ class DefaultShell extends Shell
/**
* Execute a Git clone command to clone a repository.
*/
public function executeGitClone(string $url, string $branch, string $path, bool $shallow = true, ?array $submodules = null): void
public function executeGitClone(string $url, string $branch, string $path, bool $shallow = true, ?array $submodules = null, int $retries = 0): void
{
$path = FileSystem::convertPath($path);
if (file_exists($path)) {
@@ -99,7 +99,21 @@ class DefaultShell extends Shell
$cmd = clean_spaces("{$git} clone -c http.lowSpeedLimit=1 -c http.lowSpeedTime=3600 --config core.autocrlf=false --branch {$branch_arg} {$shallow_arg} {$submodules_arg} {$url_arg} {$path_arg}");
$this->logCommandInfo($cmd);
logger()->debug("[GIT CLONE] {$cmd}");
$this->passthru($cmd, $this->console_putput);
try {
$this->passthru($cmd, $this->console_putput);
} catch (InterruptException $e) {
throw $e;
} catch (\Throwable $e) {
if ($retries > 0) {
logger()->warning("Git clone failed, retrying... ({$retries} retries left)");
if (is_dir($path)) {
FileSystem::removeDir($path);
}
$this->executeGitClone($url, $branch, $path, $shallow, $submodules, $retries - 1);
return;
}
throw $e;
}
if ($submodules !== null) {
$depth_flag = $shallow ? '--depth 1' : '';
foreach ($submodules as $submodule) {