Compare commits

...

74 Commits

Author SHA1 Message Date
henderkes
6df778f92f llvm-tools: build host llvm-objcopy/strip/profdata under ZigToolchain
Add an `llvm-tools` target artifact that downloads llvm-project source
matching the version of clang shipped by the active zig install,
builds llvm-objcopy, llvm-strip and llvm-profdata into
PKG_ROOT_PATH/llvm-tools/bin, and exposes them through the same
path/binary/isInstalled static surface as the other artifacts.

A new LlvmToolsCheck doctor item runs when the active toolchain is
ZigToolchain and reports whether the three tools are built, with a
fix that installs the package and runs the build.

PackageBuilder now picks the right tool when the active toolchain is
ZigToolchain:
- extractDebugInfo() honours OBJCOPY from the environment, then falls
  back to llvm-tools' llvm-objcopy under Zig and plain objcopy
  otherwise.
- stripBinary() uses llvm-strip under Zig and plain strip otherwise.

System strip/objcopy refuse zig-produced archives and bitcode
sections, so without this the strip stage breaks LTO builds. Other
toolchains keep using the system binaries.

ApplicationContext::tryGet() wraps the container's get() in a
try/catch and returns null on failure, so PackageBuilder can ask
"which toolchain is active right now" without PHP-DI throwing on
autowirable-but-unconstructable classes.

Depends on v3c/artifact-static-helpers (uses zig::isInstalled()
and zig::binary()).
2026-05-24 21:50:57 +07:00
Jerry Ma
582a88ef60 artifact: use {pkg_root_path} template in rust and go_win extract (#1164) 2026-05-24 22:04:39 +08:00
Jerry Ma
153003b75c imagemagick: --without-gcc-arch (#1162) 2026-05-24 22:04:02 +08:00
Jerry Ma
899555a964 watcher: drop ldflags from compile-only invocation (#1161) 2026-05-24 22:03:38 +08:00
Jerry Ma
891a222c39 revert useless patch (#1160) 2026-05-24 22:03:11 +08:00
henderkes
39beb68024 artifact: use {pkg_root_path} template in rust and go_win extract
Switch the rust and go_win downloaders from baking PKG_ROOT_PATH into
the extract path at download time to the {pkg_root_path} template,
which ArtifactExtractor resolves at extract time. This keeps the path
stable across runs where pkg_root_path differs between download and
extract (e.g. containerised vs host builds).
2026-05-24 20:56:08 +07:00
henderkes
0807e9e253 watcher: drop ldflags from compile-only invocation
The shell invocation runs `$CXX -c` to compile watcher-c.cpp to a .o,
which never links. Passing linker flags to a compile-only step is
either ignored or, with some flags, an error. Drop them.
2026-05-24 20:54:44 +07:00
henderkes
1a779be028 imagemagick: --without-gcc-arch
ax_gcc_archflag has no Zen cpuid pattern and falls back to
-mtune=amdfam10, which under LLVM+LTO emits SSE4a extrq and SIGILLs on
Intel hosts. Disable the implicit --with-gcc-arch so host CPU features
do not bleed into the built binaries.
2026-05-24 20:54:21 +07:00
henderkes
bdfd3eb269 also revert #1122 2026-05-24 20:41:18 +07:00
Marc
7ae5d742c2 V3 check/4 (#1159) 2026-05-24 20:24:11 +07:00
Marc
95be291a84 Merge branch 'v3' into v3-check/4 2026-05-24 20:24:03 +07:00
Marc
d89add106a V3 check/3 (#1158) 2026-05-24 20:23:44 +07:00
Marc
a36129c6cd V3 check/2 (#1157) 2026-05-24 20:23:32 +07:00
Marc
3f3edd62a1 Update src/Package/Extension/password_argon2.php 2026-05-24 17:57:02 +07:00
crazywhalecc
82b77af317 Chore: extension fixes
clickhouse, mongodb, opcache, password-argon2, pgsql, spx
2026-05-24 18:16:47 +08:00
crazywhalecc
df26b93e58 Remove redundant suffix for getClassesPsr4 function 2026-05-24 18:12:04 +08:00
crazywhalecc
d1b4c05381 Fix curl exe build on windows 2026-05-24 18:11:41 +08:00
crazywhalecc
e1658bc0e6 Chore: gettext-win version, password-argon2 deps 2026-05-24 18:09:51 +08:00
crazywhalecc
5053620b61 feat: auto-load local working directory registry in vendor mode 2026-05-24 18:07:06 +08:00
crazywhalecc
9366cbacd9 Update discord invite link 2026-05-24 18:06:30 +08:00
Jerry Ma
b8ce9f7787 [v3] fix(windows): static builds vswhere.exe -product * (#1149) 2026-05-22 10:20:18 +08:00
Jerry Ma
6772403d81 [v3] fix: use ftpmirror.gnu.org instead of ftp.gnu.org (#1151) 2026-05-21 15:26:58 +08:00
Marc
60a91a82e1 [v3] fix(macos): static build remove -fno-plt from macOS CFLAGS (#1150) 2026-05-21 12:06:18 +07:00
Luther Monson
4a274b69ac fix: use ftpmirror.gnu.org instead of ftp.gnu.org
ftp.gnu.org is unreliable and frequently times out during CI builds.
ftpmirror.gnu.org is GNU's own CDN that auto-redirects to the nearest
mirror. This is the recommended download method per
https://www.gnu.org/prep/ftp.en.html

Also normalizes /pub/gnu/ paths to /gnu/ since ftpmirror only serves
the latter.

Affects: libiconv, gettext, gmp, idn2, libunistring, ncurses, readline
2026-05-20 21:09:34 -07:00
Luther Monson
e4edd0a00f Merge branch 'v3' into fix/macos-fno-plt 2026-05-20 21:05:54 -07:00
Luther Monson
ae26ef3bdb fix(macos): remove -fno-plt from macOS CFLAGS
-fno-plt is an ELF-only flag that has no effect on macOS Mach-O
targets — clang emits "argument unused" when it encounters it.
Libraries like xz that run -Werror sanity checks during configure
promote that warning to a fatal error, breaking the build.
2026-05-20 20:57:12 -07:00
Luther Monson
049ecfe0a5 Merge branch 'v3' into fix/vswhere-products 2026-05-20 20:54:26 -07:00
Jerry Ma
01a4d872ad fix windows test failures: path separators and arch normalization (#1148) 2026-05-21 10:50:33 +08:00
Luther Monson
a9e54bb725 fix(windows): add -products * to vswhere so Build Tools are found
vswhere.exe defaults to searching Community, Professional, and
Enterprise editions only. CI environments typically install the
lightweight Build Tools product which is a separate product type
(Microsoft.VisualStudio.Product.BuildTools). Without -products *
the tool returns no results and the build fails with "Visual Studio
with C++ tools not found".

See: https://github.com/microsoft/vswhere/wiki/Find-MSBuild
2026-05-20 18:36:58 -07:00
Luther Monson
ad9b9ec69f Merge branch 'v3' into v3-fix-windows-test-paths 2026-05-19 23:19:39 -07:00
Marc
8a37303925 Add a Log Filter to Strip Github Tokens (#1147) 2026-05-20 13:19:03 +07:00
Luther Monson
52d234f1f4 fix windows test failures: path separators and arch normalization 2026-05-19 21:59:18 -07:00
Luther Monson
a3c39576df filter secrets at logger callback; register basic-auth encoded blob 2026-05-19 21:23:43 -07:00
Marc
3f7bad75ec Feat/clickhouse (#1137) 2026-05-11 13:28:16 +07:00
crazywhalecc
a3f135d26c Simplify pull request template 2026-05-11 13:59:32 +08:00
Jerry Ma
0732c1f0b0 Merge branch 'v3' into feat/clickhouse 2026-05-11 13:18:16 +08:00
Jerry Ma
9b64ad8299 Add dev:gen-ext-test-matrix command (#1133) 2026-05-11 13:17:57 +08:00
crazywhalecc
4d1ae0093d Bypass curl test on swow loaded time 2026-05-11 11:02:31 +08:00
Jerry Ma
db11d5a420 Update config/pkg/ext/ext-swow.yml 2026-05-11 11:01:43 +08:00
Marc
b20c1fa5c2 Update config/pkg/ext/ext-swow.yml 2026-05-11 09:49:19 +07:00
crazywhalecc
bf38212814 Add isolated extension mark 2026-05-11 10:07:02 +08:00
crazywhalecc
42fdc4eb87 Use PHP 8.5 by default 2026-05-11 09:48:31 +08:00
crazywhalecc
685f5c565f Use PHP 8.5 by default 2026-05-11 09:47:10 +08:00
crazywhalecc
b8ee484e81 Comment upterm session 2026-05-10 16:38:45 +08:00
crazywhalecc
c186038dca Use system cc instead 2026-05-10 16:27:25 +08:00
crazywhalecc
36e738f849 strange there 2026-05-10 16:06:20 +08:00
crazywhalecc
2cc3c8c9af Revert 2026-05-10 15:55:12 +08:00
crazywhalecc
0469b658bf Revert 2026-05-10 15:55:03 +08:00
crazywhalecc
7107566da7 Fix wrongly constructed class 2026-05-10 15:50:21 +08:00
crazywhalecc
02d8f51bb2 Enhance Unix Makefile patch to disable auto-vectorization for zig-cc to prevent minilua segfault 2026-05-10 15:17:51 +08:00
Jerry Ma
21c868463a Update tests.yml 2026-05-10 14:26:38 +08:00
Jerry Ma
079a30c5b1 Add tmate session setup for debugging on failure 2026-05-10 14:12:47 +08:00
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
henderkes
3f48413281 add clickhouse extension by ilia 2026-05-09 15:10:30 +07:00
henderkes
dc6e63e1ba fix logic errors in shared ext patching 2026-05-09 15:09:59 +07: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
crazywhalecc
cd803c75c5 Add filtering options for extensions, libs, and OS in test matrix generation 2026-05-09 10:44:04 +08:00
crazywhalecc
ad7475246f Merge remote-tracking branch 'origin/v3-docs/readme' into v3-docs/readme 2026-05-09 10:33:10 +08:00
crazywhalecc
b09cc968e6 Add curl execute output log 2026-05-09 10:19:16 +08:00
crazywhalecc
bf308e89a5 Remove duplicate phar patch for micro 2026-05-09 09:49:53 +08:00
crazywhalecc
bf326de985 Fix extracting hosted type for zip archive caused overwriting 2026-05-09 08:17:03 +08:00
crazywhalecc
4f9a555bf3 ds use git (pecl have buggy config.w32) 2026-05-09 08:16:11 +08:00
crazywhalecc
04df87cd5f Make intl use c++17 2026-05-09 08:15:45 +08:00
71 changed files with 1309 additions and 339 deletions

View File

@@ -1,17 +1,12 @@
## What does this PR do? ## What does this PR do?
<!-- Please describe the changes made in this PR here. -->
## Checklist before merging ## Checklist before merging
> If your PR involves the changes mentioned below and completed the action, please tick the corresponding option. - If you modified `*.php` or `*.yml`, run them locally to ensure your changes are valid:
> If a modification is not involved, please skip it directly.
- If you modified `*.php` or `*.json`, run them locally to ensure your changes are valid:
- [ ] `composer cs-fix` - [ ] `composer cs-fix`
- [ ] `composer analyse` - [ ] `composer analyse`
- [ ] `composer test` - [ ] `composer test`
- [ ] `bin/spc dev:sort-config` - [ ] `bin/spc dev:lint-config`
- If it's an extension or dependency update, please ensure the following:
- [ ] Add your test combination to `src/globals/test-extensions.php`.
- [ ] If adding new or fixing bugs, add commit message containing `extension test` or `test extensions` to trigger full test suite.

View File

@@ -1,9 +1,9 @@
name: Tests name: v3 Tests
on: on:
pull_request: pull_request:
branches: [ "main", "v3" ] branches: [ "v3" ]
types: [ opened, synchronize, reopened ] types: [ opened, synchronize, reopened, labeled, unlabeled ]
paths: paths:
- 'src/**' - 'src/**'
- 'config/**' - 'config/**'
@@ -15,6 +15,10 @@ on:
permissions: read-all permissions: read-all
concurrency:
group: ${{ github.workflow }}-${{ github.event.pull_request.number }}
cancel-in-progress: true
env: env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
@@ -103,114 +107,171 @@ jobs:
run: composer install -q --no-ansi --no-interaction --no-scripts --no-progress --prefer-dist run: composer install -q --no-ansi --no-interaction --no-scripts --no-progress --prefer-dist
- name: "Run PHPUnit Tests" - name: "Run PHPUnit Tests"
run: SPC_LIBC=glibc vendor/bin/phpunit tests/ --no-coverage run: vendor/bin/phpunit tests/ --no-coverage
define-matrix: check-gate:
if: false # TODO: enable when refactoring workflows name: "Check: need-test label"
name: "Define Matrix"
runs-on: ubuntu-latest runs-on: ubuntu-latest
outputs: outputs:
php: ${{ steps.gendef.outputs.php }} enabled: ${{ steps.gate.outputs.enabled }}
os: ${{ steps.gendef.outputs.os }}
steps: steps:
- name: "Checkout" - name: Check label
uses: actions/checkout@v4 id: gate
- name: "Setup PHP"
uses: shivammathur/setup-php@v2
with:
php-version: 8.4
extensions: curl, openssl, mbstring
- name: Define
id: gendef
run: | run: |
PHP_VERSIONS=$(php src/globals/test-extensions.php php) LABELS='${{ toJSON(github.event.pull_request.labels.*.name) }}'
OS_VERSIONS=$(php src/globals/test-extensions.php os) if echo "$LABELS" | grep -q '"need-test"'; then
echo 'php='"$PHP_VERSIONS" >> "$GITHUB_OUTPUT" echo "enabled=true" >> "$GITHUB_OUTPUT"
echo 'os='"$OS_VERSIONS" >> "$GITHUB_OUTPUT" else
echo "enabled=false" >> "$GITHUB_OUTPUT"
fi
test-bot:
build: name: "Test Bot: analyze PR"
if: false needs: check-gate
name: "Build PHP Test (PHP ${{ matrix.php }} ${{ matrix.os }})" if: needs.check-gate.outputs.enabled == 'true'
runs-on: ${{ matrix.os }} runs-on: ubuntu-latest
needs: [define-matrix, php-cs-fixer, phpstan, phpunit] permissions:
timeout-minutes: 120 pull-requests: write
strategy: contents: read
matrix: outputs:
php: ${{ fromJSON(needs.define-matrix.outputs.php) }} need_test: ${{ steps.bot.outputs.need_test }}
os: ${{ fromJSON(needs.define-matrix.outputs.os) }} gen_matrix_args: ${{ steps.bot.outputs.gen_matrix_args }}
fail-fast: false gen_matrix_args_tier2: ${{ steps.bot.outputs.gen_matrix_args_tier2 }}
php_versions: ${{ steps.bot.outputs.php_versions }}
tier2: ${{ steps.bot.outputs.tier2 }}
steps: steps:
- name: "Update runner packages" - uses: actions/checkout@v4
if: ${{ startsWith(matrix.os, 'ubuntu-') }}
run: sudo apt-get update && sudo apt-get install -y ca-certificates
- name: "Checkout" - name: Setup PHP
uses: actions/checkout@v4
- name: "Setup PHP"
uses: shivammathur/setup-php@v2 uses: shivammathur/setup-php@v2
with: with:
php-version: 8.4 php-version: '8.4'
tools: pecl, composer
extensions: curl, openssl, mbstring extensions: curl, openssl, mbstring
ini-values: memory_limit=-1 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: env:
phpts: nts phpts: nts
- name: "Cache composer packages" - name: Install dependencies
id: composer-cache run: composer install -q --no-ansi --no-interaction --no-scripts --no-progress --prefer-dist --no-dev
uses: actions/cache@v4
with:
path: vendor
key: ${{ runner.os }}-php-${{ hashFiles('**/composer.lock') }}
restore-keys: |
${{ runner.os }}-php-
# Cache downloaded source - name: Build
- id: cache-download env:
uses: actions/cache@v4 SPC_USE_SUDO: "yes"
with: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
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-') }}
run: | run: |
php src/globals/test-extensions.php install_upx_cmd ${{ matrix.os }} ${{ matrix.php }} ./bin/spc doctor --auto-fix
echo "UPX_CMD=$(php src/globals/test-extensions.php upx)" >> $env:GITHUB_ENV ${{ matrix.combo.build-args }} --dl-with-php=${{ matrix.combo.php-version }}
- name: "Prepare UPX for Linux" # - name: Setup upterm session
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
with:
name: build-logs-${{ matrix.os }}-${{ matrix.php }}
path: log
# - name: Setup tmate session
# if: ${{ failure() }} # if: ${{ failure() }}
# uses: mxschmitt/action-tmate@v3 # uses: owenthereal/action-upterm@v1
- name: Upload logs
if: always() && hashFiles('log/**') != ''
uses: actions/upload-artifact@v4
with:
name: logs-${{ matrix.combo.os }}-${{ matrix.combo.arch }}-${{ matrix.combo.extension }}-php${{ matrix.combo.php-version }}
path: log

View File

@@ -5,7 +5,7 @@
[![Releases](https://img.shields.io/packagist/v/crazywhalecc/static-php-cli?include_prereleases&label=Release&style=flat-square)](https://github.com/crazywhalecc/static-php-cli/releases) [![Releases](https://img.shields.io/packagist/v/crazywhalecc/static-php-cli?include_prereleases&label=Release&style=flat-square)](https://github.com/crazywhalecc/static-php-cli/releases)
[![CI](https://img.shields.io/github/actions/workflow/status/crazywhalecc/static-php-cli/tests.yml?branch=main&label=Build%20Test&style=flat-square)](https://github.com/crazywhalecc/static-php-cli/actions/workflows/tests.yml) [![CI](https://img.shields.io/github/actions/workflow/status/crazywhalecc/static-php-cli/tests.yml?branch=main&label=Build%20Test&style=flat-square)](https://github.com/crazywhalecc/static-php-cli/actions/workflows/tests.yml)
[![License](https://img.shields.io/badge/License-MIT-blue.svg?style=flat-square)](https://github.com/crazywhalecc/static-php-cli/blob/main/LICENSE) [![License](https://img.shields.io/badge/License-MIT-blue.svg?style=flat-square)](https://github.com/crazywhalecc/static-php-cli/blob/main/LICENSE)
[![Discord](https://img.shields.io/discord/nrSRbpMJ?label=Discord&logo=discord&style=flat-square)](https://discord.gg/nrSRbpMJ) [![Discord](https://img.shields.io/discord/nrSRbpMJ?label=Discord&logo=discord&style=flat-square)](https://discord.gg/xf6Rd4pEAk)
**StaticPHP** 是一个强大的工具,用于构建可移植的可执行文件,包括 PHP、扩展等。 **StaticPHP** 是一个强大的工具,用于构建可移植的可执行文件,包括 PHP、扩展等。

View File

@@ -5,7 +5,7 @@
[![Releases](https://img.shields.io/packagist/v/crazywhalecc/static-php-cli?include_prereleases&label=Release&style=flat-square)](https://github.com/crazywhalecc/static-php-cli/releases) [![Releases](https://img.shields.io/packagist/v/crazywhalecc/static-php-cli?include_prereleases&label=Release&style=flat-square)](https://github.com/crazywhalecc/static-php-cli/releases)
[![CI](https://img.shields.io/github/actions/workflow/status/crazywhalecc/static-php-cli/tests.yml?branch=main&label=Build%20Test&style=flat-square)](https://github.com/crazywhalecc/static-php-cli/actions/workflows/tests.yml) [![CI](https://img.shields.io/github/actions/workflow/status/crazywhalecc/static-php-cli/tests.yml?branch=main&label=Build%20Test&style=flat-square)](https://github.com/crazywhalecc/static-php-cli/actions/workflows/tests.yml)
[![License](https://img.shields.io/badge/License-MIT-blue.svg?style=flat-square)](https://github.com/crazywhalecc/static-php-cli/blob/main/LICENSE) [![License](https://img.shields.io/badge/License-MIT-blue.svg?style=flat-square)](https://github.com/crazywhalecc/static-php-cli/blob/main/LICENSE)
[![Discord](https://img.shields.io/discord/nrSRbpMJ?label=Discord&logo=discord&style=flat-square)](https://discord.gg/nrSRbpMJ) [![Discord](https://img.shields.io/discord/nrSRbpMJ?label=Discord&logo=discord&style=flat-square)](https://discord.gg/xf6Rd4pEAk)
**StaticPHP** is a powerful tool designed for building portable executables including PHP, extensions, and more. **StaticPHP** is a powerful tool designed for building portable executables including PHP, extensions, and more.

View File

@@ -4,5 +4,5 @@ ncurses:
- COPYING - COPYING
source: source:
type: filelist type: filelist
url: 'https://ftp.gnu.org/pub/gnu/ncurses/' url: 'https://ftpmirror.gnu.org/gnu/ncurses/'
regex: '/href="(?<file>ncurses-(?<version>[^"]+)\.tar\.gz)"/' regex: '/href="(?<file>ncurses-(?<version>[^"]+)\.tar\.gz)"/'

View File

@@ -142,7 +142,7 @@ CXX=${SPC_DEFAULT_CXX}
AR=${SPC_DEFAULT_AR} AR=${SPC_DEFAULT_AR}
LD=${SPC_DEFAULT_LD} LD=${SPC_DEFAULT_LD}
; default compiler flags, used in CMake toolchain file, openssl and pkg-config build ; default compiler flags, used in CMake toolchain file, openssl and pkg-config build
SPC_DEFAULT_CFLAGS="--target=${MAC_ARCH}-apple-darwin -O3 -fno-plt -fno-omit-frame-pointer -mno-omit-leaf-frame-pointer -ffunction-sections -fdata-sections" SPC_DEFAULT_CFLAGS="--target=${MAC_ARCH}-apple-darwin -O3 -fno-omit-frame-pointer -mno-omit-leaf-frame-pointer -ffunction-sections -fdata-sections"
SPC_DEFAULT_CXXFLAGS="${SPC_DEFAULT_CFLAGS}" SPC_DEFAULT_CXXFLAGS="${SPC_DEFAULT_CFLAGS}"
SPC_DEFAULT_LDFLAGS="-Wl,-dead_strip" SPC_DEFAULT_LDFLAGS="-Wl,-dead_strip"
; phpmicro patches, for more info, see: https://github.com/easysoft/phpmicro/tree/master/patches ; phpmicro patches, for more info, see: https://github.com/easysoft/phpmicro/tree/master/patches

View File

@@ -186,6 +186,7 @@ ext-password-argon2:
type: php-extension type: php-extension
depends: depends:
- libargon2 - libargon2
suggests:
- ext-openssl - ext-openssl
php-extension: php-extension:
os: os:

View File

@@ -0,0 +1,19 @@
ext-clickhouse:
type: php-extension
artifact:
source:
type: ghtar
repo: iliaal/php_clickhouse
extract: php-src/ext/clickhouse
prefer-stable: true
metadata:
license-files: [LICENSE]
license: PHP-3.01
suggests@unix:
- openssl
lang: cpp
php-extension:
os:
- Linux
- Darwin
arg-type@unix: custom

View File

@@ -2,8 +2,10 @@ ext-ds:
type: php-extension type: php-extension
artifact: artifact:
source: source:
type: pecl type: git
name: ds url: 'https://github.com/php-ds/ext-ds.git'
rev: master
extract: php-src/ext/ds
metadata: metadata:
license-files: [LICENSE] license-files: [LICENSE]
license: MIT license: MIT

View File

@@ -14,5 +14,6 @@ ext-swow:
- curl - curl
- ext-openssl - ext-openssl
- ext-curl - ext-curl
- postgresql
php-extension: php-extension:
arg-type: custom arg-type: custom

View File

@@ -4,6 +4,6 @@ gettext-win:
source: source:
type: git type: git
url: 'https://github.com/winlibs/gettext.git' url: 'https://github.com/winlibs/gettext.git'
rev: master rev: '0.18'
static-libs@windows: static-libs@windows:
- libintl_a.lib - libintl_a.lib

View File

@@ -3,7 +3,7 @@ gettext:
artifact: artifact:
source: source:
type: filelist type: filelist
url: 'https://ftp.gnu.org/pub/gnu/gettext/' url: 'https://ftpmirror.gnu.org/gnu/gettext/'
regex: '/href="(?<file>gettext-(?<version>[^"]+)\.tar\.xz)"/' regex: '/href="(?<file>gettext-(?<version>[^"]+)\.tar\.xz)"/'
metadata: metadata:
license-files: [gettext-runtime/intl/COPYING.LIB] license-files: [gettext-runtime/intl/COPYING.LIB]

View File

@@ -3,7 +3,7 @@ gmp:
artifact: artifact:
source: source:
type: filelist type: filelist
url: 'https://ftp.gnu.org/gnu/gmp/' url: 'https://ftpmirror.gnu.org/gnu/gmp/'
regex: '/href="(?<file>gmp-(?<version>[^"]+)\.tar\.xz)"/' regex: '/href="(?<file>gmp-(?<version>[^"]+)\.tar\.xz)"/'
source-mirror: source-mirror:
type: url type: url

View File

@@ -3,7 +3,7 @@ idn2:
artifact: artifact:
source: source:
type: filelist type: filelist
url: 'https://ftp.gnu.org/gnu/libidn/' url: 'https://ftpmirror.gnu.org/gnu/libidn/'
regex: '/href="(?<file>libidn2-(?<version>[^"]+)\.tar\.gz)"/' regex: '/href="(?<file>libidn2-(?<version>[^"]+)\.tar\.gz)"/'
metadata: metadata:
license-files: [COPYING.LESSERv3] license-files: [COPYING.LESSERv3]

View File

@@ -3,7 +3,7 @@ libiconv:
artifact: artifact:
source: source:
type: filelist type: filelist
url: 'https://ftp.gnu.org/gnu/libiconv/' url: 'https://ftpmirror.gnu.org/gnu/libiconv/'
regex: '/href="(?<file>libiconv-(?<version>[^"]+)\.tar\.gz)"/' regex: '/href="(?<file>libiconv-(?<version>[^"]+)\.tar\.gz)"/'
metadata: metadata:
license-files: [COPYING.LIB] license-files: [COPYING.LIB]

View File

@@ -3,7 +3,7 @@ libunistring:
artifact: artifact:
source: source:
type: filelist type: filelist
url: 'https://ftp.gnu.org/gnu/libunistring/' url: 'https://ftpmirror.gnu.org/gnu/libunistring/'
regex: '/href="(?<file>libunistring-(?<version>[^"]+)\.tar\.gz)"/' regex: '/href="(?<file>libunistring-(?<version>[^"]+)\.tar\.gz)"/'
metadata: metadata:
license-files: [COPYING.LIB] license-files: [COPYING.LIB]

View File

@@ -3,7 +3,7 @@ readline:
artifact: artifact:
source: source:
type: filelist type: filelist
url: 'https://ftp.gnu.org/pub/gnu/readline/' url: 'https://ftpmirror.gnu.org/gnu/readline/'
regex: '/href="(?<file>readline-(?<version>[^"]+)\.tar\.gz)"/' regex: '/href="(?<file>readline-(?<version>[^"]+)\.tar\.gz)"/'
metadata: metadata:
license-files: [COPYING] license-files: [COPYING]

View File

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

View File

@@ -0,0 +1,6 @@
llvm-tools:
type: target
artifact:
binary: custom
depends:
- zig

View File

@@ -29,7 +29,7 @@ spc download [artifacts] [options]
| `--for-packages=<list>` | | Download artifacts needed by the given packages | | `--for-packages=<list>` | | Download artifacts needed by the given packages |
| `--without-suggests` | | Skip suggested packages when using `--for-extensions` | | `--without-suggests` | | Skip suggested packages when using `--for-extensions` |
| `--clean` | | Delete existing download cache before fetching | | `--clean` | | Delete existing download cache before fetching |
| `--with-php=<ver>` | | PHP version in `major.minor` format (default: `8.4`) | | `--with-php=<ver>` | | PHP version in `major.minor` format (default: `8.5`) |
| `--prefer-binary` | `-p` | Prefer pre-built binaries over source archives | | `--prefer-binary` | `-p` | Prefer pre-built binaries over source archives |
| `--prefer-source` | | Prefer source archives over pre-built binaries | | `--prefer-source` | | Prefer source archives over pre-built binaries |
| `--source-only` | | Only download source artifacts | | `--source-only` | | Only download source artifacts |
@@ -47,7 +47,7 @@ spc download [artifacts] [options]
```bash ```bash
# Download only what the chosen extensions need # Download only what the chosen extensions need
spc download --for-extensions="bcmath,openssl,curl" --with-php=8.4 spc download --for-extensions="bcmath,openssl,curl" --with-php=8.5
# Download specific artifacts # Download specific artifacts
spc download "php-src,openssl" spc download "php-src,openssl"
@@ -136,7 +136,7 @@ All downloader options are available with the `--dl-` prefix:
| Option | Description | | Option | Description |
|------------------------------------|--------------------------------------------| |------------------------------------|--------------------------------------------|
| `--dl-with-php=<ver>` | PHP version to download (default: `8.4`) | | `--dl-with-php=<ver>` | PHP version to download (default: `8.5`) |
| `--dl-prefer-binary` | Prefer pre-built binaries for dependencies | | `--dl-prefer-binary` | Prefer pre-built binaries for dependencies |
| `--dl-parallel=<n>` | Number of parallel downloads | | `--dl-parallel=<n>` | Number of parallel downloads |
| `--dl-retry=<n>` | Number of retries on failure | | `--dl-retry=<n>` | Number of retries on failure |
@@ -265,12 +265,12 @@ spc check-update [artifact] [options]
### Options ### Options
| Option | Short | Description | | Option | Short | Description |
|---|---|---| |---|---|------------------------------------------------------------------------------------------|
| `--json` | | Output results in JSON format | | `--json` | | Output results in JSON format |
| `--bare` | | Check without requiring the artifact to be downloaded first (old version will be `null`) | | `--bare` | | Check without requiring the artifact to be downloaded first (old version will be `null`) |
| `--parallel=<n>` | `-p` | Number of parallel update checks (default: `10`) | | `--parallel=<n>` | `-p` | Number of parallel update checks (default: `10`) |
| `--with-php=<ver>` | | PHP version context in `major.minor` format (default: `8.4`) | | `--with-php=<ver>` | | PHP version context in `major.minor` format (default: `8.5`) |
### Examples ### Examples

View File

@@ -26,7 +26,7 @@ The `craft` command reads a `craft.yml` file and handles everything automaticall
Create a `craft.yml` in your working directory and declare the PHP version, extensions, and target SAPIs: Create a `craft.yml` in your working directory and declare the PHP version, extensions, and target SAPIs:
```yaml ```yaml
php-version: 8.4 php-version: 8.5
extensions: bcmath,posix,phar,zlib,openssl,curl,fileinfo,tokenizer extensions: bcmath,posix,phar,zlib,openssl,curl,fileinfo,tokenizer
sapi: sapi:
- cli - cli
@@ -80,10 +80,10 @@ If you want to pre-download ahead of time, or if you're working in a slow-networ
```bash ```bash
# Download only what the chosen extensions need (recommended) # Download only what the chosen extensions need (recommended)
spc download --for-extensions="bcmath,posix,phar,zlib,openssl,curl,fileinfo,tokenizer" --with-php=8.4 spc download --for-extensions="bcmath,posix,phar,zlib,openssl,curl,fileinfo,tokenizer" --with-php=8.5
# Download by specific package names # Download by specific package names
spc download "curl,openssl" --with-php=8.4 spc download "curl,openssl" --with-php=8.5
``` ```
Downloads are cached in `downloads/` and reused across builds automatically. Downloads are cached in `downloads/` and reused across builds automatically.

View File

@@ -47,7 +47,7 @@ Build your CLI with [symfony/console](https://symfony.com/doc/current/components
## Community ## Community
Join our [Discord server](https://discord.gg/nrSRbpMJ) to ask questions, share your builds, and connect with other StaticPHP users. Join our [Discord server](https://discord.gg/xf6Rd4pEAk) to ask questions, share your builds, and connect with other StaticPHP users.
## Next steps ## Next steps

View File

@@ -22,32 +22,32 @@ spc download [artifacts] [options]
### 选项 ### 选项
| 选项 | 缩写 | 说明 | | 选项 | 缩写 | 说明 |
|---|------|---| |---|------|------------------------------------|
| `--for-extensions=<list>` | `-e` | 按扩展名下载其所需的制品 | | `--for-extensions=<list>` | `-e` | 按扩展名下载其所需的制品 |
| `--for-libs=<list>` | `-l` | 按库名下载其所需的制品 | | `--for-libs=<list>` | `-l` | 按库名下载其所需的制品 |
| `--for-packages=<list>` | | 按包名下载其所需的制品 | | `--for-packages=<list>` | | 按包名下载其所需的制品 |
| `--without-suggests` | | 使用 `--for-extensions` 时跳过建议包 | | `--without-suggests` | | 使用 `--for-extensions` 时跳过建议包 |
| `--clean` | | 下载前删除旧的下载缓存 | | `--clean` | | 下载前删除旧的下载缓存 |
| `--with-php=<ver>` | | PHP 版本,格式为 `major.minor`(默认 `8.4`| | `--with-php=<ver>` | | PHP 版本,格式为 `major.minor`(默认 `8.5` |
| `--prefer-binary` | `-p` | 优先使用预编译二进制 | | `--prefer-binary` | `-p` | 优先使用预编译二进制 |
| `--prefer-source` | | 优先使用源码包 | | `--prefer-source` | | 优先使用源码包 |
| `--source-only` | | 仅下载源码制品 | | `--source-only` | | 仅下载源码制品 |
| `--binary-only` | | 仅下载二进制制品 | | `--binary-only` | | 仅下载二进制制品 |
| `--parallel=<n>` | `-P` | 并行下载数(默认 `1`| | `--parallel=<n>` | `-P` | 并行下载数(默认 `1` |
| `--retry=<n>` | `-R` | 失败重试次数(默认 `0`| | `--retry=<n>` | `-R` | 失败重试次数(默认 `0` |
| `--ignore-cache=<list>` | `-i` | 强制重新下载指定制品 | | `--ignore-cache=<list>` | `-i` | 强制重新下载指定制品 |
| `--no-alt` | | 不使用镜像站 | | `--no-alt` | | 不使用镜像站 |
| `--no-shallow-clone` | | 不使用浅层克隆 | | `--no-shallow-clone` | | 不使用浅层克隆 |
| `--custom-url=<src:url>` | `-U` | 覆盖指定源的下载地址 | | `--custom-url=<src:url>` | `-U` | 覆盖指定源的下载地址 |
| `--custom-git=<src:branch:url>` | `-G` | 覆盖为自定义 git 仓库 | | `--custom-git=<src:branch:url>` | `-G` | 覆盖为自定义 git 仓库 |
| `--custom-local=<src:path>` | `-L` | 使用本地路径作为制品来源 | | `--custom-local=<src:path>` | `-L` | 使用本地路径作为制品来源 |
### 示例 ### 示例
```bash ```bash
# 按扩展名下载(推荐) # 按扩展名下载(推荐)
spc download --for-extensions="bcmath,openssl,curl" --with-php=8.4 spc download --for-extensions="bcmath,openssl,curl" --with-php=8.5
# 下载指定制品 # 下载指定制品
spc download "php-src,openssl" spc download "php-src,openssl"
@@ -134,14 +134,14 @@ spc build:php <extensions> [options]
所有下载器选项均可加 `--dl-` 前缀使用: 所有下载器选项均可加 `--dl-` 前缀使用:
| 选项 | 说明 | | 选项 | 说明 |
|---|---| |---|------------------------|
| `--dl-with-php=<ver>` | 指定下载的 PHP 版本(默认 `8.4`| | `--dl-with-php=<ver>` | 指定下载的 PHP 版本(默认 `8.5` |
| `--dl-prefer-binary` | 优先使用预编译二进制依赖 | | `--dl-prefer-binary` | 优先使用预编译二进制依赖 |
| `--dl-parallel=<n>` | 并行下载数 | | `--dl-parallel=<n>` | 并行下载数 |
| `--dl-retry=<n>` | 失败重试次数 | | `--dl-retry=<n>` | 失败重试次数 |
| `--dl-custom-url=<src:url>` | 覆盖指定源的下载地址 | | `--dl-custom-url=<src:url>` | 覆盖指定源的下载地址 |
| `--dl-custom-git=<src:branch:url>` | 覆盖为自定义 git 仓库 | | `--dl-custom-git=<src:branch:url>` | 覆盖为自定义 git 仓库 |
Downloader 选项传递给 `build:php` 命令时,会被自动下载器在构建前使用。 Downloader 选项传递给 `build:php` 命令时,会被自动下载器在构建前使用。
这样你就可以直接通过构建命令控制下载行为,无需单独执行 `spc download` 命令。 这样你就可以直接通过构建命令控制下载行为,无需单独执行 `spc download` 命令。
@@ -265,12 +265,12 @@ spc check-update [artifact] [options]
### 选项 ### 选项
| 选项 | 缩写 | 说明 | | 选项 | 缩写 | 说明 |
|---|---|---| |---|---|---------------------------------------|
| `--json` | | 以 JSON 格式输出结果 | | `--json` | | 以 JSON 格式输出结果 |
| `--bare` | | 检查时不要求制品已下载(旧版本显示为 null| | `--bare` | | 检查时不要求制品已下载(旧版本显示为 null |
| `--parallel=<n>` | `-p` | 并行检查数(默认 `10`| | `--parallel=<n>` | `-p` | 并行检查数(默认 `10` |
| `--with-php=<ver>` | | PHP 版本上下文,格式为 `major.minor`(默认 `8.4`| | `--with-php=<ver>` | | PHP 版本上下文,格式为 `major.minor`(默认 `8.5` |
### 示例 ### 示例

View File

@@ -26,7 +26,7 @@ StaticPHP 提供两种构建方式,根据使用场景选择:
在当前目录创建 `craft.yml`,声明要编译的 PHP 版本、扩展和目标 SAPI 在当前目录创建 `craft.yml`,声明要编译的 PHP 版本、扩展和目标 SAPI
```yaml ```yaml
php-version: 8.4 php-version: 8.5
extensions: bcmath,posix,phar,zlib,openssl,curl,fileinfo,tokenizer extensions: bcmath,posix,phar,zlib,openssl,curl,fileinfo,tokenizer
sapi: sapi:
- cli - cli
@@ -80,10 +80,10 @@ v3 版本中你可以省略这一步骤直接构建想要的内容Stati
```bash ```bash
# 按扩展列表下载(推荐,只下载实际需要的内容) # 按扩展列表下载(推荐,只下载实际需要的内容)
spc download --for-extensions="bcmath,posix,phar,zlib,openssl,curl,fileinfo,tokenizer" --with-php=8.4 spc download --for-extensions="bcmath,posix,phar,zlib,openssl,curl,fileinfo,tokenizer" --with-php=8.5
# 按依赖包列表下载 # 按依赖包列表下载
spc download "curl,openssl" --with-php=8.4 spc download "curl,openssl" --with-php=8.5
``` ```
下载内容缓存在 `downloads/` 目录,重复构建时会直接复用。 下载内容缓存在 `downloads/` 目录,重复构建时会直接复用。

View File

@@ -55,7 +55,7 @@ StaticPHP 支持将 FrankenPHP 连同所需扩展一起静态编译,
## 社区 ## 社区
加入我们的 [Discord 服务器](https://discord.gg/nrSRbpMJ),提问、分享构建成果,与其他 StaticPHP 用户交流。 加入我们的 [Discord 服务器](https://discord.gg/xf6Rd4pEAk),提问、分享构建成果,与其他 StaticPHP 用户交流。
## 接下来 ## 接下来

View File

@@ -20,16 +20,14 @@ class go_win
])] ])]
public function downBinary(ArtifactDownloader $downloader): DownloadResult public function downBinary(ArtifactDownloader $downloader): DownloadResult
{ {
$pkgroot = PKG_ROOT_PATH;
// get version // 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 === '') { if ($version === '') {
throw new DownloaderException('Failed to get latest Go version from https://go.dev/VERSION?m=text'); throw new DownloaderException('Failed to get latest Go version from https://go.dev/VERSION?m=text');
} }
// find SHA256 hash from download page // 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) { if ($page === '' || $page === false) {
throw new DownloaderException('Failed to get Go download page from https://go.dev/dl/'); throw new DownloaderException('Failed to get Go download page from https://go.dev/dl/');
} }
@@ -52,7 +50,7 @@ class go_win
throw new DownloaderException("Hash mismatch for downloaded go-win binary. Expected {$hash}, got {$file_hash}"); throw new DownloaderException("Hash mismatch for downloaded go-win binary. Expected {$hash}, got {$file_hash}");
} }
return DownloadResult::archive(basename($path), ['url' => $url, 'version' => $version], extract: "{$pkgroot}/go-win", verified: true, version: $version); return DownloadResult::archive(basename($path), ['url' => $url, 'version' => $version], extract: '{pkg_root_path}/go-win', verified: true, version: $version);
} }
#[CustomBinaryCheckUpdate('go-win', ['windows-x86_64'])] #[CustomBinaryCheckUpdate('go-win', ['windows-x86_64'])]

View File

@@ -39,11 +39,11 @@ class go_xcaddy
}; };
// get version and hash // 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 === '') { if ($version === '') {
throw new DownloaderException('Failed to get latest Go version from https://go.dev/VERSION?m=text'); 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) { if ($page === '' || $page === false) {
throw new DownloaderException('Failed to get Go download page from https://go.dev/dl/'); throw new DownloaderException('Failed to get Go download page from https://go.dev/dl/');
} }

View File

@@ -0,0 +1,162 @@
<?php
declare(strict_types=1);
namespace Package\Artifact;
use StaticPHP\Artifact\ArtifactDownloader;
use StaticPHP\Artifact\Downloader\DownloadResult;
use StaticPHP\Artifact\Downloader\Type\CheckUpdateResult;
use StaticPHP\Artifact\Downloader\Type\GitHubTokenSetupTrait;
use StaticPHP\Attribute\Artifact\AfterBinaryExtract;
use StaticPHP\Attribute\Artifact\CustomBinary;
use StaticPHP\Attribute\Artifact\CustomBinaryCheckUpdate;
use StaticPHP\DI\ApplicationContext;
use StaticPHP\Exception\BuildFailureException;
use StaticPHP\Exception\DownloaderException;
use StaticPHP\Package\PackageBuilder;
class llvm_tools
{
use GitHubTokenSetupTrait;
public const array TOOLS = ['llvm-objcopy', 'llvm-strip', 'llvm-profdata'];
/** Install prefix for the locally-built llvm-tools. */
public static function path(): string
{
return PKG_ROOT_PATH . '/llvm-tools';
}
/** Path to a binary under llvm-tools/bin (llvm-objcopy, llvm-strip, llvm-profdata, …). */
public static function binary(string $name = 'llvm-strip'): string
{
return self::path() . '/bin/' . $name;
}
/** True when every required TOOLS binary is present and executable. */
public static function isInstalled(): bool
{
foreach (self::TOOLS as $t) {
$p = self::binary($t);
if (!is_file($p) || !is_executable($p)) {
return false;
}
}
return true;
}
#[CustomBinary('llvm-tools', [
'linux-x86_64',
'linux-aarch64',
'macos-x86_64',
'macos-aarch64',
])]
public function downBinary(ArtifactDownloader $downloader): DownloadResult
{
$llvmVersion = $this->detectLlvmVersion()
?? throw new DownloaderException('Could not detect a clang version on host; install zig or clang first');
$tarball = "llvm-project-{$llvmVersion}.src.tar.xz";
$url = "https://github.com/llvm/llvm-project/releases/download/llvmorg-{$llvmVersion}/{$tarball}";
$tarballPath = DOWNLOAD_PATH . '/' . $tarball;
default_shell()->executeCurlDownload($url, $tarballPath, headers: $this->getGitHubTokenHeaders(), retries: $downloader->getRetry());
return DownloadResult::archive($tarball, ['url' => $url, 'version' => $llvmVersion], extract: '{source_path}/llvm-tools', verified: false, version: $llvmVersion);
}
#[CustomBinaryCheckUpdate('llvm-tools', [
'linux-x86_64',
'linux-aarch64',
'macos-x86_64',
'macos-aarch64',
])]
public function checkUpdateBinary(?string $old_version, ArtifactDownloader $downloader): CheckUpdateResult
{
$llvmVersion = $this->detectLlvmVersion()
?? throw new DownloaderException('Could not detect a clang version on host; install zig or clang first');
return new CheckUpdateResult(
old: $old_version,
new: $llvmVersion,
needUpdate: $old_version === null || $llvmVersion !== $old_version,
);
}
#[AfterBinaryExtract('llvm-tools', [
'linux-x86_64',
'linux-aarch64',
'macos-x86_64',
'macos-aarch64',
])]
public function postExtract(string $target_path): void
{
$this->buildForHost($target_path);
}
public function buildForHost(?string $sourceRoot = null): void
{
$sourceRoot ??= SOURCE_PATH . '/llvm-tools';
if (self::isInstalled()) {
return;
}
$llvmDir = "{$sourceRoot}/llvm";
if (!is_dir($llvmDir)) {
throw new BuildFailureException("llvm-tools: missing source at {$llvmDir} (extraction layout changed?)");
}
$buildDir = "{$sourceRoot}/build";
$installDir = self::path();
$binDir = self::path() . '/bin';
f_mkdir($buildDir, recursive: true);
f_mkdir($binDir, recursive: true);
$cmakeArgs = implode(' ', array_map('escapeshellarg', [
'-S', $llvmDir,
'-B', $buildDir,
'-DCMAKE_BUILD_TYPE=Release',
'-DLLVM_ENABLE_PROJECTS=',
'-DLLVM_TARGETS_TO_BUILD=',
'-DLLVM_INCLUDE_BENCHMARKS=OFF',
'-DLLVM_INCLUDE_TESTS=OFF',
'-DLLVM_INCLUDE_EXAMPLES=OFF',
'-DLLVM_INCLUDE_DOCS=OFF',
'-DLLVM_ENABLE_ZLIB=OFF',
'-DLLVM_ENABLE_ZSTD=OFF',
'-DLLVM_ENABLE_LIBXML2=OFF',
'-DLLVM_ENABLE_TERMINFO=OFF',
'-DLLVM_ENABLE_LIBEDIT=OFF',
'-DLLVM_ENABLE_LIBPFM=OFF',
'-DLLVM_BUILD_LLVM_DYLIB=OFF',
'-DLLVM_LINK_LLVM_DYLIB=OFF',
'-DBUILD_SHARED_LIBS=OFF',
'-DCMAKE_C_COMPILER=' . zig::binary('zig-cc'),
'-DCMAKE_CXX_COMPILER=' . zig::binary('zig-c++'),
'-DCMAKE_INSTALL_PREFIX=' . $installDir,
]));
$jobs = ApplicationContext::get(PackageBuilder::class)->concurrency;
$targetArgs = implode(' ', array_map(fn ($t) => '--target ' . escapeshellarg($t), self::TOOLS));
shell()
->setEnv(['SPC_TARGET' => GNU_ARCH . '-linux-musl'])
->exec('cmake ' . $cmakeArgs)
->exec('cmake --build ' . escapeshellarg($buildDir) . ' ' . $targetArgs . " -j {$jobs}");
foreach (self::TOOLS as $t) {
$built = "{$buildDir}/bin/{$t}";
if (!is_file($built)) {
throw new BuildFailureException("llvm-tools: missing build output {$built}");
}
copy($built, self::binary($t));
chmod(self::binary($t), 0755);
}
}
private function detectLlvmVersion(): ?string
{
if (!zig::isInstalled()) {
return null;
}
[$rc, $out] = shell()->execWithResult(escapeshellarg(zig::binary()) . ' cc --version', false);
if ($rc !== 0) {
return null;
}
return preg_match('/clang version (\d+\.\d+\.\d+)/', implode("\n", $out), $m) ? $m[1] : null;
}
}

View File

@@ -46,7 +46,7 @@ class rust
$download_url = "https://static.rust-lang.org/dist/rust-{$latest_version}-{$arch}-unknown-linux-{$distro}.tar.xz"; $download_url = "https://static.rust-lang.org/dist/rust-{$latest_version}-{$arch}-unknown-linux-{$distro}.tar.xz";
$path = DOWNLOAD_PATH . DIRECTORY_SEPARATOR . basename($download_url); $path = DOWNLOAD_PATH . DIRECTORY_SEPARATOR . basename($download_url);
default_shell()->executeCurlDownload($download_url, $path, retries: $downloader->getRetry()); default_shell()->executeCurlDownload($download_url, $path, retries: $downloader->getRetry());
return DownloadResult::archive(basename($path), ['url' => $download_url, 'version' => $latest_version], extract: PKG_ROOT_PATH . '/rust-install', verified: false, version: $latest_version); return DownloadResult::archive(basename($path), ['url' => $download_url, 'version' => $latest_version], extract: '{pkg_root_path}/rust-install', verified: false, version: $latest_version);
} }
#[CustomBinaryCheckUpdate('rust', [ #[CustomBinaryCheckUpdate('rust', [

View File

@@ -15,6 +15,23 @@ use StaticPHP\Runtime\SystemTarget;
class zig class zig
{ {
/** Directory zig extracts into. */
public static function path(): string
{
return PKG_ROOT_PATH . '/zig';
}
/** Path to a binary inside the zig install dir (zig, zig-cc, zig-c++, zig-ar, …). */
public static function binary(string $name = 'zig'): string
{
return self::path() . '/' . $name;
}
public static function isInstalled(): bool
{
return is_file(self::binary());
}
#[CustomBinary('zig', [ #[CustomBinary('zig', [
'linux-x86_64', 'linux-x86_64',
'linux-aarch64', 'linux-aarch64',

View File

@@ -0,0 +1,25 @@
<?php
declare(strict_types=1);
namespace Package\Extension;
use StaticPHP\Attribute\Package\CustomPhpConfigureArg;
use StaticPHP\Attribute\Package\Extension;
use StaticPHP\Package\PackageInstaller;
use StaticPHP\Package\PhpExtensionPackage;
#[Extension('clickhouse')]
class clickhouse extends PhpExtensionPackage
{
#[CustomPhpConfigureArg('Darwin')]
#[CustomPhpConfigureArg('Linux')]
public function getUnixConfigureArg(bool $shared, PackageInstaller $installer): string
{
$arg = '--enable-clickhouse' . ($shared ? '=shared' : '');
if ($installer->getLibraryPackage('openssl')) {
$arg .= ' --enable-clickhouse-openssl';
}
return $arg;
}
}

View File

@@ -16,7 +16,7 @@ use StaticPHP\Util\FileSystem;
class intl extends PhpExtensionPackage class intl extends PhpExtensionPackage
{ {
#[BeforeStage('php', [php::class, 'buildconfForWindows'], 'ext-intl')] #[BeforeStage('php', [php::class, 'buildconfForWindows'], 'ext-intl')]
#[PatchDescription('Fix intl config.w32: replace hardcoded true with PHP_INTL_SHARED for static build support')] #[PatchDescription('Fix intl config.w32: replace hardcoded true with PHP_INTL_SHARED for static build support; add /std:c++17 required by ICU 73+')]
public function patchBeforeBuildconfForWindows(PackageInstaller $installer): void public function patchBeforeBuildconfForWindows(PackageInstaller $installer): void
{ {
$php_src = $installer->getTargetPackage('php')->getSourceDir(); $php_src = $installer->getTargetPackage('php')->getSourceDir();
@@ -25,5 +25,11 @@ class intl extends PhpExtensionPackage
'EXTENSION("intl", "php_intl.c intl_convert.c intl_convertcpp.cpp intl_error.c ", true,', 'EXTENSION("intl", "php_intl.c intl_convert.c intl_convertcpp.cpp intl_error.c ", true,',
'EXTENSION("intl", "php_intl.c intl_convert.c intl_convertcpp.cpp intl_error.c ", PHP_INTL_SHARED,' 'EXTENSION("intl", "php_intl.c intl_convert.c intl_convertcpp.cpp intl_error.c ", PHP_INTL_SHARED,'
); );
// ICU 73+ headers (char16ptr.h etc.) unconditionally include <string_view> which requires C++17.
FileSystem::replaceFileStr(
"{$php_src}/ext/intl/config.w32",
'ADD_FLAG("CFLAGS_INTL", "/EHsc',
'ADD_FLAG("CFLAGS_INTL", "/std:c++17 /EHsc'
);
} }
} }

View File

@@ -16,6 +16,14 @@ use StaticPHP\Util\FileSystem;
#[Extension('mongodb')] #[Extension('mongodb')]
class mongodb extends PhpExtensionPackage class mongodb extends PhpExtensionPackage
{ {
#[BeforeStage('php', [php::class, 'configureForUnix'], 'ext-mongodb')]
#[PatchDescription('Export PHP_VERSION_ID so mongo-php-driver >= 2.3.3 skips its php-config lookup (in-tree builds have no php-config).')]
public function exportPhpVersionIdForUnix(): void
{
$id = php::getPHPVersionID();
f_putenv("PHP_VERSION_ID={$id}");
}
#[BeforeStage('php', [php::class, 'buildconfForWindows'], 'ext-mongodb')] #[BeforeStage('php', [php::class, 'buildconfForWindows'], 'ext-mongodb')]
#[PatchDescription('Add /utf-8 flag to CFLAGS_MONGODB for Windows build to fix compilation error on non-English Windows.')] #[PatchDescription('Add /utf-8 flag to CFLAGS_MONGODB for Windows build to fix compilation error on non-English Windows.')]
public function patchBeforeBuild(): void public function patchBeforeBuild(): void

View File

@@ -72,6 +72,10 @@ class opcache extends PhpExtensionPackage
) { ) {
$opcache_jit = ' --disable-opcache-jit'; $opcache_jit = ' --disable-opcache-jit';
} }
return '--enable-opcache' . ($shared ? '=shared' : '') . $opcache_jit; // PHP 8.5+ has opcache built-in
if ($phpVersionID < 80500) {
return '--enable-opcache' . ($shared ? '=shared' : '') . $opcache_jit;
}
return trim($opcache_jit);
} }
} }

View File

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

@@ -27,7 +27,7 @@ class password_argon2 extends PhpExtensionPackage
#[CustomPhpConfigureArg('Darwin')] #[CustomPhpConfigureArg('Darwin')]
public function getConfigureArg(PackageInstaller $installer, PackageBuilder $builder): string public function getConfigureArg(PackageInstaller $installer, PackageBuilder $builder): string
{ {
if ($installer->getLibraryPackage('openssl') !== null) { if ($installer->getPhpExtensionPackage('openssl')?->isBuildStatic()) {
if (php::getPHPVersionID() >= 80500 || (php::getPHPVersionID() >= 80400 && !$builder->getOption('enable-zts'))) { if (php::getPHPVersionID() >= 80500 || (php::getPHPVersionID() >= 80400 && !$builder->getOption('enable-zts'))) {
return '--without-password-argon2'; // use --with-openssl-argon2 in openssl extension instead return '--without-password-argon2'; // use --with-openssl-argon2 in openssl extension instead
} }

View File

@@ -20,7 +20,7 @@ class pgsql extends PhpExtensionPackage
public function getUnixConfigureArg(bool $shared, PackageBuilder $builder, PackageInstaller $installer): string public function getUnixConfigureArg(bool $shared, PackageBuilder $builder, PackageInstaller $installer): string
{ {
if (php::getPHPVersionID() >= 80400) { if (php::getPHPVersionID() >= 80400) {
$libfiles = new SPCConfigUtil(['libs_only_deps' => true, 'absolute_libs' => true])->getPackageDepsConfig('postgresql', array_keys($installer->getResolvedPackages()), $builder->getOption('with-suggests'))['libs']; $libfiles = new SPCConfigUtil(['libs_only_deps' => true, 'absolute_libs' => true])->getPackageDepsConfig('postgresql', array_keys($installer->getResolvedPackages()))['libs'];
$libfiles = str_replace("{$builder->getLibDir()}/lib", '-l', $libfiles); $libfiles = str_replace("{$builder->getLibDir()}/lib", '-l', $libfiles);
$libfiles = str_replace('.a', '', $libfiles); $libfiles = str_replace('.a', '', $libfiles);
return '--with-pgsql' . ($shared ? '=shared' : '') . return '--with-pgsql' . ($shared ? '=shared' : '') .

View File

@@ -6,14 +6,27 @@ namespace Package\Extension;
use Package\Target\php; use Package\Target\php;
use StaticPHP\Attribute\Package\BeforeStage; use StaticPHP\Attribute\Package\BeforeStage;
use StaticPHP\Attribute\Package\CustomPhpConfigureArg;
use StaticPHP\Attribute\Package\Extension; use StaticPHP\Attribute\Package\Extension;
use StaticPHP\Attribute\PatchDescription; use StaticPHP\Attribute\PatchDescription;
use StaticPHP\Package\PackageInstaller;
use StaticPHP\Package\PhpExtensionPackage; use StaticPHP\Package\PhpExtensionPackage;
use StaticPHP\Util\FileSystem; use StaticPHP\Util\FileSystem;
#[Extension('spx')] #[Extension('spx')]
class spx extends PhpExtensionPackage class spx extends PhpExtensionPackage
{ {
#[CustomPhpConfigureArg('Linux')]
#[CustomPhpConfigureArg('Darwin')]
public function getUnixConfigureArg(bool $shared, PackageInstaller $installer): string
{
$arg = '--enable-SPX' . ($shared ? '=shared' : '');
if ($installer->getLibraryPackage('zlib') !== null) {
$arg .= ' --with-zlib-dir=' . BUILD_ROOT_PATH;
}
return $arg;
}
#[BeforeStage('php', [php::class, 'buildconfForUnix'], 'ext-spx')] #[BeforeStage('php', [php::class, 'buildconfForUnix'], 'ext-spx')]
#[PatchDescription('Fix spx extension compile error when building as static')] #[PatchDescription('Fix spx extension compile error when building as static')]
public function patchBeforeBuildconf(): bool public function patchBeforeBuildconf(): bool

View File

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

View File

@@ -11,7 +11,6 @@ use StaticPHP\Attribute\Package\Extension;
use StaticPHP\Attribute\PatchDescription; use StaticPHP\Attribute\PatchDescription;
use StaticPHP\Package\PackageInstaller; use StaticPHP\Package\PackageInstaller;
use StaticPHP\Package\PhpExtensionPackage; use StaticPHP\Package\PhpExtensionPackage;
use StaticPHP\Util\GlobalEnvManager;
use StaticPHP\Util\SourcePatcher; use StaticPHP\Util\SourcePatcher;
#[Extension('xlswriter')] #[Extension('xlswriter')]
@@ -21,20 +20,14 @@ class xlswriter extends PhpExtensionPackage
#[CustomPhpConfigureArg('Linux')] #[CustomPhpConfigureArg('Linux')]
public function getUnixConfigureArg(bool $shared, PackageInstaller $installer): string public function getUnixConfigureArg(bool $shared, PackageInstaller $installer): string
{ {
$arg = '--with-xlswriter --enable-reader'; $shared = $shared ? '=shared' : '';
$arg = "--with-xlswriter{$shared} --enable-reader";
if ($installer->getLibraryPackage('openssl')) { if ($installer->getLibraryPackage('openssl')) {
$arg .= ' --with-openssl=' . $installer->getLibraryPackage('openssl')->getBuildRootPath(); $arg .= ' --with-openssl=' . $installer->getLibraryPackage('openssl')->getBuildRootPath();
} }
return $arg; return $arg;
} }
#[BeforeStage('php', [php::class, 'makeForUnix'], 'ext-xlswriter')]
#[PatchDescription('Fix Unix build: add -std=gnu17 to CFLAGS to fix build errors on older GCC versions')]
public function patchBeforeUnixMake(): void
{
GlobalEnvManager::putenv('SPC_CMD_VAR_PHP_MAKE_EXTRA_CFLAGS=' . getenv('SPC_CMD_VAR_PHP_MAKE_EXTRA_CFLAGS') . ' -std=gnu17');
}
#[BeforeStage('php', [php::class, 'makeForWindows'], 'ext-xlswriter')] #[BeforeStage('php', [php::class, 'makeForWindows'], 'ext-xlswriter')]
#[PatchDescription('Fix Windows build: apply win32 patch and add UTF-8 BOM to theme.c')] #[PatchDescription('Fix Windows build: apply win32 patch and add UTF-8 BOM to theme.c')]
public function patchBeforeMakeForWindows(): void public function patchBeforeMakeForWindows(): void
@@ -47,11 +40,4 @@ class xlswriter extends PhpExtensionPackage
file_put_contents($this->getSourceDir() . '/library/libxlsxwriter/src/theme.c', $bom . $content); file_put_contents($this->getSourceDir() . '/library/libxlsxwriter/src/theme.c', $bom . $content);
} }
} }
public function getSharedExtensionEnv(): array
{
$parent = parent::getSharedExtensionEnv();
$parent['CFLAGS'] .= ' -std=gnu17';
return $parent;
}
} }

View File

@@ -42,6 +42,9 @@ class imagemagick
->addConfigureArgs( ->addConfigureArgs(
'--disable-openmp', '--disable-openmp',
'--without-x', '--without-x',
// implicit --with-gcc-arch
// bleeds host cpu features into built binaries
'--without-gcc-arch',
); );
// special: linux-static target needs `-static` // special: linux-static target needs `-static`

View File

@@ -20,9 +20,8 @@ class watcher extends LibraryPackage
if (stripos($cflags, '-fpic') === false) { if (stripos($cflags, '-fpic') === false) {
$cflags .= ' -fPIC'; $cflags .= ' -fPIC';
} }
$ldflags = $this->getLibExtraLdFlags() ? ' ' . $this->getLibExtraLdFlags() : '';
shell()->cd("{$this->getSourceDir()}/watcher-c") shell()->cd("{$this->getSourceDir()}/watcher-c")
->exec(getenv('CXX') . " -c -o libwatcher-c.o ./src/watcher-c.cpp -I ./include -I ../include -std=c++17 -Wall -Wextra {$cflags}{$ldflags}") ->exec(getenv('CXX') . " -c -o libwatcher-c.o ./src/watcher-c.cpp -I ./include -I ../include -std=c++17 -Wall -Wextra {$cflags}")
->exec(getenv('AR') . ' rcs libwatcher-c.a libwatcher-c.o'); ->exec(getenv('AR') . ' rcs libwatcher-c.a libwatcher-c.o');
copy("{$this->getSourceDir()}/watcher-c/libwatcher-c.a", "{$this->getLibDir()}/libwatcher-c.a"); copy("{$this->getSourceDir()}/watcher-c/libwatcher-c.a", "{$this->getLibDir()}/libwatcher-c.a");

View File

@@ -39,7 +39,7 @@ class curl
->optionalPackage('zstd', ...cmake_boolean_args('CURL_ZSTD')) ->optionalPackage('zstd', ...cmake_boolean_args('CURL_ZSTD'))
->optionalPackage('brotli', ...cmake_boolean_args('CURL_BROTLI')) ->optionalPackage('brotli', ...cmake_boolean_args('CURL_BROTLI'))
->addConfigureArgs( ->addConfigureArgs(
'-DBUILD_CURL_EXE=OFF', '-DBUILD_CURL_EXE=ON',
'-DZSTD_LIBRARY=zstd_static.lib', '-DZSTD_LIBRARY=zstd_static.lib',
'-DBUILD_TESTING=OFF', '-DBUILD_TESTING=OFF',
'-DBUILD_EXAMPLES=OFF', '-DBUILD_EXAMPLES=OFF',
@@ -81,6 +81,7 @@ class curl
->addConfigureArgs( ->addConfigureArgs(
'-DBUILD_CURL_EXE=ON', '-DBUILD_CURL_EXE=ON',
'-DBUILD_LIBCURL_DOCS=OFF', '-DBUILD_LIBCURL_DOCS=OFF',
'-DOPENSSL_ROOT_DIR=' . BUILD_ROOT_PATH,
) )
->build(); ->build();
@@ -92,6 +93,9 @@ class curl
if (str_contains(FileSystem::readFile($pc_path), '-lgssapi_krb5')) { if (str_contains(FileSystem::readFile($pc_path), '-lgssapi_krb5')) {
FileSystem::replaceFileRegex($pc_path, '/-lcom_err$/m', '-lcom_err -lkrb5support'); FileSystem::replaceFileRegex($pc_path, '/-lcom_err$/m', '-lcom_err -lkrb5support');
} }
// FindThreads can put '-lpthread' into INTERFACE_LINK_LIBRARIES; curl's pc generator
// prepends '-l' to each entry, producing '-l-lpthread'. Strip the extra '-l'.
FileSystem::replaceFileRegex($pc_path, '/-l(-l\S+)/', '$1');
shell()->cd("{$lib->getLibDir()}/cmake/CURL/") shell()->cd("{$lib->getLibDir()}/cmake/CURL/")
->exec("sed -ie 's|\"/lib/libcurl.a\"|\"{$lib->getLibDir()}/libcurl.a\"|g' CURLTargets-release.cmake"); ->exec("sed -ie 's|\"/lib/libcurl.a\"|\"{$lib->getLibDir()}/libcurl.a\"|g' CURLTargets-release.cmake");

View File

@@ -20,8 +20,10 @@ use StaticPHP\Package\PhpExtensionPackage;
use StaticPHP\Package\TargetPackage; use StaticPHP\Package\TargetPackage;
use StaticPHP\Runtime\SystemTarget; use StaticPHP\Runtime\SystemTarget;
use StaticPHP\Toolchain\Interface\ToolchainInterface; use StaticPHP\Toolchain\Interface\ToolchainInterface;
use StaticPHP\Toolchain\ZigToolchain;
use StaticPHP\Util\DirDiff; use StaticPHP\Util\DirDiff;
use StaticPHP\Util\FileSystem; use StaticPHP\Util\FileSystem;
use StaticPHP\Util\GlobalEnvManager;
use StaticPHP\Util\InteractiveTerm; use StaticPHP\Util\InteractiveTerm;
use StaticPHP\Util\SourcePatcher; use StaticPHP\Util\SourcePatcher;
use StaticPHP\Util\SPCConfigUtil; use StaticPHP\Util\SPCConfigUtil;
@@ -93,7 +95,8 @@ trait unix
// disable undefined behavior sanitizer when opcache JIT is enabled (Linux only) // disable undefined behavior sanitizer when opcache JIT is enabled (Linux only)
if (SystemTarget::getTargetOS() === 'Linux' && !$package->getBuildOption('disable-opcache-jit', false)) { if (SystemTarget::getTargetOS() === 'Linux' && !$package->getBuildOption('disable-opcache-jit', false)) {
if ($version_id >= 80500 || $installer->isPackageResolved('ext-opcache')) { 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 // PHP JSON extension is built-in since PHP 8.0
@@ -165,14 +168,20 @@ trait unix
#[BeforeStage('php', [self::class, 'makeForUnix'], 'php')] #[BeforeStage('php', [self::class, 'makeForUnix'], 'php')]
#[PatchDescription('Patch Makefile to fix //lib path for Linux builds')] #[PatchDescription('Patch Makefile to fix //lib path for Linux builds')]
public function tryPatchMakefileUnix(): void #[PatchDescription('Patch BUILD_CC to use system cc instead of zig-cc (prevents minilua crash)')]
public function tryPatchMakefileUnix(TargetPackage $package, ToolchainInterface $toolchain): void
{ {
if (SystemTarget::getTargetOS() !== 'Linux') { if (SystemTarget::getTargetOS() !== 'Linux') {
return; return;
} }
// replace //lib with /lib in Makefile // replace //lib with /lib in Makefile
shell()->cd(SOURCE_PATH . '/php-src')->exec('sed -i "s|//lib|/lib|g" Makefile'); shell()->cd($package->getSourceDir())->exec('sed -i "s|//lib|/lib|g" Makefile');
if ($toolchain instanceof ZigToolchain) {
$makefile = "{$package->getSourceDir()}/Makefile";
FileSystem::replaceFileRegex($makefile, '/^BUILD_CC\s*=\s*zig-cc\s*$/m', 'BUILD_CC = cc');
}
} }
#[BeforeStage('php', [self::class, 'makeForUnix'], 'php')] #[BeforeStage('php', [self::class, 'makeForUnix'], 'php')]
@@ -266,43 +275,32 @@ trait unix
#[PatchDescription('Patch phar extension for micro SAPI to support compressed phar')] #[PatchDescription('Patch phar extension for micro SAPI to support compressed phar')]
public function makeMicroForUnix(TargetPackage $package, PackageInstaller $installer, PackageBuilder $builder): void public function makeMicroForUnix(TargetPackage $package, PackageInstaller $installer, PackageBuilder $builder): void
{ {
$phar_patched = false; InteractiveTerm::setMessage('Building php: ' . ConsoleColor::yellow('make micro'));
try { // apply --with-micro-fake-cli option
if ($installer->isPackageResolved('ext-phar')) { $vars = $this->makeVars($installer);
$phar_patched = true; $vars['EXTRA_CFLAGS'] .= $package->getBuildOption('with-micro-fake-cli', false) ? ' -DPHP_MICRO_FAKE_CLI' : '';
SourcePatcher::patchMicroPhar(self::getPHPVersionID()); $makeArgs = $this->makeVarsToArgs($vars);
} // build
InteractiveTerm::setMessage('Building php: ' . ConsoleColor::yellow('make micro')); shell()->cd($package->getSourceDir())
// apply --with-micro-fake-cli option ->setEnv($vars)
$vars = $this->makeVars($installer); ->exec("make -j{$builder->concurrency} {$makeArgs} micro");
$vars['EXTRA_CFLAGS'] .= $package->getBuildOption('with-micro-fake-cli', false) ? ' -DPHP_MICRO_FAKE_CLI' : '';
$makeArgs = $this->makeVarsToArgs($vars);
// build
shell()->cd($package->getSourceDir())
->setEnv($vars)
->exec("make -j{$builder->concurrency} {$makeArgs} micro");
$dst = BUILD_BIN_PATH . '/micro.sfx'; $dst = BUILD_BIN_PATH . '/micro.sfx';
$builder->deployBinary($package->getSourceDir() . '/sapi/micro/micro.sfx', $dst); $builder->deployBinary($package->getSourceDir() . '/sapi/micro/micro.sfx', $dst);
// patch after UPX-ed micro.sfx (Linux only) // patch after UPX-ed micro.sfx (Linux only)
if (SystemTarget::getTargetOS() === 'Linux' && $builder->getOption('with-upx-pack')) { if (SystemTarget::getTargetOS() === 'Linux' && $builder->getOption('with-upx-pack')) {
// cut binary with readelf to remove UPX extra segment // cut binary with readelf to remove UPX extra segment
[$ret, $out] = shell()->execWithResult("readelf -l {$dst} | awk '/LOAD|GNU_STACK/ {getline; print \\$1, \\$2, \\$3, \\$4, \\$6, \\$7}'"); [$ret, $out] = shell()->execWithResult("readelf -l {$dst} | awk '/LOAD|GNU_STACK/ {getline; print \\$1, \\$2, \\$3, \\$4, \\$6, \\$7}'");
$out[1] = explode(' ', $out[1]); $out[1] = explode(' ', $out[1]);
$offset = $out[1][0]; $offset = $out[1][0];
if ($ret !== 0 || !str_starts_with($offset, '0x')) { if ($ret !== 0 || !str_starts_with($offset, '0x')) {
throw new PatchException('phpmicro UPX patcher', 'Cannot find offset in readelf output'); throw new PatchException('phpmicro UPX patcher', 'Cannot find offset in readelf output');
}
$offset = hexdec($offset);
// remove upx extra wastes
file_put_contents($dst, substr(file_get_contents($dst), 0, $offset));
}
$package->setOutput('Binary path for micro SAPI', $dst);
} finally {
if ($phar_patched) {
SourcePatcher::unpatchMicroPhar();
} }
$offset = hexdec($offset);
// remove upx extra wastes
file_put_contents($dst, substr(file_get_contents($dst), 0, $offset));
} }
$package->setOutput('Binary path for micro SAPI', $dst);
} }
#[Stage] #[Stage]
@@ -354,14 +352,13 @@ trait unix
// ------------- SPC_CMD_VAR_PHP_EMBED_TYPE=static ------------- // ------------- SPC_CMD_VAR_PHP_EMBED_TYPE=static -------------
// process libphp.a for static embed // process libphp.a for static embed (only when present)
if (!file_exists("{$package->getLibDir()}/libphp.a")) { if (file_exists("{$package->getLibDir()}/libphp.a")) {
return; $ar = getenv('AR') ?: 'ar';
$libphp_a = "{$package->getLibDir()}/libphp.a";
shell()->exec("{$ar} -t {$libphp_a} | grep '\\.a$' | xargs -n1 {$ar} d {$libphp_a}");
UnixUtil::exportDynamicSymbols($libphp_a);
} }
$ar = getenv('AR') ?: 'ar';
$libphp_a = "{$package->getLibDir()}/libphp.a";
shell()->exec("{$ar} -t {$libphp_a} | grep '\\.a$' | xargs -n1 {$ar} d {$libphp_a}");
UnixUtil::exportDynamicSymbols($libphp_a);
// deploy embed php scripts // deploy embed php scripts
$package->runStage([$this, 'patchUnixEmbedScripts']); $package->runStage([$this, 'patchUnixEmbedScripts']);
@@ -510,7 +507,8 @@ trait unix
if (file_exists(BUILD_BIN_PATH . '/php-config')) { if (file_exists(BUILD_BIN_PATH . '/php-config')) {
logger()->debug('Patching php-config prefix and libs order'); logger()->debug('Patching php-config prefix and libs order');
$php_config_str = FileSystem::readFile(BUILD_BIN_PATH . '/php-config'); $php_config_str = FileSystem::readFile(BUILD_BIN_PATH . '/php-config');
$php_config_str = str_replace('prefix=""', 'prefix="' . BUILD_ROOT_PATH . '"', $php_config_str); // anchor to start-of-line so we don't also match `program_prefix=""`
$php_config_str = preg_replace('/^prefix=""/m', 'prefix="' . BUILD_ROOT_PATH . '"', $php_config_str);
// move mimalloc to the beginning of libs // move mimalloc to the beginning of libs
$php_config_str = preg_replace('/(libs=")(.*?)\s*(' . preg_quote(BUILD_LIB_PATH, '/') . '\/mimalloc\.o)\s*(.*?)"/', '$1$3 $2 $4"', $php_config_str); $php_config_str = preg_replace('/(libs=")(.*?)\s*(' . preg_quote(BUILD_LIB_PATH, '/') . '\/mimalloc\.o)\s*(.*?)"/', '$1$3 $2 $4"', $php_config_str);
// move lstdc++ to the end of libs // move lstdc++ to the end of libs

View File

@@ -293,21 +293,8 @@ trait windows
$fake_cli = $package->getBuildOption('with-micro-fake-cli', false) ? ' /DPHP_MICRO_FAKE_CLI' : ''; $fake_cli = $package->getBuildOption('with-micro-fake-cli', false) ? ' /DPHP_MICRO_FAKE_CLI' : '';
// phar patch for micro cmd()->cd($package->getSourceDir())
$phar_patched = false; ->exec("nmake /nologo {$debug_overrides}LIBS_MICRO=\"ws2_32.lib shell32.lib {$extra_libs}\" CFLAGS_MICRO=\"/DZEND_ENABLE_STATIC_TSRMLS_CACHE=1{$fake_cli}\" EXTRA_LD_FLAGS_PROGRAM= micro");
if ($installer->isPackageResolved('ext-phar')) {
$phar_patched = true;
SourcePatcher::patchMicroPhar(self::getPHPVersionID());
}
try {
cmd()->cd($package->getSourceDir())
->exec("nmake /nologo {$debug_overrides}LIBS_MICRO=\"ws2_32.lib shell32.lib {$extra_libs}\" CFLAGS_MICRO=\"/DZEND_ENABLE_STATIC_TSRMLS_CACHE=1{$fake_cli}\" EXTRA_LD_FLAGS_PROGRAM= micro");
} finally {
if ($phar_patched) {
SourcePatcher::unpatchMicroPhar();
}
}
$this->deployWindowsBinary($builder, $package, 'php-micro'); $this->deployWindowsBinary($builder, $package, 'php-micro');
} }

View File

@@ -327,7 +327,7 @@ class Artifact
public function getSourceRoot(): string public function getSourceRoot(): string
{ {
if (isset($this->config['metadata']['source-root'])) { if (isset($this->config['metadata']['source-root'])) {
return $this->getSourceDir() . '/' . ltrim($this->config['metadata']['source-root'], '/'); return FileSystem::convertPath($this->getSourceDir() . '/' . ltrim($this->config['metadata']['source-root'], '/'));
} }
return $this->getSourceDir(); return $this->getSourceDir();
} }

View File

@@ -223,8 +223,8 @@ class ArtifactCache
public function getCacheFullPath(array $cache_info): string public function getCacheFullPath(array $cache_info): string
{ {
return match ($cache_info['cache_type']) { return match ($cache_info['cache_type']) {
'archive', 'file' => DOWNLOAD_PATH . '/' . $cache_info['filename'], 'archive', 'file' => FileSystem::convertPath(DOWNLOAD_PATH . '/' . $cache_info['filename']),
'git' => DOWNLOAD_PATH . '/' . $cache_info['dirname'], 'git' => FileSystem::convertPath(DOWNLOAD_PATH . '/' . $cache_info['dirname']),
'local' => $cache_info['dirname'], // local dirname is absolute path 'local' => $cache_info['dirname'], // local dirname is absolute path
default => throw new SPCInternalException("Unknown cache type: {$cache_info['cache_type']}"), default => throw new SPCInternalException("Unknown cache type: {$cache_info['cache_type']}"),
}; };

View File

@@ -242,7 +242,10 @@ class ArtifactExtractor
} }
logger()->info("Extracting binary [{$name}] to {$target_path}..."); logger()->info("Extracting binary [{$name}] to {$target_path}...");
$this->doStandardExtract($name, $cache_info, $target_path); // When a binary artifact targets the shared buildroot, merge into it instead of wiping it.
// Wiping buildroot would destroy files installed by packages processed earlier in the build queue.
$merge = (FileSystem::convertPath($target_path) === FileSystem::convertPath(BUILD_ROOT_PATH));
$this->doStandardExtract($name, $cache_info, $target_path, $merge);
$artifact->emitAfterBinaryExtract($target_path, $platform); $artifact->emitAfterBinaryExtract($target_path, $platform);
logger()->debug("Emitted after-binary-extract hooks for [{$name}]"); logger()->debug("Emitted after-binary-extract hooks for [{$name}]");
@@ -256,8 +259,10 @@ class ArtifactExtractor
/** /**
* Standard extraction: extract entire archive to target directory. * Standard extraction: extract entire archive to target directory.
*
* @param bool $merge when true, merge extracted files into existing target dir instead of wiping it
*/ */
protected function doStandardExtract(string $name, array $cache_info, string $target_path): void protected function doStandardExtract(string $name, array $cache_info, string $target_path, bool $merge = false): void
{ {
$source_file = $this->cache->getCacheFullPath($cache_info); $source_file = $this->cache->getCacheFullPath($cache_info);
$cache_type = $cache_info['cache_type']; $cache_type = $cache_info['cache_type'];
@@ -265,7 +270,7 @@ class ArtifactExtractor
// Validate source file exists before extraction // Validate source file exists before extraction
$this->validateSourceFile($name, $source_file, $cache_type); $this->validateSourceFile($name, $source_file, $cache_type);
$this->extractWithType($cache_type, $source_file, $target_path); $this->extractWithType($cache_type, $source_file, $target_path, $merge);
} }
/** /**
@@ -443,10 +448,10 @@ class ArtifactExtractor
* @param string $source_file Path to source file or directory * @param string $source_file Path to source file or directory
* @param string $target_path Target extraction path * @param string $target_path Target extraction path
*/ */
protected function extractWithType(string $cache_type, string $source_file, string $target_path): void protected function extractWithType(string $cache_type, string $source_file, string $target_path, bool $merge = false): void
{ {
match ($cache_type) { match ($cache_type) {
'archive' => $this->extractArchive($source_file, $target_path), 'archive' => $this->extractArchive($source_file, $target_path, $merge),
'file' => $this->copyFile($source_file, $target_path), 'file' => $this->copyFile($source_file, $target_path),
'git' => FileSystem::copyDir(FileSystem::convertPath($source_file), $target_path), 'git' => FileSystem::copyDir(FileSystem::convertPath($source_file), $target_path),
'local' => symlink(FileSystem::convertPath($source_file), $target_path), 'local' => symlink(FileSystem::convertPath($source_file), $target_path),
@@ -458,8 +463,10 @@ class ArtifactExtractor
* Extract archive file to target directory. * Extract archive file to target directory.
* *
* Supports: tar, tar.gz, tgz, tar.bz2, tar.xz, txz, zip, exe * Supports: tar, tar.gz, tgz, tar.bz2, tar.xz, txz, zip, exe
*
* @param bool $merge when true, merge zip contents into existing target dir instead of wiping it
*/ */
protected function extractArchive(string $filename, string $target): void protected function extractArchive(string $filename, string $target, bool $merge = false): void
{ {
$target = FileSystem::convertPath($target); $target = FileSystem::convertPath($target);
$filename = FileSystem::convertPath($filename); $filename = FileSystem::convertPath($filename);
@@ -476,7 +483,7 @@ class ArtifactExtractor
'Windows' => match ($extname) { 'Windows' => match ($extname) {
'tar' => default_shell()->executeTarExtract($filename, $target, 'none'), 'tar' => default_shell()->executeTarExtract($filename, $target, 'none'),
'xz', 'txz', 'gz', 'tgz', 'bz2' => default_shell()->execute7zExtract($filename, $target), 'xz', 'txz', 'gz', 'tgz', 'bz2' => default_shell()->execute7zExtract($filename, $target),
'zip' => $this->unzipWithStrip($filename, $target), 'zip' => $this->unzipWithStrip($filename, $target, $merge),
'exe' => $this->copyFile($filename, $target), 'exe' => $this->copyFile($filename, $target),
default => throw new FileSystemException("Unknown archive format: {$filename}"), default => throw new FileSystemException("Unknown archive format: {$filename}"),
}, },
@@ -485,7 +492,7 @@ class ArtifactExtractor
'gz', 'tgz' => default_shell()->executeTarExtract($filename, $target, 'gz'), 'gz', 'tgz' => default_shell()->executeTarExtract($filename, $target, 'gz'),
'bz2' => default_shell()->executeTarExtract($filename, $target, 'bz2'), 'bz2' => default_shell()->executeTarExtract($filename, $target, 'bz2'),
'xz', 'txz' => default_shell()->executeTarExtract($filename, $target, 'xz'), 'xz', 'txz' => default_shell()->executeTarExtract($filename, $target, 'xz'),
'zip' => $this->unzipWithStrip($filename, $target), 'zip' => $this->unzipWithStrip($filename, $target, $merge),
'exe' => $this->copyFile($filename, $target), 'exe' => $this->copyFile($filename, $target),
default => throw new FileSystemException("Unknown archive format: {$filename}"), default => throw new FileSystemException("Unknown archive format: {$filename}"),
}, },
@@ -496,7 +503,7 @@ class ArtifactExtractor
/** /**
* Unzip file with stripping top-level directory. * Unzip file with stripping top-level directory.
*/ */
protected function unzipWithStrip(string $zip_file, string $extract_path): bool protected function unzipWithStrip(string $zip_file, string $extract_path, bool $merge = false): bool
{ {
$temp_dir = FileSystem::convertPath(sys_get_temp_dir() . '/spc_unzip_' . bin2hex(random_bytes(16))); $temp_dir = FileSystem::convertPath(sys_get_temp_dir() . '/spc_unzip_' . bin2hex(random_bytes(16)));
$zip_file = FileSystem::convertPath($zip_file); $zip_file = FileSystem::convertPath($zip_file);
@@ -517,15 +524,22 @@ class ArtifactExtractor
throw new FileSystemException('Cannot scan unzip temp dir: ' . $temp_dir); throw new FileSystemException('Cannot scan unzip temp dir: ' . $temp_dir);
} }
// If extract path already exists, remove it if (!$merge) {
if (is_dir($extract_path)) { // Replace mode: wipe the target directory before extracting
FileSystem::removeDir($extract_path); if (is_dir($extract_path)) {
FileSystem::removeDir($extract_path);
}
} }
// If only one dir, move its contents to extract_path // If only one dir, move/merge its contents to extract_path
$subdir = FileSystem::convertPath("{$temp_dir}/{$contents[0]}"); $subdir = FileSystem::convertPath("{$temp_dir}/{$contents[0]}");
if (count($contents) === 1 && is_dir($subdir)) { if (count($contents) === 1 && is_dir($subdir)) {
$this->moveFileOrDir($subdir, $extract_path); if ($merge) {
$this->mergeDirContent($subdir, $extract_path);
FileSystem::removeDir($subdir);
} else {
$this->moveFileOrDir($subdir, $extract_path);
}
} else { } else {
// Else, if it contains only one dir, strip dir and copy other files // Else, if it contains only one dir, strip dir and copy other files
$dircount = 0; $dircount = 0;
@@ -550,26 +564,36 @@ class ArtifactExtractor
throw new FileSystemException("Cannot scan unzip temp sub-dir: {$dir[0]}"); throw new FileSystemException("Cannot scan unzip temp sub-dir: {$dir[0]}");
} }
foreach ($sub_contents as $sub_item) { foreach ($sub_contents as $sub_item) {
$this->moveFileOrDir( $src = FileSystem::convertPath("{$temp_dir}/{$dir[0]}/{$sub_item}");
FileSystem::convertPath("{$temp_dir}/{$dir[0]}/{$sub_item}"), $dst = FileSystem::convertPath("{$extract_path}/{$sub_item}");
FileSystem::convertPath("{$extract_path}/{$sub_item}") if ($merge && is_dir($src)) {
); $this->mergeDirContent($src, $dst);
} else {
$this->moveFileOrDir($src, $dst);
}
} }
} else { } else {
foreach ($dir as $item) { foreach ($dir as $item) {
$this->moveFileOrDir( $src = FileSystem::convertPath("{$temp_dir}/{$item}");
FileSystem::convertPath("{$temp_dir}/{$item}"), $dst = FileSystem::convertPath("{$extract_path}/{$item}");
FileSystem::convertPath("{$extract_path}/{$item}") if ($merge) {
); $this->mergeDirContent($src, $dst);
} else {
$this->moveFileOrDir($src, $dst);
}
} }
} }
// Move top-level files to extract_path // Move or copy top-level files to extract_path
foreach ($top_files as $top_file) { foreach ($top_files as $top_file) {
$this->moveFileOrDir( $src = FileSystem::convertPath("{$temp_dir}/{$top_file}");
FileSystem::convertPath("{$temp_dir}/{$top_file}"), $dst = FileSystem::convertPath("{$extract_path}/{$top_file}");
FileSystem::convertPath("{$extract_path}/{$top_file}") if ($merge) {
); FileSystem::createDir(dirname($dst));
copy($src, $dst);
} else {
$this->moveFileOrDir($src, $dst);
}
} }
} }
@@ -595,6 +619,25 @@ class ArtifactExtractor
return str_replace(array_keys($replacement), array_values($replacement), $path); return str_replace(array_keys($replacement), array_values($replacement), $path);
} }
private function mergeDirContent(string $src_dir, string $dest_dir): void
{
FileSystem::createDir($dest_dir);
$items = FileSystem::scanDirFiles($src_dir, false, true, true);
if ($items === false || empty($items)) {
return;
}
foreach ($items as $item) {
$src_item = FileSystem::convertPath("{$src_dir}/{$item}");
$dest_item = FileSystem::convertPath("{$dest_dir}/{$item}");
if (is_dir($src_item)) {
$this->mergeDirContent($src_item, $dest_item);
} else {
FileSystem::createDir(dirname($dest_item));
copy($src_item, $dest_item);
}
}
}
/** /**
* Move file or directory, handling cross-device scenarios * Move file or directory, handling cross-device scenarios
* Uses rename() if possible, falls back to copy+delete for cross-device moves * Uses rename() if possible, falls back to copy+delete for cross-device moves

View File

@@ -20,7 +20,7 @@ class Git implements DownloadTypeInterface, CheckUpdateInterface
// direct branch clone // direct branch clone
if (isset($config['rev'])) { 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); $shell = PHP_OS_FAMILY === 'Windows' ? cmd(false) : shell(false);
$hash_result = $shell->execWithResult(SPC_GIT_EXEC . ' -C ' . escapeshellarg($path) . ' rev-parse --short HEAD'); $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]) : ''; $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); $version = array_key_first($matched_version_branch);
$branch = $matched_version_branch[$version]; $branch = $matched_version_branch[$version];
logger()->info("Matched version {$version} from branch {$branch} for {$name}"); 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); 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)."); 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; 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}"); logger()->debug("Fetching {$name} GitHub releases from {$repo}");
$url = str_replace('{repo}', $repo, self::API_URL); $url = str_replace('{repo}', $repo, self::API_URL);
$url .= ($query ?? ''); $url .= ($query ?? '');
$headers = $this->getGitHubTokenHeaders(); $headers = $this->getGitHubTokenHeaders();
$data2 = default_shell()->executeCurl($url, headers: $headers); $data2 = default_shell()->executeCurl($url, headers: $headers, retries: $retries);
$data = json_decode($data2 ?: '', true); $data = json_decode($data2 ?: '', true);
if (!is_array($data)) { if (!is_array($data)) {
throw new DownloaderException("Failed to get GitHub release API info for {$repo} from {$url}"); 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. * Get the latest GitHub release assets for a given repository.
* match_asset is provided, only return the asset that matches the regex. * 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}"); logger()->debug("Fetching {$name} GitHub release from {$repo}");
$url = str_replace('{repo}', $repo, self::API_URL); $url = str_replace('{repo}', $repo, self::API_URL);
$url .= ($query ?? ''); $url .= ($query ?? '');
$headers = $this->getGitHubTokenHeaders(); $headers = $this->getGitHubTokenHeaders();
$data2 = default_shell()->executeCurl($url, headers: $headers); $data2 = default_shell()->executeCurl($url, headers: $headers, retries: $retries);
$data = json_decode($data2 ?: '', true); $data = json_decode($data2 ?: '', true);
if (!is_array($data)) { if (!is_array($data)) {
throw new DownloaderException("Failed to get GitHub release API info for {$repo} from {$url}"); 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'])) { if (!isset($config['match'])) {
throw new DownloaderException("GitHubRelease downloader requires 'match' config for {$name}"); 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 // download file using curl
$asset_url = str_replace(['{repo}', '{id}'], [$config['repo'], $rel['id']], self::ASSET_URL); $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'])) { if (!isset($config['match'])) {
throw new DownloaderException("GitHubRelease downloader requires 'match' config for {$name}"); 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 ?? ''; $new_version = $this->version ?? $old_version ?? '';
return new CheckUpdateResult( return new CheckUpdateResult(
old: $old_version, 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. * 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. * 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) { if ($rel_type === 'releases' && $match_url === null && $query === null && $prefer_stable) {
$api_url = str_replace(['{repo}', '{rel_type}'], [$repo, 'releases/latest'], self::API_URL); $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); $data = json_decode($data ?: '', true);
if (!is_array($data) || empty($data['tarball_url'])) { if (!is_array($data) || empty($data['tarball_url'])) {
throw new DownloaderException("Failed to get GitHub latest release for {$repo} from {$api_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 { } else {
$api_url = str_replace(['{repo}', '{rel_type}'], [$repo, $rel_type], self::API_URL); $api_url = str_replace(['{repo}', '{rel_type}'], [$repo, $rel_type], self::API_URL);
$api_url .= ($query ?? ''); $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); $data = json_decode($data ?: '', true);
if (!is_array($data)) { if (!is_array($data)) {
throw new DownloaderException("Failed to get GitHub tarball URL for {$repo} from {$api_url}"); 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; $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); preg_match('/^content-disposition:\s+attachment;\s*filename=("?)(?<filename>.+\.tar\.gz)\1/im', $head, $matches);
if ($matches) { if ($matches) {
$filename = $matches['filename']; $filename = $matches['filename'];
@@ -84,9 +84,9 @@ class GitHubTarball implements DownloadTypeInterface, CheckUpdateInterface
'ghtagtar' => 'tags', 'ghtagtar' => 'tags',
default => throw new DownloaderException("Invalid GitHubTarball type for {$name}"), 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}"; $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); 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', 'ghtagtar' => 'tags',
default => throw new DownloaderException("Invalid GitHubTarball type for {$name}"), 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 ?? ''; $new_version = $this->version ?? $old_version ?? '';
return new CheckUpdateResult( return new CheckUpdateResult(
old: $old_version, old: $old_version,

View File

@@ -16,8 +16,9 @@ trait GitHubTokenSetupTrait
// GITHUB_TOKEN support // GITHUB_TOKEN support
if (($token = getenv('GITHUB_TOKEN')) !== false && ($user = getenv('GITHUB_USER')) !== false) { if (($token = getenv('GITHUB_TOKEN')) !== false && ($user = getenv('GITHUB_USER')) !== false) {
logger()->debug("Using 'GITHUB_TOKEN' with user {$user} for authentication"); logger()->debug("Using 'GITHUB_TOKEN' with user {$user} for authentication");
spc_add_log_filter([$user, $token]); $encoded = base64_encode("{$user}:{$token}");
return ['Authorization: Basic ' . base64_encode("{$user}:{$token}")]; spc_add_log_filter([$user, $token, $encoded]);
return ["Authorization: Basic {$encoded}"];
} }
if (($token = getenv('GITHUB_TOKEN')) !== false) { if (($token = getenv('GITHUB_TOKEN')) !== false) {
logger()->debug("Using 'GITHUB_TOKEN' for authentication"); logger()->debug("Using 'GITHUB_TOKEN' for authentication");

View File

@@ -24,7 +24,7 @@ class PhpRelease implements DownloadTypeInterface, ValidatorInterface, CheckUpda
public function download(string $name, array $config, ArtifactDownloader $downloader): DownloadResult public function download(string $name, array $config, ArtifactDownloader $downloader): DownloadResult
{ {
$phpver = $downloader->getOption('with-php', '8.4'); $phpver = $downloader->getOption('with-php', '8.5');
// Handle 'git' version to clone from php-src repository // Handle 'git' version to clone from php-src repository
if ($phpver === 'git') { if ($phpver === 'git') {
$this->sha256 = null; $this->sha256 = null;
@@ -74,7 +74,7 @@ class PhpRelease implements DownloadTypeInterface, ValidatorInterface, CheckUpda
public function checkUpdate(string $name, array $config, ?string $old_version, ArtifactDownloader $downloader): CheckUpdateResult public function checkUpdate(string $name, array $config, ?string $old_version, ArtifactDownloader $downloader): CheckUpdateResult
{ {
$phpver = $downloader->getOption('with-php', '8.4'); $phpver = $downloader->getOption('with-php', '8.5');
if ($phpver === 'git') { if ($phpver === 'git') {
// git version: delegate to Git checkUpdate with master branch // git version: delegate to Git checkUpdate with master branch
return (new Git())->checkUpdate($name, ['url' => 'https://github.com/php/php-src.git', 'rev' => 'master'], $old_version, $downloader); return (new Git())->checkUpdate($name, ['url' => 'https://github.com/php/php-src.git', 'rev' => 'master'], $old_version, $downloader);
@@ -90,7 +90,7 @@ class PhpRelease implements DownloadTypeInterface, ValidatorInterface, CheckUpda
protected function fetchPhpReleaseInfo(string $name, array $config, ArtifactDownloader $downloader): array protected function fetchPhpReleaseInfo(string $name, array $config, ArtifactDownloader $downloader): array
{ {
$phpver = $downloader->getOption('with-php', '8.4'); $phpver = $downloader->getOption('with-php', '8.5');
// Handle 'git' version to clone from php-src repository // Handle 'git' version to clone from php-src repository
if ($phpver === 'git') { if ($phpver === 'git') {
// cannot fetch release info for git version, return empty info to skip validation // cannot fetch release info for git version, return empty info to skip validation

View File

@@ -52,7 +52,7 @@ class DownloaderOptions
return [ return [
// php version option // php version option
new InputOption("{$p}with-php", null, InputOption::VALUE_REQUIRED, 'PHP version in major.minor format (default 8.4)', '8.4'), new InputOption("{$p}with-php", null, InputOption::VALUE_REQUIRED, 'PHP version in major.minor format (default 8.5)', '8.5'),
// download preference options // download preference options
new InputOption("{$p}prefer-source", null, InputOption::VALUE_OPTIONAL, 'Prefer source downloads when both source and binary are available', false), new InputOption("{$p}prefer-source", null, InputOption::VALUE_OPTIONAL, 'Prefer source downloads when both source and binary are available', false),

View File

@@ -26,7 +26,7 @@ class CheckUpdateCommand extends BaseCommand
$this->addOption('parallel', 'p', InputOption::VALUE_REQUIRED, 'Number of parallel update checks (default: 10)', 10); $this->addOption('parallel', 'p', InputOption::VALUE_REQUIRED, 'Number of parallel update checks (default: 10)', 10);
// --with-php option for checking updates with a specific PHP version context // --with-php option for checking updates with a specific PHP version context
$this->addOption('with-php', null, InputOption::VALUE_REQUIRED, 'PHP version in major.minor format (default 8.4)', '8.4'); $this->addOption('with-php', null, InputOption::VALUE_REQUIRED, 'PHP version in major.minor format (default 8.5)', '8.5');
} }
public function handle(): int public function handle(): int

View File

@@ -7,11 +7,12 @@ namespace StaticPHP\Command\Dev;
use StaticPHP\Command\BaseCommand; use StaticPHP\Command\BaseCommand;
use StaticPHP\Config\PackageConfig; use StaticPHP\Config\PackageConfig;
use Symfony\Component\Console\Attribute\AsCommand; use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Input\InputOption;
#[AsCommand('dev:gen-ext-test-matrix', 'Generate GitHub Actions extension test matrix JSON', [], true)] #[AsCommand('dev:gen-ext-test-matrix', 'Generate GitHub Actions extension test matrix JSON', [], true)]
class GenExtTestMatrixCommand extends BaseCommand 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 = [ private const array OS_RUNNERS = [
'linux' => ['arch' => 'x86_64', 'runner' => 'ubuntu-latest', 'os_key' => 'Linux'], 'linux' => ['arch' => 'x86_64', 'runner' => 'ubuntu-latest', 'os_key' => 'Linux'],
@@ -19,6 +20,14 @@ class GenExtTestMatrixCommand extends BaseCommand
'macos' => ['arch' => 'aarch64', 'runner' => 'macos-15', 'os_key' => 'Darwin'], '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. * Extensions excluded from specific OS matrix entries.
*/ */
@@ -53,8 +62,29 @@ class GenExtTestMatrixCommand extends BaseCommand
'intl', 'intl',
]; ];
/**
* Extensions that are emitted as isolated standalone entries.
*/
private const array STANDALONE_ISOLATED = [
'swow' => '',
'swoole' => 'swoole-hook-',
];
/**
* Maximum number of orphan extensions per matrix entry.
*/
private const int ORPHAN_BATCH_SIZE = 15;
protected bool $no_motd = true; protected bool $no_motd = true;
public function configure(): void
{
$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('tier2', null, InputOption::VALUE_NONE, 'Use Tier 2 runners (Linux aarch64 + macOS x86_64, no Windows)');
}
public function handle(): int public function handle(): int
{ {
if (!spc_mode(SPC_MODE_SOURCE)) { if (!spc_mode(SPC_MODE_SOURCE)) {
@@ -62,6 +92,14 @@ class GenExtTestMatrixCommand extends BaseCommand
return static::USER_ERROR; return static::USER_ERROR;
} }
$parse_option = fn (string $name): array => array_values(array_filter(array_map('trim', explode(',', (string) $this->input->getOption($name)))));
$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(); $all = PackageConfig::getAll();
// Separate into regular and virtual extensions (build-static:false excluded globally) // Separate into regular and virtual extensions (build-static:false excluded globally)
@@ -81,9 +119,14 @@ class GenExtTestMatrixCommand extends BaseCommand
} }
} }
$entries = []; $os_runners = empty($filter_os_keys)
? $base_runners
: array_filter($base_runners, fn ($info) => in_array($info['os_key'], $filter_os_keys, true));
foreach (self::OS_RUNNERS as $os => $os_info) { $entries = [];
$all_ext_lib_deps = [];
foreach ($os_runners as $os => $os_info) {
$os_key = $os_info['os_key']; $os_key = $os_info['os_key'];
// Filter by OS support // Filter by OS support
@@ -99,6 +142,7 @@ class GenExtTestMatrixCommand extends BaseCommand
// Compute ext_deps for every pool member: union of depends + suggests, limited to pool // Compute ext_deps for every pool member: union of depends + suggests, limited to pool
$ext_deps = []; $ext_deps = [];
$os_lib_deps = [];
foreach (array_merge($os_regular, $os_virtual) as $pkg_name => $config) { foreach (array_merge($os_regular, $os_virtual) as $pkg_name => $config) {
$raw = array_merge( $raw = array_merge(
$this->resolvePlatformList($config, 'depends', $os), $this->resolvePlatformList($config, 'depends', $os),
@@ -108,7 +152,12 @@ class GenExtTestMatrixCommand extends BaseCommand
$raw, $raw,
fn ($d) => isset($pool_set[$d]) && $d !== $pkg_name fn ($d) => isset($pool_set[$d]) && $d !== $pkg_name
)); ));
$os_lib_deps[$this->displayName($pkg_name)] = array_values(array_filter(
$raw,
fn ($d) => !str_starts_with($d, 'ext-')
));
} }
$all_ext_lib_deps[$os] = $os_lib_deps;
// Which regular exts are reachable as a dep/suggest from another regular ext? // Which regular exts are reachable as a dep/suggest from another regular ext?
$depended_on = []; $depended_on = [];
@@ -136,13 +185,34 @@ class GenExtTestMatrixCommand extends BaseCommand
$groups = []; $groups = [];
$orphans = []; $orphans = [];
$standalone_set = array_fill_keys(self::STANDALONE, true); $standalone_set = array_fill_keys(self::STANDALONE, true);
$standalone_isolated = self::STANDALONE_ISOLATED;
foreach (array_merge($roots, $non_roots) as $ext) { foreach (array_merge($roots, $non_roots) as $ext) {
if (isset($covered[$ext])) { if (isset($covered[$ext])) {
continue; continue;
} }
$chain = $this->dfsCollect($ext, $ext_deps, $pool_set, $covered);
$display = $this->displayName($ext); $display = $this->displayName($ext);
if (array_key_exists($display, $standalone_isolated)) {
// Isolated standalone: mark only this ext + its hook virtuals as covered
$covered[$ext] = true;
$hook_prefix = $standalone_isolated[$display];
$group_names = [$display];
if ($hook_prefix !== '') {
foreach ($os_virtual as $vpkg => $_) {
$vdisplay = $this->displayName($vpkg);
if (str_starts_with($vdisplay, $hook_prefix) && !isset($covered[$vpkg])) {
$covered[$vpkg] = true;
$group_names[] = $vdisplay;
}
}
sort($group_names);
}
$groups[] = implode(',', $group_names);
continue;
}
$chain = $this->dfsCollect($ext, $ext_deps, $pool_set, $covered);
if (isset($standalone_set[$display])) { if (isset($standalone_set[$display])) {
// Always emit standalone extensions as their own single entry // Always emit standalone extensions as their own single entry
$groups[] = $display; $groups[] = $display;
@@ -169,11 +239,31 @@ class GenExtTestMatrixCommand extends BaseCommand
'os' => $os, 'os' => $os,
'arch' => $os_info['arch'], 'arch' => $os_info['arch'],
'extension' => $group, 'extension' => $group,
'build-args' => '"' . $group . '" ' . self::BUILD_TARGETS . ($extra !== '' ? ' ' . $extra : ''), 'build-args' => './bin/spc build "' . $group . '" ' . self::BUILD_TARGETS . ($extra !== '' ? ' ' . $extra : ''),
]; ];
} }
} }
if (!empty($filter_extensions)) {
$entries = array_values(array_filter($entries, function (array $entry) use ($filter_extensions): bool {
$names = explode(',', $entry['extension']);
return count(array_intersect($names, $filter_extensions)) > 0;
}));
}
if (!empty($filter_libs)) {
$entries = array_values(array_filter($entries, function (array $entry) use ($filter_libs, $all_ext_lib_deps): bool {
$names = explode(',', $entry['extension']);
$lib_deps = $all_ext_lib_deps[$entry['os']] ?? [];
foreach ($names as $name) {
if (count(array_intersect($lib_deps[$name] ?? [], $filter_libs)) > 0) {
return true;
}
}
return false;
}));
}
$this->output->write(json_encode($entries, JSON_UNESCAPED_SLASHES)); $this->output->write(json_encode($entries, JSON_UNESCAPED_SLASHES));
return static::SUCCESS; return static::SUCCESS;
} }
@@ -227,6 +317,9 @@ class GenExtTestMatrixCommand extends BaseCommand
foreach ($orphans as $ext) { foreach ($orphans as $ext) {
$placed = false; $placed = false;
foreach ($batches as &$batch) { foreach ($batches as &$batch) {
if (count($batch) >= self::ORPHAN_BATCH_SIZE) {
continue;
}
$conflict = false; $conflict = false;
foreach ($batch as $member) { foreach ($batch as $member) {
if (isset($adjacency[$ext][$member])) { if (isset($adjacency[$ext][$member])) {

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

View File

@@ -98,6 +98,25 @@ class ApplicationContext
return self::getContainer()->has($id); return self::getContainer()->has($id);
} }
/**
* Resolve $id, returning null if it can't be constructed.
* PHP-DI's has() returns true for any autowirable class even when get()
* would throw on missing scalar args — for "is this resolvable right now"
* semantics use this.
*
* @template T
* @param class-string<T> $id
* @return null|T
*/
public static function tryGet(string $id): mixed
{
try {
return self::getContainer()->get($id);
} catch (\Throwable) {
return null;
}
}
/** /**
* Set a service in the container. * Set a service in the container.
* Use sparingly - prefer configuration-based definitions. * Use sparingly - prefer configuration-based definitions.

View File

@@ -0,0 +1,44 @@
<?php
declare(strict_types=1);
namespace StaticPHP\Doctor\Item;
use Package\Artifact\llvm_tools;
use StaticPHP\Attribute\Doctor\CheckItem;
use StaticPHP\Attribute\Doctor\FixItem;
use StaticPHP\Attribute\Doctor\OptionalCheck;
use StaticPHP\DI\ApplicationContext;
use StaticPHP\Doctor\CheckResult;
use StaticPHP\Package\PackageInstaller;
use StaticPHP\Toolchain\Interface\ToolchainInterface;
use StaticPHP\Toolchain\ZigToolchain;
#[OptionalCheck([self::class, 'optionalCheck'])]
class LlvmToolsCheck
{
public static function optionalCheck(): bool
{
return ApplicationContext::get(ToolchainInterface::class) instanceof ZigToolchain;
}
/** @noinspection PhpUnused */
#[CheckItem('if llvm-tools (objcopy/strip/profdata) are built', level: 798)]
public function checkLlvmTools(): CheckResult
{
if (llvm_tools::isInstalled()) {
return CheckResult::ok(llvm_tools::path() . '/bin');
}
return CheckResult::fail('llvm-tools are not built', 'build-llvm-tools');
}
#[FixItem('build-llvm-tools')]
public function fixLlvmTools(): bool
{
$installer = new PackageInstaller(interactive: false);
$installer->addInstallPackage('llvm-tools');
$installer->run(true);
new llvm_tools()->buildForHost();
return llvm_tools::isInstalled();
}
}

View File

@@ -4,6 +4,7 @@ declare(strict_types=1);
namespace StaticPHP\Package; namespace StaticPHP\Package;
use Package\Artifact\llvm_tools;
use StaticPHP\Config\PackageConfig; use StaticPHP\Config\PackageConfig;
use StaticPHP\DI\ApplicationContext; use StaticPHP\DI\ApplicationContext;
use StaticPHP\Exception\SPCException; use StaticPHP\Exception\SPCException;
@@ -11,6 +12,8 @@ use StaticPHP\Exception\SPCInternalException;
use StaticPHP\Exception\WrongUsageException; use StaticPHP\Exception\WrongUsageException;
use StaticPHP\Runtime\Shell\Shell; use StaticPHP\Runtime\Shell\Shell;
use StaticPHP\Runtime\SystemTarget; use StaticPHP\Runtime\SystemTarget;
use StaticPHP\Toolchain\Interface\ToolchainInterface;
use StaticPHP\Toolchain\ZigToolchain;
use StaticPHP\Util\FileSystem; use StaticPHP\Util\FileSystem;
use StaticPHP\Util\GlobalPathTrait; use StaticPHP\Util\GlobalPathTrait;
use StaticPHP\Util\InteractiveTerm; use StaticPHP\Util\InteractiveTerm;
@@ -178,14 +181,18 @@ class PackageBuilder
if (SystemTarget::getTargetOS() === 'Darwin') { if (SystemTarget::getTargetOS() === 'Darwin') {
shell()->exec("dsymutil -f {$binary_path} -o {$debug_file}"); shell()->exec("dsymutil -f {$binary_path} -o {$debug_file}");
} elseif (SystemTarget::getTargetOS() === 'Linux') { } elseif (SystemTarget::getTargetOS() === 'Linux') {
$objcopy = getenv('OBJCOPY')
?: (ApplicationContext::tryGet(ToolchainInterface::class) instanceof ZigToolchain
? llvm_tools::binary('llvm-objcopy')
: 'objcopy');
if ($eu_strip = LinuxUtil::findCommand('eu-strip')) { if ($eu_strip = LinuxUtil::findCommand('eu-strip')) {
shell() shell()
->exec("{$eu_strip} -f {$debug_file} {$binary_path}") ->exec("{$eu_strip} -f {$debug_file} {$binary_path}")
->exec("objcopy --add-gnu-debuglink={$debug_file} {$binary_path}"); ->exec("{$objcopy} --add-gnu-debuglink={$debug_file} {$binary_path}");
} else { } else {
shell() shell()
->exec("objcopy --only-keep-debug {$binary_path} {$debug_file}") ->exec("{$objcopy} --only-keep-debug {$binary_path} {$debug_file}")
->exec("objcopy --add-gnu-debuglink={$debug_file} {$binary_path}"); ->exec("{$objcopy} --add-gnu-debuglink={$debug_file} {$binary_path}");
} }
} else { } else {
logger()->debug('extractDebugInfo is only supported on Linux and macOS'); logger()->debug('extractDebugInfo is only supported on Linux and macOS');
@@ -199,9 +206,12 @@ class PackageBuilder
*/ */
public function stripBinary(string $binary_path): void public function stripBinary(string $binary_path): void
{ {
$strip = ApplicationContext::tryGet(ToolchainInterface::class) instanceof ZigToolchain
? llvm_tools::binary('llvm-strip')
: 'strip';
shell()->exec(match (SystemTarget::getTargetOS()) { shell()->exec(match (SystemTarget::getTargetOS()) {
'Darwin' => "strip -S {$binary_path}", 'Darwin' => "{$strip} -S {$binary_path}",
'Linux' => "strip --strip-unneeded {$binary_path}", 'Linux' => "{$strip} --strip-unneeded {$binary_path}",
'Windows' => 'echo "Skip strip on Windows"', // Windows strip is not available for now 'Windows' => 'echo "Skip strip on Windows"', // Windows strip is not available for now
default => throw new SPCInternalException('stripBinary is only supported on Linux and macOS'), default => throw new SPCInternalException('stripBinary is only supported on Linux and macOS'),
}); });

View File

@@ -306,7 +306,7 @@ class PhpExtensionPackage extends Package
shell()->cd($package->getSourceDir()) shell()->cd($package->getSourceDir())
->setEnv($env) ->setEnv($env)
->exec( ->exec(
'./configure ' . $this->getPhpConfigureArg(SystemTarget::getCurrentPlatformString(), true) . './configure ' . $this->getPhpConfigureArg(SystemTarget::getTargetOS(), true) .
' --with-php-config=' . BUILD_BIN_PATH . '/php-config ' . ' --with-php-config=' . BUILD_BIN_PATH . '/php-config ' .
"--enable-shared --disable-static {$phpvars}" "--enable-shared --disable-static {$phpvars}"
); );

View File

@@ -499,6 +499,7 @@ class PackageLoader
throw new RegistryException('Package name must not be empty when no package context is available for BeforeStage attribute.'); throw new RegistryException('Package name must not be empty when no package context is available for BeforeStage attribute.');
} }
$package_name = $method_instance->package_name === '' ? $pkg->getName() : $method_instance->package_name; $package_name = $method_instance->package_name === '' ? $pkg->getName() : $method_instance->package_name;
$conditionals = array_map( $conditionals = array_map(
fn (\ReflectionAttribute $a) => $a->newInstance()->class, fn (\ReflectionAttribute $a) => $a->newInstance()->class,
[...$method->getDeclaringClass()->getAttributes(ConditionalOn::class), ...$method->getAttributes(ConditionalOn::class)], [...$method->getDeclaringClass()->getAttributes(ConditionalOn::class), ...$method->getAttributes(ConditionalOn::class)],
@@ -529,6 +530,7 @@ class PackageLoader
throw new RegistryException('Package name must not be empty when no package context is available for AfterStage attribute.'); throw new RegistryException('Package name must not be empty when no package context is available for AfterStage attribute.');
} }
$package_name = $method_instance->package_name === '' ? $pkg->getName() : $method_instance->package_name; $package_name = $method_instance->package_name === '' ? $pkg->getName() : $method_instance->package_name;
$conditionals = array_map( $conditionals = array_map(
fn (\ReflectionAttribute $a) => $a->newInstance()->class, fn (\ReflectionAttribute $a) => $a->newInstance()->class,
[...$method->getDeclaringClass()->getAttributes(ConditionalOn::class), ...$method->getAttributes(ConditionalOn::class)], [...$method->getDeclaringClass()->getAttributes(ConditionalOn::class), ...$method->getAttributes(ConditionalOn::class)],

View File

@@ -44,6 +44,7 @@ class DefaultShell extends Shell
$cmd = SPC_CURL_EXEC . " -sfSL --max-time 3600 {$retry_arg} {$compressed_arg} {$method_arg} {$header_arg} {$url_arg}"; $cmd = SPC_CURL_EXEC . " -sfSL --max-time 3600 {$retry_arg} {$compressed_arg} {$method_arg} {$header_arg} {$url_arg}";
$this->logCommandInfo($cmd); $this->logCommandInfo($cmd);
logger()->debug("[CURL EXECUTE] {$cmd}");
$result = $this->passthru($cmd, capture_output: true, throw_on_error: false); $result = $this->passthru($cmd, capture_output: true, throw_on_error: false);
$ret = $result['code']; $ret = $result['code'];
$output = $result['output']; $output = $result['output'];
@@ -83,7 +84,7 @@ class DefaultShell extends Shell
/** /**
* Execute a Git clone command to clone a repository. * 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); $path = FileSystem::convertPath($path);
if (file_exists($path)) { if (file_exists($path)) {
@@ -98,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}"); $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); $this->logCommandInfo($cmd);
logger()->debug("[GIT CLONE] {$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) { if ($submodules !== null) {
$depth_flag = $shallow ? '--depth 1' : ''; $depth_flag = $shallow ? '--depth 1' : '';
foreach ($submodules as $submodule) { foreach ($submodules as $submodule) {

View File

@@ -244,6 +244,7 @@ class FileSystem
*/ */
public static function getClassesPsr4(string $dir, string $base_namespace, mixed $rule = null, bool|string $return_path_value = false, bool $auto_require = false): array public static function getClassesPsr4(string $dir, string $base_namespace, mixed $rule = null, bool|string $return_path_value = false, bool $auto_require = false): array
{ {
$base_namespace = rtrim($base_namespace, '\\');
$classes = []; $classes = [];
$files = FileSystem::scanDirFiles($dir, true, true); $files = FileSystem::scanDirFiles($dir, true, true);
if ($files === false) { if ($files === false) {

View File

@@ -54,6 +54,7 @@ class WindowsUtil
} }
$args = [ $args = [
'-latest', '-latest',
'-products', '*',
'-format', 'json', '-format', 'json',
'-requires', 'Microsoft.VisualStudio.Component.VC.Tools.x86.x64', '-requires', 'Microsoft.VisualStudio.Component.VC.Tools.x86.x64',
]; ];

View File

@@ -33,6 +33,23 @@ ConsoleLogger::$date_format = 'H:i:s';
ConsoleLogger::$format = '[%date% %level_long%] %body%'; ConsoleLogger::$format = '[%date% %level_long%] %body%';
$ob_logger = new ConsoleLogger(LogLevel::WARNING); $ob_logger = new ConsoleLogger(LogLevel::WARNING);
$ob_logger->addLogCallback(function ($level, &$output, &$message, &$context, bool $shouldLog) {
global $spc_log_filters;
if (!is_array($spc_log_filters)) {
$spc_log_filters = [];
}
// filter message and context
$output = str_replace($spc_log_filters, '***', $output);
$message = str_replace($spc_log_filters, '***', $message);
$context = array_map(function ($item) use ($spc_log_filters) {
if (is_string($item)) {
return str_replace($spc_log_filters, '***', $item);
}
return $item;
}, $context);
return true;
});
// setup log file // setup log file
if (filter_var(getenv('SPC_ENABLE_LOG_FILE'), FILTER_VALIDATE_BOOLEAN)) { if (filter_var(getenv('SPC_ENABLE_LOG_FILE'), FILTER_VALIDATE_BOOLEAN)) {
// init spc log files // init spc log files
@@ -60,5 +77,9 @@ if (filter_var(getenv('SPC_ENABLE_LOG_FILE'), FILTER_VALIDATE_BOOLEAN)) {
// load core registry // load core registry
Registry::loadRegistry(ROOT_DIR . '/spc.registry.yml'); Registry::loadRegistry(ROOT_DIR . '/spc.registry.yml');
// in vendor mode, auto-load the local working directory registry if it exists
if (spc_mode(SPC_MODE_VENDOR) && file_exists(WORKING_DIR . '/spc.registry.yml')) {
Registry::loadRegistry(WORKING_DIR . '/spc.registry.yml');
}
// load registries from environment variable SPC_REGISTRIES // load registries from environment variable SPC_REGISTRIES
Registry::loadFromEnvOrOption(); Registry::loadFromEnvOrOption();

View File

@@ -8,7 +8,7 @@ assert(function_exists('curl_exec'));
assert(function_exists('curl_close')); assert(function_exists('curl_close'));
assert(function_exists('curl_version')); assert(function_exists('curl_version'));
$curl_version = curl_version(); $curl_version = curl_version();
if (stripos($curl_version['ssl_version'], 'schannel') !== false) { if (stripos($curl_version['ssl_version'], 'schannel') !== false && !extension_loaded('swow')) {
$domain_list = [ $domain_list = [
'https://captive.apple.com/', 'https://captive.apple.com/',
'https://detectportal.firefox.com/', 'https://detectportal.firefox.com/',

View File

@@ -50,7 +50,7 @@ $prefer_pre_built = false;
// If you want to test your added extensions and libs, add below (comma separated, example `bcmath,openssl`). // If you want to test your added extensions and libs, add below (comma separated, example `bcmath,openssl`).
$extensions = match (PHP_OS_FAMILY) { $extensions = match (PHP_OS_FAMILY) {
'Linux', 'Darwin' => 'curl,swoole', 'Linux', 'Darwin' => 'openssl,zstd,clickhouse',
'Windows' => 'intl', 'Windows' => 'intl',
}; };

View File

@@ -0,0 +1,104 @@
<?php
declare(strict_types=1);
namespace Tests;
use PHPUnit\Framework\TestCase;
use Psr\Log\LogLevel;
use ZM\Logger\ConsoleLogger;
/**
* @internal
*/
class GlobalsFunctionsTest extends TestCase
{
protected function setUp(): void
{
$GLOBALS['spc_log_filters'] = null;
}
protected function tearDown(): void
{
$GLOBALS['spc_log_filters'] = null;
}
public function testAddLogFilterDeduplicates(): void
{
spc_add_log_filter('secret-value');
spc_add_log_filter('secret-value');
spc_add_log_filter(['secret-value', 'other']);
$this->assertSame(['secret-value', 'other'], $GLOBALS['spc_log_filters']);
}
public function testWriteLogMasksRegisteredValues(): void
{
spc_add_log_filter(['octocat', 'ghp_abcdef1234567890']);
$stream = fopen('php://memory', 'r+');
spc_write_log($stream, 'user=octocat token=ghp_abcdef1234567890');
rewind($stream);
$written = stream_get_contents($stream);
fclose($stream);
$this->assertSame('user=*** token=***', $written);
}
public function testLoggerCallbackMasksOutput(): void
{
$token = 'ghp_abcdef1234567890';
spc_add_log_filter($token);
$stream = fopen('php://memory', 'r+');
$logger = new ConsoleLogger(LogLevel::DEBUG, $stream, false);
$logger->addLogCallback(function ($level, &$output, &$message, &$context, bool $shouldLog) {
global $spc_log_filters;
if (!is_array($spc_log_filters)) {
$spc_log_filters = [];
}
$output = str_replace($spc_log_filters, '***', $output);
$message = str_replace($spc_log_filters, '***', $message);
$context = array_map(function ($item) use ($spc_log_filters) {
if (is_string($item)) {
return str_replace($spc_log_filters, '***', $item);
}
return $item;
}, $context);
return true;
});
$logger->debug("[PASSTHRU] curl -H\"Authorization: Bearer {$token}\" https://api.github.com/x");
rewind($stream);
$written = stream_get_contents($stream);
fclose($stream);
$this->assertStringNotContainsString($token, $written);
$this->assertStringContainsString('***', $written);
}
public function testGitHubTokenTraitRegistersEncodedBasicAuthBlob(): void
{
$user = 'octocat';
$token = 'ghp_abcdef1234567890';
$original_token = getenv('GITHUB_TOKEN');
$original_user = getenv('GITHUB_USER');
putenv("GITHUB_TOKEN={$token}");
putenv("GITHUB_USER={$user}");
try {
$headers = \StaticPHP\Artifact\Downloader\Type\GitHubRelease::getGitHubTokenHeadersStatic();
$encoded = base64_encode("{$user}:{$token}");
$this->assertSame(["Authorization: Basic {$encoded}"], $headers);
$this->assertContains($user, $GLOBALS['spc_log_filters']);
$this->assertContains($token, $GLOBALS['spc_log_filters']);
$this->assertContains($encoded, $GLOBALS['spc_log_filters']);
} finally {
$original_token === false ? putenv('GITHUB_TOKEN') : putenv("GITHUB_TOKEN={$original_token}");
$original_user === false ? putenv('GITHUB_USER') : putenv("GITHUB_USER={$original_user}");
}
}
}

View File

@@ -254,11 +254,16 @@ class ArtifactTest extends TestCase
ApplicationContext::initialize(); ApplicationContext::initialize();
ApplicationContext::set(ArtifactCache::class, $cache); ApplicationContext::set(ArtifactCache::class, $cache);
// Use a platform-appropriate absolute path: a Unix-style /tmp/... isn't
// absolute on Windows (no drive letter), so the test would otherwise
// fall through into the SOURCE_PATH-prefixed branch on Windows.
$extract = DIRECTORY_SEPARATOR === '\\' ? 'C:\tmp\my-pkg-extract' : '/tmp/my-pkg-extract';
$artifact = new Artifact('my-pkg', [ $artifact = new Artifact('my-pkg', [
'source' => ['type' => 'url', 'url' => 'https://example.com/file.tar.gz', 'extract' => '/tmp/my-pkg-extract'], 'source' => ['type' => 'url', 'url' => 'https://example.com/file.tar.gz', 'extract' => $extract],
]); ]);
$expected = str_replace(['/', '\\'], DIRECTORY_SEPARATOR, '/tmp/my-pkg-extract'); $expected = str_replace(['/', '\\'], DIRECTORY_SEPARATOR, $extract);
$this->assertSame($expected, $artifact->getSourceDir()); $this->assertSame($expected, $artifact->getSourceDir());
} }
@@ -703,11 +708,7 @@ class ArtifactTest extends TestCase
'Windows' => 'windows', 'Windows' => 'windows',
default => 'linux', default => 'linux',
}; };
$arch = php_uname('m'); return "{$os}-" . arch2gnu(php_uname('m'));
if ($arch === 'arm64') {
$arch = 'aarch64';
}
return "{$os}-{$arch}";
} }
private function injectArtifactConfig(string $name, array $config): void private function injectArtifactConfig(string $name, array $config): void