Compare commits

..
3 Commits
Author SHA1 Message Date
Shivam Mathur 02130b2212 testing [skip ci] 2026-10-08 12:51:19 +05:30
Shivam Mathur d2b260fd73 testing [skip ci] 2026-06-08 21:16:04 +05:30
Shivam Mathur 420be8cbcd Release v2-verbose 2026-06-08 21:15:20 +05:30
79 changed files with 1790 additions and 3844 deletions
+1 -1
View File
@@ -88,7 +88,7 @@ body:
label: "Are you willing to submit a PR?" label: "Are you willing to submit a PR?"
description: "We accept pull requests targeting the develop branch." description: "We accept pull requests targeting the develop branch."
options: options:
- "No"
- "Yes" - "Yes"
- "No"
validations: validations:
required: true required: true
+4 -4
View File
@@ -20,19 +20,19 @@ jobs:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- name: Checkout - name: Checkout
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6
with: with:
fetch-depth: 2 fetch-depth: 2
persist-credentials: false persist-credentials: false
- name: Initialize CodeQL - name: Initialize CodeQL
uses: github/codeql-action/init@33d7b85da1a04171e211befe2c739303b9a4c066 # v4 uses: github/codeql-action/init@7211b7c8077ea37d8641b6271f6a365a22a5fbfa # v4
with: with:
config-file: ./.github/codeql/codeql-configuration.yml config-file: ./.github/codeql/codeql-configuration.yml
languages: javascript languages: javascript
- name: Autobuild - name: Autobuild
uses: github/codeql-action/autobuild@33d7b85da1a04171e211befe2c739303b9a4c066 # v4 uses: github/codeql-action/autobuild@7211b7c8077ea37d8641b6271f6a365a22a5fbfa # v4
- name: Perform CodeQL Analysis - name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@33d7b85da1a04171e211befe2c739303b9a4c066 # v4 uses: github/codeql-action/analyze@7211b7c8077ea37d8641b6271f6a365a22a5fbfa # v4
+9 -9
View File
@@ -19,11 +19,11 @@ jobs:
strategy: strategy:
fail-fast: false fail-fast: false
matrix: matrix:
operating-system: [ubuntu-24.04, ubuntu-22.04, windows-2022, macos-15] operating-system: [ubuntu-24.04, ubuntu-22.04, windows-2022, macos-15-intel]
php-versions: ['5.3', '5.4', '5.5', '5.6', '7.0', '7.1', '7.2', '7.3', '7.4', '8.0', '8.1', '8.2', '8.3', '8.4', '8.5', '8.6', '8.7'] php-versions: ['5.3', '5.4', '5.5', '5.6', '7.0', '7.1', '7.2', '7.3', '7.4', '8.0', '8.1', '8.2', '8.3', '8.4', '8.5', '8.6']
steps: steps:
- name: Setup PHP - name: Setup PHP
uses: shivammathur/setup-php@eb7c497e18156a6bbabfef1d3a82760b9eda3962 # v2 uses: shivammathur/setup-php@7c071dfe9dc99bdf297fa79cb49ea005b9fcadbc # v2
with: with:
php-version: ${{ matrix.php-versions }} php-version: ${{ matrix.php-versions }}
tools: none tools: none
@@ -42,7 +42,7 @@ jobs:
run: | run: |
php -m | Out-File -FilePath "$env:file.all" -Append php -m | Out-File -FilePath "$env:file.all" -Append
- name: Setup PHP - name: Setup PHP
uses: shivammathur/setup-php@eb7c497e18156a6bbabfef1d3a82760b9eda3962 # v2 uses: shivammathur/setup-php@7c071dfe9dc99bdf297fa79cb49ea005b9fcadbc # v2
with: with:
php-version: ${{ matrix.php-versions }} php-version: ${{ matrix.php-versions }}
extensions: none extensions: none
@@ -91,7 +91,7 @@ jobs:
Remove-Item "$env:file.all" -Force Remove-Item "$env:file.all" -Force
Remove-Item "$env:file.builtin" -Force Remove-Item "$env:file.builtin" -Force
- name: Upload artifacts - name: Upload artifacts
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7
with: with:
name: lists-php${{ matrix.php-versions }}-${{ matrix.operating-system }}.md name: lists-php${{ matrix.php-versions }}-${{ matrix.operating-system }}.md
path: php${{ matrix.php-versions }}-${{ matrix.operating-system }}.md path: php${{ matrix.php-versions }}-${{ matrix.operating-system }}.md
@@ -104,12 +104,12 @@ jobs:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- name: Checkout - name: Checkout
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6
with: with:
repository: ${{ github.repository }}.wiki repository: ${{ github.repository }}.wiki
persist-credentials: false persist-credentials: false
- name: Download artifacts - name: Download artifacts
uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8 uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8
with: with:
path: ${{ github.workspace }}/lists path: ${{ github.workspace }}/lists
pattern: lists-* pattern: lists-*
@@ -125,9 +125,9 @@ jobs:
run: | run: |
for os in ubuntu-24.04 ubuntu-22.04 windows-2025 windows-2022 windows-2019 macos-13 macos-14 macos-15 macos-26; do for os in ubuntu-24.04 ubuntu-22.04 windows-2025 windows-2022 windows-2019 macos-13 macos-14 macos-15 macos-26; do
echo "These are extensions which are loaded by default on the following PHP versions. More extensions which are available as packages and available on pecl are supported by setup-php. Refer to [php extension support](https://github.com/shivammathur/setup-php#heavy_plus_sign-php-extension-support) for more details." > Php-extensions-loaded-on-"$os".md echo "These are extensions which are loaded by default on the following PHP versions. More extensions which are available as packages and available on pecl are supported by setup-php. Refer to [php extension support](https://github.com/shivammathur/setup-php#heavy_plus_sign-php-extension-support) for more details." > Php-extensions-loaded-on-"$os".md
for version in 5.3 5.4 5.5 5.6 7.0 7.1 7.2 7.3 7.4 8.0 8.1 8.2 8.3 8.4 8.5 8.6 8.7; do for version in 5.3 5.4 5.5 5.6 7.0 7.1 7.2 7.3 7.4 8.0 8.1 8.2 8.3 8.4 8.5 8.6; do
if [[ "${os%-*}" = "macos" ]]; then if [[ "${os%-*}" = "macos" ]]; then
cat lists/php"$version"-macos-15.md >> Php-extensions-loaded-on-"$os".md cat lists/php"$version"-macos-15-intel.md >> Php-extensions-loaded-on-"$os".md
elif [ "${os%-*}" = "windows" ]; then elif [ "${os%-*}" = "windows" ]; then
cat lists/php"$version"-windows-2022.md >> Php-extensions-loaded-on-"$os".md cat lists/php"$version"-windows-2022.md >> Php-extensions-loaded-on-"$os".md
else else
+3 -6
View File
@@ -33,13 +33,13 @@ jobs:
operating-system: [ubuntu-latest, windows-latest, macos-latest] operating-system: [ubuntu-latest, windows-latest, macos-latest]
steps: steps:
- name: Checkout - name: Checkout
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6
with: with:
fetch-depth: 2 fetch-depth: 2
persist-credentials: false persist-credentials: false
- name: Setup Node.js 24.x - name: Setup Node.js 24.x
uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v6 uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6
with: with:
node-version: 24.x node-version: 24.x
@@ -52,9 +52,6 @@ jobs:
- name: ESLint Check - name: ESLint Check
run: npm run lint run: npm run lint
- name: TypeScript Check
run: npm run typecheck
- name: Run tests - name: Run tests
run: npm test run: npm test
@@ -62,7 +59,7 @@ jobs:
run: npm audit run: npm audit
- name: Send Coverage - name: Send Coverage
uses: codecov/codecov-action@303a32d7a59b442fa8d48b6a1cc6825c09c847a5 # v7.1.1 uses: codecov/codecov-action@e79a6962e0d4c0c17b229090214935d2e33f8354 # v6
with: with:
token: ${{ secrets.CODECOV_TOKEN }} token: ${{ secrets.CODECOV_TOKEN }}
files: coverage/lcov.info files: coverage/lcov.info
+5 -5
View File
@@ -31,8 +31,8 @@ jobs:
strategy: strategy:
fail-fast: false fail-fast: false
matrix: matrix:
operating-system: [ubuntu-24.04, ubuntu-22.04, windows-2022, macos-15] operating-system: [ubuntu-24.04, ubuntu-22.04, windows-2022, macos-15-intel]
php-versions: ['5.3', '5.4', '5.5', '5.6', '7.0', '7.1', '7.2', '7.3', '7.4', '8.0', '8.1', '8.2', '8.3', '8.4', '8.5', '8.6', '8.7'] php-versions: ['5.3', '5.4', '5.5', '5.6', '7.0', '7.1', '7.2', '7.3', '7.4', '8.0', '8.1', '8.2', '8.3', '8.4', '8.5', '8.6']
include: include:
- operating-system: ubuntu-24.04 - operating-system: ubuntu-24.04
php-versions: '' php-versions: ''
@@ -42,20 +42,20 @@ jobs:
key: cache-v5 key: cache-v5
steps: steps:
- name: Checkout - name: Checkout
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6
with: with:
persist-credentials: false persist-credentials: false
- name: Setup cache environment - name: Setup cache environment
id: cache-env id: cache-env
uses: shivammathur/cache-extensions@695b1b465eba861efe67cbbc31252c27f5ed253d # v1 uses: shivammathur/cache-extensions@256729b5fef535345e27904657f78048c0990f81 # v1
with: with:
php-version: ${{ matrix.php-versions || env.default-php-version }} php-version: ${{ matrix.php-versions || env.default-php-version }}
extensions: ${{ env.extensions }} extensions: ${{ env.extensions }}
key: ${{ env.key }} key: ${{ env.key }}
- name: Cache extensions - name: Cache extensions
uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v5 uses: actions/cache@27d5ce7f107fe9357f9df03efb73ab90386fccae # v5
with: with:
path: ${{ steps.cache-env.outputs.dir }} path: ${{ steps.cache-env.outputs.dir }}
key: ${{ steps.cache-env.outputs.key }} key: ${{ steps.cache-env.outputs.key }}
+6 -11
View File
@@ -26,19 +26,19 @@ jobs:
steps: steps:
- name: Checkout release - name: Checkout release
if: github.event_name != 'workflow_dispatch' if: github.event_name != 'workflow_dispatch'
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6
with: with:
persist-credentials: false persist-credentials: false
- name: Checkout tag - name: Checkout tag
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6
if: github.event_name == 'workflow_dispatch' if: github.event_name == 'workflow_dispatch'
with: with:
ref: ${{ github.event.inputs.tag }} ref: ${{ github.event.inputs.tag }}
persist-credentials: false persist-credentials: false
- name: Setup Node.js - name: Setup Node.js
uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v6 uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6
with: with:
node-version: '24.x' node-version: '24.x'
registry-url: https://registry.npmjs.org registry-url: https://registry.npmjs.org
@@ -50,17 +50,12 @@ jobs:
npm run build npm run build
sed -i -e '/lib\//d' .gitignore sed -i -e '/lib\//d' .gitignore
- name: Select npm distribution tag
id: publish-tag
run: |
jq -r '.version | if test("alpha|beta|rc"; "i") then "tag=next" else "tag=latest" end' package.json >> "$GITHUB_OUTPUT"
- name: Publish to NPM - name: Publish to NPM
if: "!contains(github.event.inputs.skip, 'skip-npm')" if: "!contains(github.event.inputs.skip, 'skip-npm')"
run: npm publish --access public --tag "${{ steps.publish-tag.outputs.tag }}" run: npm publish --access public
- name: Change to GitHub Packages registry - name: Change to GitHub Packages registry
uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v6 uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6
with: with:
registry-url: https://npm.pkg.github.com registry-url: https://npm.pkg.github.com
package-manager-cache: false package-manager-cache: false
@@ -72,6 +67,6 @@ jobs:
- name: Publish to GitHub Packages - name: Publish to GitHub Packages
if: "!contains(github.event.inputs.skip, 'skip-github-packages')" if: "!contains(github.event.inputs.skip, 'skip-github-packages')"
run: npm publish --tag "${{ steps.publish-tag.outputs.tag }}" run: npm publish
env: env:
NODE_AUTH_TOKEN: ${{ secrets.GITHUB_TOKEN }} NODE_AUTH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+56 -94
View File
@@ -10,7 +10,7 @@
<a href="https://github.com/shivammathur/setup-php" title="GitHub action to setup PHP"><img alt="GitHub Actions status" src="https://github.com/shivammathur/setup-php/workflows/Main%20workflow/badge.svg"></a> <a href="https://github.com/shivammathur/setup-php" title="GitHub action to setup PHP"><img alt="GitHub Actions status" src="https://github.com/shivammathur/setup-php/workflows/Main%20workflow/badge.svg"></a>
<a href="https://codecov.io/gh/shivammathur/setup-php" title="Code coverage"><img alt="Codecov Code Coverage" src="https://img.shields.io/codecov/c/github/shivammathur/setup-php?logo=codecov"></a> <a href="https://codecov.io/gh/shivammathur/setup-php" title="Code coverage"><img alt="Codecov Code Coverage" src="https://img.shields.io/codecov/c/github/shivammathur/setup-php?logo=codecov"></a>
<a href="https://github.com/shivammathur/setup-php/blob/main/LICENSE" title="license"><img alt="LICENSE" src="https://img.shields.io/badge/license-MIT-428f7e.svg?logo=open%20source%20initiative&logoColor=white&labelColor=555555"></a> <a href="https://github.com/shivammathur/setup-php/blob/main/LICENSE" title="license"><img alt="LICENSE" src="https://img.shields.io/badge/license-MIT-428f7e.svg?logo=open%20source%20initiative&logoColor=white&labelColor=555555"></a>
<a href="#tada-php-support" title="PHP Versions Supported"><img alt="PHP Versions Supported" src="https://img.shields.io/badge/php-5.3%20to%208.7-777bb3.svg?logo=php&logoColor=white&labelColor=555555"></a> <a href="#tada-php-support" title="PHP Versions Supported"><img alt="PHP Versions Supported" src="https://img.shields.io/badge/php-5.3%20to%208.6-777bb3.svg?logo=php&logoColor=white&labelColor=555555"></a>
</p> </p>
<p align="center"> <p align="center">
<a href="https://reddit.com/r/setup_php" title="setup-php reddit"><img alt="setup-php reddit" src="https://img.shields.io/badge/reddit-join-FF5700?logo=reddit&logoColor=FF5700&labelColor=555555"></a> <a href="https://reddit.com/r/setup_php" title="setup-php reddit"><img alt="setup-php reddit" src="https://img.shields.io/badge/reddit-join-FF5700?logo=reddit&logoColor=FF5700&labelColor=555555"></a>
@@ -18,7 +18,7 @@
<a href="https://status.setup-php.com" title="setup-php status"><img alt="setup-php status" src="https://img.shields.io/badge/status-subscribe-28A745?logo=statuspage&logoColor=28A745&labelColor=555555"></a> <a href="https://status.setup-php.com" title="setup-php status"><img alt="setup-php status" src="https://img.shields.io/badge/status-subscribe-28A745?logo=statuspage&logoColor=28A745&labelColor=555555"></a>
</p> </p>
Setup PHP with required extensions, php.ini configuration, code-coverage support, and various tools like composer in [GitHub Actions](https://github.com/features/actions "GitHub Actions"). This action gives you a cross-platform interface to set up the PHP environment you need to test your application. Refer to the [Usage](#memo-usage "How to use this") section and [examples](#examples "Examples of use") to see how to use this. Setup PHP with required extensions, php.ini configuration, code-coverage support and various tools like composer in [GitHub Actions](https://github.com/features/actions "GitHub Actions"). This action gives you a cross-platform interface to set up the PHP environment you need to test your application. Refer to [Usage](#memo-usage "How to use this") section and [examples](#examples "Examples of use") to see how to use this.
## Contents ## Contents
@@ -68,52 +68,46 @@ Both `GitHub-hosted` and `self-hosted` runners are supported by `setup-php` on t
### GitHub-Hosted Runners ### GitHub-Hosted Runners
| Virtual environment | Arch | YAML workflow label | Pre-installed PHP | | Virtual environment | Arch | YAML workflow label | Pre-installed PHP |
|------------------------|---------|-----------------------------------------------------------|-------------------| |---------------------|---------|------------------------------------|-------------------|
| Ubuntu 26.04 | x86_64 | `ubuntu-26.04` | `PHP 8.5` | | Ubuntu 24.04 | x86_64 | `ubuntu-latest` or `ubuntu-24.04` | `PHP 8.3` |
| Ubuntu 24.04 | x86_64 | `ubuntu-latest` or `ubuntu-24.04` | `PHP 8.3` | | Ubuntu 22.04 | x86_64 | `ubuntu-22.04` | `PHP 8.1` |
| Ubuntu 22.04 | x86_64 | `ubuntu-22.04` | `PHP 8.1` | | Ubuntu 24.04 | aarch64 | `ubuntu-24.04-arm` | `PHP 8.3` |
| Ubuntu 26.04 | aarch64 | `ubuntu-26.04-arm` | `PHP 8.5` | | Ubuntu 22.04 | aarch64 | `ubuntu-22.04-arm` | `PHP 8.1` |
| Ubuntu 24.04 | aarch64 | `ubuntu-24.04-arm` | `PHP 8.3` | | Windows Server 2025 | x64 | `windows-2025` | `PHP 8.5` |
| Ubuntu 22.04 | aarch64 | `ubuntu-22.04-arm` | `PHP 8.1` | | Windows Server 2022 | x64 | `windows-latest` or `windows-2022` | `PHP 8.5` |
| Windows Server 2025 | x64 | `windows-latest`, `windows-2025` or `windows-2025-vs2026` | `PHP 8.5` | | macOS Tahoe 26.x | arm64 | `macos-26` | - |
| Windows Server 2022 | x64 | `windows-2022` | `PHP 8.5` | | macOS Sequoia 15.x | arm64 | `macos-latest` or `macos-15` | - |
| Windows 11 ARM | arm64 | `windows-11-arm` or `windows-11-vs2026-arm` | `PHP 8.4` | | macOS Sonoma 14.x | arm64 | `macos-14` | - |
| macOS Golden Gate 27.x | arm64 | `xcode-27` | - | | macOS Tahoe 26.x | x86_64 | `macos-26-intel` | `PHP 8.5` |
| macOS Tahoe 26.x | arm64 | `macos-latest` or `macos-26` | - | | macOS Sequoia 15.x | x86_64 | `macos-15-intel` | `PHP 8.5` |
| macOS Sequoia 15.x | arm64 | `macos-15` | - |
| macOS Tahoe 26.x | x86_64 | `macos-26-intel` | `PHP 8.5` |
| macOS Sequoia 15.x | x86_64 | `macos-15-intel` | `PHP 8.5` |
> [!NOTE]
> Support for Intel (`x86_64`) macOS runners and macOS Sonoma 14.x (`macos-14`) arm64 runners is deprecated and will be removed completely in a future release of `setup-php`. We recommend migrating to arm64-based macOS runners running macOS 15 or newer, such as `macos-26` or `macos-15`.
### Self-Hosted Runners ### Self-Hosted Runners
| Host OS/Virtual environment | YAML workflow label | | Host OS/Virtual environment | YAML workflow label |
|----------------------------------|----------------------------| |----------------------------------|----------------------------|
| Ubuntu 26.04 | `self-hosted` or `Linux` |
| Ubuntu 24.04 | `self-hosted` or `Linux` | | Ubuntu 24.04 | `self-hosted` or `Linux` |
| Ubuntu 22.04 | `self-hosted` or `Linux` | | Ubuntu 22.04 | `self-hosted` or `Linux` |
| Debian 13 | `self-hosted` or `Linux` | | Debian 13 | `self-hosted` or `Linux` |
| Debian 12 | `self-hosted` or `Linux` | | Debian 12 | `self-hosted` or `Linux` |
| Debian 11 | `self-hosted` or `Linux` |
| Windows 7 and newer | `self-hosted` or `Windows` | | Windows 7 and newer | `self-hosted` or `Windows` |
| Windows Server 2012 R2 and newer | `self-hosted` or `Windows` | | Windows Server 2012 R2 and newer | `self-hosted` or `Windows` |
| macOS Golden Gate 27.x arm64 | `self-hosted` or `macOS` | | macOS Tahoe 26.x x86_64/arm64 | `self-hosted` or `macOS` |
| macOS Tahoe 26.x arm64 | `self-hosted` or `macOS` | | macOS Sequoia 15.x x86_64/arm64 | `self-hosted` or `macOS` |
| macOS Sequoia 15.x arm64 | `self-hosted` or `macOS` | | macOS Sonoma 14.x x86_64/arm64 | `self-hosted` or `macOS` |
- Refer to the [self-hosted setup](#self-hosted-setup) to use the action on self-hosted runners. - Refer to the [self-hosted setup](#self-hosted-setup) to use the action on self-hosted runners.
- Operating systems based on the above Ubuntu and Debian versions are also supported on a best effort basis. - Operating systems based on the above Ubuntu and Debian versions are also supported on best effort basis.
- If the requested PHP version is pre-installed, `setup-php` switches to it, otherwise it installs the PHP version. - If the requested PHP version is pre-installed, `setup-php` switches to it, otherwise it installs the PHP version.
## :tada: PHP Support ## :tada: PHP Support
On all supported OS/Platforms, the following PHP versions can be set up as per the runner. On all supported OS/Platforms, the following PHP versions can be set up as per the runner.
- PHP 5.3 to PHP 8.7 on GitHub-hosted runners, except for macOS ARM64 runners. - PHP 5.3 to PHP 8.6 on GitHub-hosted runners, except for macOS ARM64 runners (macos-14).
- PHP 5.6 to PHP 8.7 on GitHub-hosted macOS ARM64 runners. - PHP 5.6 to PHP 8.6 on GitHub-hosted macOS ARM64 runners (macos-14).
- PHP 5.6 to PHP 8.7 on self-hosted runners. - PHP 5.6 to PHP 8.6 on self-hosted runners.
| PHP Version | Stability | Release Support | Runner Support | | PHP Version | Stability | Release Support | Runner Support |
|-------------|-----------|-----------------------|--------------------------------| |-------------|-----------|-----------------------|--------------------------------|
@@ -133,11 +127,10 @@ On all supported OS/Platforms, the following PHP versions can be set up as per t
| `8.4` | `Stable` | `Active` | `GitHub-hosted`, `self-hosted` | | `8.4` | `Stable` | `Active` | `GitHub-hosted`, `self-hosted` |
| `8.5` | `Stable` | `Active` | `GitHub-hosted`, `self-hosted` | | `8.5` | `Stable` | `Active` | `GitHub-hosted`, `self-hosted` |
| `8.6` | `Nightly` | `In development` | `GitHub-hosted`, `self-hosted` | | `8.6` | `Nightly` | `In development` | `GitHub-hosted`, `self-hosted` |
| `8.7` | `Nightly` | `In development` | `GitHub-hosted`, `self-hosted` |
> [!Note] > [!Note]
> - Specifying `8.7` or `master` in `php-version` input installs a nightly build of `PHP 8.7.0-dev` from the master branch of PHP. Specifying `8.6` or `nightly` installs a nightly build of `PHP 8.6.0-dev` from the PHP-8.6 branch. See [nightly build setup](#nightly-build-setup) for more information. > - Specifying `8.6` in `php-version` input installs a nightly build of `PHP 8.6.0-dev` from the master branch of PHP. See [nightly build setup](#nightly-build-setup) for more information.
> - To use JIT on `PHP 8.0` and above, refer to the [JIT configuration](#jit-configuration) section. > - To use JIT on `PHP 8.0` and above, refer to the [JIT configuration](#jit-configuration) section.
## :heavy_plus_sign: PHP Extension Support ## :heavy_plus_sign: PHP Extension Support
@@ -162,7 +155,7 @@ PHP extensions can be set up using the `extensions` input. It accepts a `string`
- Extensions installed along with PHP if specified are enabled. - Extensions installed along with PHP if specified are enabled.
- Specific versions of extensions available on `PECL` can be set up by suffixing the extension's name with the version. This is useful for installing old versions of extensions which support end-of-life PHP versions. - Specific versions of extensions available on `PECL` can be set up by suffixing the extension's name with the version. This is useful for installing old versions of extensions which support end of life PHP versions.
```yaml ```yaml
- name: Setup PHP with specific version of PECL extension - name: Setup PHP with specific version of PECL extension
@@ -174,8 +167,6 @@ PHP extensions can be set up using the `extensions` input. It accepts a `string`
- Extensions with pre-release versions available on `PECL` can be set up by suffixing the extension's name with its state i.e `alpha`, `beta`, `devel` or `snapshot`. - Extensions with pre-release versions available on `PECL` can be set up by suffixing the extension's name with its state i.e `alpha`, `beta`, `devel` or `snapshot`.
This sets the minimum stability. The newest release with that stability or a more stable state is selected.
```yaml ```yaml
- name: Setup PHP with pre-release PECL extension - name: Setup PHP with pre-release PECL extension
uses: shivammathur/setup-php@v2 uses: shivammathur/setup-php@v2
@@ -189,14 +180,14 @@ PHP extensions can be set up using the `extensions` input. It accepts a `string`
- Shared extensions can be disabled by prefixing them with a `:`. All extensions depending on the specified extension will also be disabled. - Shared extensions can be disabled by prefixing them with a `:`. All extensions depending on the specified extension will also be disabled.
```yaml ```yaml
- name: Setup PHP and disable mbstring - name: Setup PHP and disable opcache
uses: shivammathur/setup-php@v2 uses: shivammathur/setup-php@v2
with: with:
php-version: '8.5' php-version: '8.5'
extensions: :mbstring extensions: :mbstring
``` ```
- All shared extensions can be disabled by specifying `none`. When `none` is specified along with other extensions, it is hoisted to the start of the input. So, all the shared extensions will be disabled first, then the rest of the extensions in the input will be processed. - All shared extensions can be disabled by specifying `none`. When `none` is specified along with other extensions, it is hoisted to the start of the input. So, all the shared extensions will be disabled first, then rest of the extensions in the input will be processed.
This disables all core and third-party shared extensions and thus, can break some tools that need them. Required extensions are enabled again when the tools are set up on a best-effort basis. So it is recommended to add the extensions required for your tools after `none` in the `extensions` input to avoid any issues. This disables all core and third-party shared extensions and thus, can break some tools that need them. Required extensions are enabled again when the tools are set up on a best-effort basis. So it is recommended to add the extensions required for your tools after `none` in the `extensions` input to avoid any issues.
@@ -225,7 +216,7 @@ This disables all core and third-party shared extensions and thus, can break som
- `event`, `gearman`, `geos` and `relay` on `Ubuntu` and `macOS`. - `event`, `gearman`, `geos` and `relay` on `Ubuntu` and `macOS`.
- `blackfire`, `couchbase`, `ibm_db2`, `ioncube`, `oci8`, `pdo_firebird`, `pdo_ibm`, `pdo_oci`, `pecl_http`, `phalcon3`, `phalcon4`, `phalcon5`, and `zephir_parser` on all supported OS. - `blackfire`, `couchbase`, `ibm_db2`, `ioncube`, `oci8`, `pdo_firebird`, `pdo_ibm`, `pdo_oci`, `pecl_http`, `phalcon3`, `phalcon4`, `phalcon5`, and `zephir_parser` on all supported OS.
- By default, extensions which cannot be added or disabled gracefully leave an error message in the logs. The execution is not interrupted. To change this behaviour you can set `fail-fast` flag to `true`. - By default, extensions which cannot be added or disabled gracefully leave an error message in the logs, the execution is not interrupted. To change this behaviour you can set `fail-fast` flag to `true`.
```yaml ```yaml
- name: Setup PHP with fail-fast - name: Setup PHP with fail-fast
@@ -241,7 +232,7 @@ This disables all core and third-party shared extensions and thus, can break som
These tools can be set up globally using the `tools` input. It accepts a string in csv-format. These tools can be set up globally using the `tools` input. It accepts a string in csv-format.
[`backward-compatibility-check`], [`behat`], [`blackfire`], [`blackfire-player`], [`box`], [`castor`], [`churn`], [`codeception`], [`composer`], [`composer-dependency-analyser`], [`composer-normalize`], [`composer-prefetcher`], [`composer-require-checker`], [`composer-unused`], [`cpx`], [`cs2pr`], [`deployer`], [`ecs`], [`flex`], [`grpc_php_plugin`], [`infection`], [`laravel-cloud`] or [`cloud-cli`], [`mago`], [`name-collision-detector`], [`parallel-lint`], [`pecl`], [`phan`], [`phing`], [`phinx`], [`phive`], [`php-config`], [`php-cs-fixer`], [`php-scoper`], [`phpcbf`], [`phpcpd`], [`phpcs`], [`phpdoc`] or [`phpDocumentor`], [`phpize`], [`phplint`], [`phpmd`], [`phpspec`], [`phpstan`], [`phpunit`], [`phpunit-bridge`], [`phpunit-polyfills`], [`pie`], [`pint`], [`prestissimo`], [`protoc`], [`psalm`], [`rector`], [`symfony`] or [`symfony-cli`], [`vapor`] or [`vapor-cli`], [`wp`] or [`wp-cli`] [`backward-compatibility-check`], [`behat`], [`blackfire`], [`blackfire-player`], [`box`], [`castor`], [`churn`], [`codeception`], [`composer`], [`composer-dependency-analyser`], [`composer-normalize`], [`composer-prefetcher`], [`composer-require-checker`], [`composer-unused`], [`cs2pr`], [`deployer`], [`ecs`], [`flex`], [`grpc_php_plugin`], [`infection`], [`mago`], [`name-collision-detector`], [`parallel-lint`], [`pecl`], [`phan`], [`phing`], [`phinx`], [`phive`], [`php-config`], [`php-cs-fixer`], [`php-scoper`], [`phpcbf`], [`phpcpd`], [`phpcs`], [`phpdoc`] or [`phpDocumentor`], [`phpize`], [`phplint`], [`phpmd`], [`phpspec`], [`phpstan`], [`phpunit`], [`phpunit-bridge`], [`phpunit-polyfills`], [`pie`], [`pint`], [`prestissimo`], [`protoc`], [`psalm`], [`rector`], [`symfony`] or [`symfony-cli`], [`vapor`] or [`vapor-cli`], [`wp`] or [`wp-cli`]
```yaml ```yaml
- name: Setup PHP with tools - name: Setup PHP with tools
@@ -251,7 +242,7 @@ These tools can be set up globally using the `tools` input. It accepts a string
tools: php-cs-fixer, phpunit tools: php-cs-fixer, phpunit
``` ```
- In addition to the above tools, any composer tool or package can also be set up globally by specifying it as `vendor/package` matching the listing on Packagist. This format accepts the same [version constraints](https://getcomposer.org/doc/articles/versions.md#writing-version-constraints "Composer version constraints") as `composer`. - In addition to above tools any composer tool or package can also be set up globally by specifying it as `vendor/package` matching the listing on Packagist. This format accepts the same [version constraints](https://getcomposer.org/doc/articles/versions.md#writing-version-constraints "Composer version constraints") as `composer`.
```yaml ```yaml
- name: Setup PHP with tools - name: Setup PHP with tools
@@ -268,19 +259,7 @@ These tools can be set up globally using the `tools` input. It accepts a string
- Major version. For example `tool:1` or `tool:1.x`. - Major version. For example `tool:1` or `tool:1.x`.
- Major and minor version. For example `tool:1.2` or `tool:1.2.x`. - Major and minor version. For example `tool:1.2` or `tool:1.2.x`.
When you specify just the major version or the version in `major.minor` format, the latest patch version matching the input will be set up. When you specify just the major version or the version in `major.minor` format, the latest patch version matching the input will be setup.
- To harden your workflow against supply chain attacks, you can pin a tool to a checksum in the form `tool:version@sha256:<hash>` or `tool:version@sha512:<hash>`. The downloaded tool is verified against the checksum and it is not set up if the verification fails, even if the tool is served from the tools cache.
```yaml
- name: Setup PHP with tools pinned to a checksum
uses: shivammathur/setup-php@v2
with:
php-version: '8.5'
tools: composer:2.9.8@sha256:59b2c50e10cafa0d8efc19ede9a326d782f096c674a26baf98cf042ce23de890
```
Checksum verification is supported only for tools downloaded as phar archives with a full version, such as `tool:1.2.3` or `tool:1.2.3-beta1`. Specifying a checksum with an omitted version, a variable tag such as `latest`, `stable`, `preview` or `snapshot`, or a partial version such as `2`, `2.x`, `2.9` or `2.9.x` results in an error. These versions can resolve to different releases with different checksums. Checksum verification is not supported for tools set up using `composer` packages or custom package scripts; specifying a checksum for these tools also results in an error.
- The latest stable version of `composer` is set up by default. You can set up the required `composer` version by specifying the major version `v1` or `v2`, or the version in `major.minor` or `semver` format. Additionally, for composer `snapshot` and `preview` can also be specified to set up the respective releases. - The latest stable version of `composer` is set up by default. You can set up the required `composer` version by specifying the major version `v1` or `v2`, or the version in `major.minor` or `semver` format. Additionally, for composer `snapshot` and `preview` can also be specified to set up the respective releases.
@@ -320,10 +299,10 @@ These tools can be set up globally using the `tools` input. It accepts a string
fail-fast: true fail-fast: true
``` ```
- By default, `composer` blocks all its plugins. If you are using the `tools` input to install a composer plugin it will be added to the allowlist, alternatively if your dependencies have composer plugins, you can allow them by setting `COMPOSER_ALLOW_PLUGINS` that accepts a csv string of plugin names. - By default, `composer` blocks all its plugins. If you are using the `tools` input to install a composer plugin it will be added to the allow list, alternatively if your dependencies have composer plugins, you can allow them by setting `COMPOSER_ALLOW_PLUGINS` that accepts a csv string of plugin names.
```yaml ```yaml
- name: Setup PHP with allow composer plugins - name: Setup PHP with fail-fast
uses: shivammathur/setup-php@v2 uses: shivammathur/setup-php@v2
with: with:
php-version: '8.5' php-version: '8.5'
@@ -363,7 +342,7 @@ Runs on all [PHP versions supported](#tada-php-support "List of PHP versions sup
``` ```
- When you specify `coverage: xdebug`, the latest version of Xdebug compatible with the PHP version is set up by default. - When you specify `coverage: xdebug`, the latest version of Xdebug compatible with the PHP version is set up by default.
- If you need Xdebug 2.x on PHP 7.2, 7.3, or 7.4, you can specify `coverage: xdebug2`. - If you need Xdebug 2.x on PHP 7.2, 7.3 or 7.4, you can specify `coverage: xdebug2`.
```yaml ```yaml
- name: Setup PHP with Xdebug 2.x - name: Setup PHP with Xdebug 2.x
@@ -374,7 +353,7 @@ Runs on all [PHP versions supported](#tada-php-support "List of PHP versions sup
``` ```
> [!NOTE] > [!NOTE]
> Xdebug is enabled by default on Ubuntu GitHub Actions images, so if you are not using it in your workflows, it is recommended to disable it as that will have a positive impact on your PHP performance. Please refer to the [disable coverage](#disable-coverage) section for details. > Xdebug is enabled by default on Ubuntu GitHub Actions images, so if you are not using it in your workflow it is recommended to disable it as that will have a positive impact on your PHP performance. Please refer to the [disable coverage](#disable-coverage) section for details.
### PCOV ### PCOV
@@ -393,7 +372,7 @@ Runs on PHP 7.1 and newer PHP versions.
``` ```
- PHPUnit 8.x and above support PCOV out of the box. - PHPUnit 8.x and above support PCOV out of the box.
- If you are using PHPUnit 5.x, 6.x, or 7.x, you need to set up `pcov/clobber` before executing your tests. - If you are using PHPUnit 5.x, 6.x or 7.x, you need to set up `pcov/clobber` before executing your tests.
```yaml ```yaml
- name: Setup PCOV - name: Setup PCOV
@@ -411,7 +390,7 @@ Disable coverage for these reasons:
- You are not generating coverage reports while testing. - You are not generating coverage reports while testing.
- You are using `phpdbg` for running your tests. - You are using `phpdbg` for running your tests.
- You are profiling your code using `blackfire`. - You are profiling your code using `blackfire`.
- You are using PHP in JIT mode. Please refer to the [JIT configuration](#jit-configuration) section for more details. - You are using PHP in JIT mode. Please refer to [JIT configuration](#jit-configuration) section for more details.
```yaml ```yaml
- name: Setup PHP with no coverage driver - name: Setup PHP with no coverage driver
@@ -433,8 +412,7 @@ Disable coverage for these reasons:
- Accepts a `string`. For example `'8.5'`. - Accepts a `string`. For example `'8.5'`.
- Accepts `lowest` to set up the lowest supported PHP version. - Accepts `lowest` to set up the lowest supported PHP version.
- Accepts `highest` or `latest` to set up the latest stable PHP version. - Accepts `highest` or `latest` to set up the latest stable PHP version.
- Accepts `nightly` to set up a nightly build of the next PHP release (`8.6`). - Accepts `nightly` to set up a nightly build from the master branch of PHP.
- Accepts `master` to set up a nightly build from the master branch of PHP (`8.7`).
- Accepts `pre-installed` to set up the highest pre-installed PHP version. You can combine this with `update: true` to update the pre-installed PHP version. - Accepts `pre-installed` to set up the highest pre-installed PHP version. You can combine this with `update: true` to update the pre-installed PHP version.
- Accepts the format `d.x`, where `d` is the major version. For example `5.x`, `7.x` and `8.x`. - Accepts the format `d.x`, where `d` is the major version. For example `5.x`, `7.x` and `8.x`.
- See [PHP support](#tada-php-support) for the supported PHP versions. - See [PHP support](#tada-php-support) for the supported PHP versions.
@@ -536,13 +514,6 @@ On GitHub Actions you can assign the `setup-php` step an `id`, you can use the s
- By default, it is set to `false`. - By default, it is set to `false`.
- See [force update setup](#force-update-setup) for more info. - See [force update setup](#force-update-setup) for more info.
#### `verbose` (optional)
- Specify to enable verbose output.
- Accepts `true`, `false`, `v`, `vv` and `vvv`.
- By default, it is set to `false`.
- See [verbose setup](#verbose-setup) for more info.
See below for more info. See below for more info.
### Basic Setup ### Basic Setup
@@ -591,7 +562,7 @@ jobs:
### Nightly Build Setup ### Nightly Build Setup
> Set up a nightly build of `PHP 8.6` or `PHP 8.7`. > Set up a nightly build of `PHP 8.6`.
- These PHP versions are currently in active development and might contain bugs and breaking changes. - These PHP versions are currently in active development and might contain bugs and breaking changes.
- Some user space extensions might not support these versions currently. - Some user space extensions might not support these versions currently.
@@ -601,7 +572,7 @@ steps:
- name: Setup nightly PHP - name: Setup nightly PHP
uses: shivammathur/setup-php@v2 uses: shivammathur/setup-php@v2
with: with:
php-version: '8.7' php-version: '8.6'
extensions: mbstring extensions: mbstring
ini-values: post_max_size=256M, max_execution_time=180 ini-values: post_max_size=256M, max_execution_time=180
coverage: xdebug coverage: xdebug
@@ -671,24 +642,18 @@ jobs:
> Debug your workflow > Debug your workflow
- Set the `verbose` environment variable to `true` or `v` to show command output. To debug any issues, you can use the `verbose` tag instead of `v2`.
- Set `verbose` to `vv` or `vvv` to also enable `set -x` on Linux and macOS.
- On Windows, `vv` enables `Set-PSDebug -Trace 1` and `vvv` enables `Set-PSDebug -Trace 2`.
- Enabling [GitHub Actions debug logging](https://docs.github.com/en/actions/how-tos/monitor-workflows/enable-debug-logging) (`RUNNER_DEBUG=1`) also enables verbose mode.
- The `verbose` and `more-verbose` tags have been deprecated and will be discontinued in the next major release.
```yaml ```yaml
- name: Setup PHP with logs - name: Setup PHP with logs
uses: shivammathur/setup-php@v2 uses: shivammathur/setup-php@verbose
with: with:
php-version: '8.5' php-version: '8.5'
env:
verbose: true
``` ```
### Multi-Arch Setup ### Multi-Arch Setup
> Set up PHP on multiple architectures on Ubuntu GitHub Runners. > Set up PHP on multiple architecture on Ubuntu GitHub Runners.
- `PHP 5.6` to `PHP 8.5` are supported by `setup-php` on multiple architecture on `Ubuntu` and `Debian`. - `PHP 5.6` to `PHP 8.5` are supported by `setup-php` on multiple architecture on `Ubuntu` and `Debian`.
- For this, you can use `shivammathur/node` images as containers. These have compatible `Nodejs` and `PHP` installed for `setup-php`. - For this, you can use `shivammathur/node` images as containers. These have compatible `Nodejs` and `PHP` installed for `setup-php`.
@@ -718,7 +683,7 @@ jobs:
> Set up PHP on a self-hosted runner. > Set up PHP on a self-hosted runner.
- To set up a containerized self-hosted runner, refer to the following guides as per your base operating system. - To set up a containerised self-hosted runner, refer to the following guides as per your base operating system.
- [Linux](https://github.com/shivammathur/setup-php/wiki/Dockerized-self-hosted-runner-on-Linux) - [Linux](https://github.com/shivammathur/setup-php/wiki/Dockerized-self-hosted-runner-on-Linux)
- [Windows](https://github.com/shivammathur/setup-php/wiki/Dockerized-self-hosted-runner-on-Windows) - [Windows](https://github.com/shivammathur/setup-php/wiki/Dockerized-self-hosted-runner-on-Windows)
@@ -745,7 +710,7 @@ jobs:
``` ```
> [!NOTE] > [!NOTE]
> - Do not set up multiple self-hosted runners on a single server instance as parallel workflows will conflict with each other. > - Do not set up multiple self-hosted runners on a single server instance as parallel workflow will conflict with each other.
> - Do not set up self-hosted runners on the side of your development environment or your production server. > - Do not set up self-hosted runners on the side of your development environment or your production server.
> - Avoid using the same labels for your `self-hosted` runners which are used by `GitHub-hosted` runners. > - Avoid using the same labels for your `self-hosted` runners which are used by `GitHub-hosted` runners.
@@ -788,7 +753,7 @@ act -P ubuntu-22.04=shivammathur/node:22.04
- By default, `opcache.jit=1235` and `opcache.jit_buffer_size=256M` (`opcache.jit_buffer_size=128M` on ARM-based environments) are set which can be changed using `ini-values` input. - By default, `opcache.jit=1235` and `opcache.jit_buffer_size=256M` (`opcache.jit_buffer_size=128M` on ARM-based environments) are set which can be changed using `ini-values` input.
- For detailed information about JIT related directives refer to the [`official PHP documentation`](https://www.php.net/manual/en/opcache.configuration.php#ini.opcache.jit "opcache.jit documentation"). - For detailed information about JIT related directives refer to the [`official PHP documentation`](https://www.php.net/manual/en/opcache.configuration.php#ini.opcache.jit "opcache.jit documentation").
For example, to enable JIT in `tracing` mode with buffer size of `64 MB`. For example to enable JIT in `tracing` mode with buffer size of `64 MB`.
```yaml ```yaml
- name: Setup PHP with JIT in tracing mode - name: Setup PHP with JIT in tracing mode
@@ -868,7 +833,7 @@ If you use Private Packagist for your private composer dependencies, you can set
### Manual Composer Authentication ### Manual Composer Authentication
In addition to GitHub or Private Packagist, if you want to authenticate private repositories hosted elsewhere, you can set the `COMPOSER_AUTH_JSON` environment variable with the authentication methods and the credentials in JSON format. In addition to GitHub or Private Packagist, if you want to authenticate private repositories hosted elsewhere, you can set the `COMPOSER_AUTH_JSON` environment variable with the authentication methods and the credentials in json format.
Please refer to the authentication section in [`composer documentation`](https://getcomposer.org/doc/articles/authentication-for-private-packages.md "composer documentation") for more details. Please refer to the authentication section in [`composer documentation`](https://getcomposer.org/doc/articles/authentication-for-private-packages.md "composer documentation") for more details.
```yaml ```yaml
@@ -914,7 +879,7 @@ Problem matchers are `json` configurations which identify errors and warnings in
#### PHP #### PHP
Set up problem matchers for your `PHP` output by adding this step after the `setup-php` step. Setup problem matchers for your `PHP` output by adding this step after the `setup-php` step.
```yaml ```yaml
- name: Setup problem matchers for PHP - name: Setup problem matchers for PHP
@@ -923,7 +888,7 @@ Set up problem matchers for your `PHP` output by adding this step after the `set
#### PHPUnit #### PHPUnit
Set up problem matchers for your `PHPUnit` output by adding this step after the `setup-php` step. Setup problem matchers for your `PHPUnit` output by adding this step after the `setup-php` step.
```yaml ```yaml
- name: Setup problem matchers for PHPUnit - name: Setup problem matchers for PHPUnit
@@ -1005,7 +970,7 @@ Examples of using `setup-php` with various PHP frameworks and packages.
| Symfony with `PostgreSQL` | `ubuntu` | [symfony-postgres.yml](./examples/symfony-postgres.yml "GitHub Action for Symfony with PostgreSQL") | | Symfony with `PostgreSQL` | `ubuntu` | [symfony-postgres.yml](./examples/symfony-postgres.yml "GitHub Action for Symfony with PostgreSQL") |
| Symfony without services | `macOS`, `ubuntu` and `windows` | [symfony.yml](./examples/symfony.yml "GitHub Action for Symfony without services") | | Symfony without services | `macOS`, `ubuntu` and `windows` | [symfony.yml](./examples/symfony.yml "GitHub Action for Symfony without services") |
| WordPress plugin | `ubuntu` | [wordpress.yml](./examples/wordpress.yml "GitHub Action for WordPress plugins") | | WordPress plugin | `ubuntu` | [wordpress.yml](./examples/wordpress.yml "GitHub Action for WordPress plugins") |
| WordPress with Roots/Bedrock | `ubuntu` | [bedrock.yml](./examples/bedrock.yml "GitHub Action for WordPress development using @roots/bedrock") | | WordPress with Roots/Bedrock | `ubuntu` | [bedrock.yml](./examples/bedrock.yml "GitHub Action for WordPress development using @roots/bedrock") |
| WordPress with Roots/Sage | `ubuntu` | [sage.yml](./examples/sage.yml "GitHub Action for WordPress development using @roots/sage") | | WordPress with Roots/Sage | `ubuntu` | [sage.yml](./examples/sage.yml "GitHub Action for WordPress development using @roots/sage") |
| Yii3 web application with `MySQL` | `ubuntu` | [yii3-mysql.yml](./examples/yii3-mysql.yml "GitHub Action for Yii3 web application with MySQL") | | Yii3 web application with `MySQL` | `ubuntu` | [yii3-mysql.yml](./examples/yii3-mysql.yml "GitHub Action for Yii3 web application with MySQL") |
| Yii3 web application with `PostgreSQL` | `ubuntu` | [yii3-postgres.yml](./examples/yii3-postgres.yml "GitHub Action for Yii3 web application with PostgreSQL") | | Yii3 web application with `PostgreSQL` | `ubuntu` | [yii3-postgres.yml](./examples/yii3-postgres.yml "GitHub Action for Yii3 web application with PostgreSQL") |
@@ -1013,12 +978,12 @@ Examples of using `setup-php` with various PHP frameworks and packages.
## :bookmark: Versioning ## :bookmark: Versioning
- Use the `v2` tag as `setup-php` version. It is a rolling tag and is synced with the latest minor and patch releases. With `v2` you automatically get the bug fixes, security patches, new features, and support for latest PHP releases. - Use the `v2` tag as `setup-php` version. It is a rolling tag and is synced with the latest minor and patch releases. With `v2` you automatically get the bug fixes, security patches, new features and support for latest PHP releases.
- Semantic release versions can also be used. It is recommended to [use dependabot](https://docs.github.com/en/github/administering-a-repository/keeping-your-actions-up-to-date-with-github-dependabot "Setup Dependabot with GitHub Actions") with semantic versioning to keep the actions in your workflows up to date. - Semantic release versions can also be used. It is recommended to [use dependabot](https://docs.github.com/en/github/administering-a-repository/keeping-your-actions-up-to-date-with-github-dependabot "Setup Dependabot with GitHub Actions") with semantic versioning to keep the actions in your workflows up to date.
- Commit SHA can also be used, but is not recommended unless you set up tooling to update them with each release of the action. - Commit SHA can also be used, but are not recommended unless you set up tooling to update them with each release of the action.
- A new major version of the action will only be tagged when there are breaking changes in the setup-php API i.e. - inputs, outputs, and environment flags. - A new major version of the action will only be tagged when there are breaking changes in the setup-php API i.e. inputs, outputs, and environment flags.
- For debugging any issues, use the [`verbose` environment variable](#verbose-setup). - For debugging any issues `verbose` tag can be used temporarily. It outputs all the logs and is also synced with the latest releases.
- It is highly discouraged to use the `main` branch as the version, it might break your workflow after major releases as they have breaking changes. - It is highly discouraged to use the `main` branch as version, it might break your workflow after major releases as they have breaking changes.
- If you are using the `v1` tag or a `1.x.y` version, you should [switch to v2](https://github.com/shivammathur/setup-php/wiki/Switch-to-v2 "Guide for switching from setup-php v1 to v2") as `v1` is not supported anymore. - If you are using the `v1` tag or a `1.x.y` version, you should [switch to v2](https://github.com/shivammathur/setup-php/wiki/Switch-to-v2 "Guide for switching from setup-php v1 to v2") as `v1` is not supported anymore.
## :scroll: License ## :scroll: License
@@ -1080,7 +1045,7 @@ Many users and organizations support setup-php via [GitHub Sponsors](https://git
<a href="https://github.com/sponsors/shivammathur"><img src="https://setup-php.com/sponsors.svg?" alt="Sponsor shivammathur"></a> <a href="https://github.com/sponsors/shivammathur"><img src="https://setup-php.com/sponsors.svg?" alt="Sponsor shivammathur"></a>
- If you use setup-php, please consider starring the project and sharing it. - If you use setup-php, please consider starring the project and share it.
- If you blog, please share your experience of using `setup-php`. - If you blog, please share your experience of using `setup-php`.
- Please [reach out](mailto:contact@setup-php.com) if you have any questions about sponsoring setup-php. - Please [reach out](mailto:contact@setup-php.com) if you have any questions about sponsoring setup-php.
@@ -1116,7 +1081,6 @@ Many users and organizations support setup-php via [GitHub Sponsors](https://git
[`box`]: https://github.com/humbug/box [`box`]: https://github.com/humbug/box
[`castor`]: https://github.com/jolicode/castor [`castor`]: https://github.com/jolicode/castor
[`churn`]: https://github.com/bmitch/churn-php [`churn`]: https://github.com/bmitch/churn-php
[`cloud-cli`]: https://cloud.laravel.com/docs/api/cli
[`codeception`]: https://codeception.com/ [`codeception`]: https://codeception.com/
[`composer`]: https://getcomposer.org/ [`composer`]: https://getcomposer.org/
[`composer-dependency-analyser`]: https://github.com/shipmonk-rnd/composer-dependency-analyser [`composer-dependency-analyser`]: https://github.com/shipmonk-rnd/composer-dependency-analyser
@@ -1124,14 +1088,12 @@ Many users and organizations support setup-php via [GitHub Sponsors](https://git
[`composer-prefetcher`]: https://github.com/narrowspark/automatic-composer-prefetcher [`composer-prefetcher`]: https://github.com/narrowspark/automatic-composer-prefetcher
[`composer-require-checker`]: https://github.com/maglnet/ComposerRequireChecker [`composer-require-checker`]: https://github.com/maglnet/ComposerRequireChecker
[`composer-unused`]: https://github.com/composer-unused/composer-unused [`composer-unused`]: https://github.com/composer-unused/composer-unused
[`cpx`]: https://github.com/laravel/cpx
[`cs2pr`]: https://github.com/staabm/annotate-pull-request-from-checkstyle [`cs2pr`]: https://github.com/staabm/annotate-pull-request-from-checkstyle
[`deployer`]: https://deployer.org/ [`deployer`]: https://deployer.org/
[`ecs`]: https://github.com/easy-coding-standard/easy-coding-standard [`ecs`]: https://github.com/easy-coding-standard/easy-coding-standard
[`flex`]: https://github.com/symfony/flex [`flex`]: https://github.com/symfony/flex
[`grpc_php_plugin`]: https://grpc.io/ [`grpc_php_plugin`]: https://grpc.io/
[`infection`]: https://infection.github.io/ [`infection`]: https://infection.github.io/
[`laravel-cloud`]: https://cloud.laravel.com/docs/api/cli
[`mago`]: https://github.com/carthage-software/mago [`mago`]: https://github.com/carthage-software/mago
[`name-collision-detector`]: https://github.com/shipmonk/name-collision-detector [`name-collision-detector`]: https://github.com/shipmonk/name-collision-detector
[`parallel-lint`]: https://github.com/php-parallel-lint/PHP-Parallel-Lint [`parallel-lint`]: https://github.com/php-parallel-lint/PHP-Parallel-Lint
+1 -1
View File
@@ -1,4 +1,4 @@
import * as config from '../src/config.js'; import * as config from '../src/config';
describe('Config tests', () => { describe('Config tests', () => {
it.each` it.each`
+1 -2
View File
@@ -1,5 +1,4 @@
import {jest} from '@jest/globals'; import * as core from '../src/core';
import * as core from '../src/core.js';
describe('Core tests', () => { describe('Core tests', () => {
const originalEnv = process.env; const originalEnv = process.env;
+2 -2
View File
@@ -1,4 +1,4 @@
import * as coverage from '../src/coverage.js'; import * as coverage from '../src/coverage';
describe('Config tests', () => { describe('Config tests', () => {
it.each` it.each`
@@ -21,7 +21,7 @@ describe('Config tests', () => {
${'xdebug'} | ${'7.4'} | ${'linux'} | ${'Xdebug $xdebug_version enabled as coverage driver'} ${'xdebug'} | ${'7.4'} | ${'linux'} | ${'Xdebug $xdebug_version enabled as coverage driver'}
${'xdebug'} | ${'7.4'} | ${'darwin'} | ${'add_brew_extension xdebug'} ${'xdebug'} | ${'7.4'} | ${'darwin'} | ${'add_brew_extension xdebug'}
${'xdebug3'} | ${'7.1'} | ${'darwin'} | ${'xdebug3 is not supported on PHP 7.1'} ${'xdebug3'} | ${'7.1'} | ${'darwin'} | ${'xdebug3 is not supported on PHP 7.1'}
${'xdebug2'} | ${'7.4'} | ${'darwin'} | ${'add_brew_extension xdebug2 zend_extension 2.9.8'} ${'xdebug2'} | ${'7.4'} | ${'darwin'} | ${'add_brew_extension xdebug2'}
${'xdebug2'} | ${'8.0'} | ${'darwin'} | ${'xdebug2 is not supported on PHP 8.0'} ${'xdebug2'} | ${'8.0'} | ${'darwin'} | ${'xdebug2 is not supported on PHP 8.0'}
${'none'} | ${'7.4'} | ${'win32'} | ${'Disable-Extension xdebug false,Disable-Extension pcov false'} ${'none'} | ${'7.4'} | ${'win32'} | ${'Disable-Extension xdebug false,Disable-Extension pcov false'}
${'none'} | ${'7.4'} | ${'linux'} | ${'disable_extension xdebug false,disable_extension pcov false'} ${'none'} | ${'7.4'} | ${'linux'} | ${'disable_extension xdebug false,disable_extension pcov false'}
+1 -3
View File
@@ -1,5 +1,5 @@
import * as fs from 'fs'; import * as fs from 'fs';
import * as extensions from '../src/extensions.js'; import * as extensions from '../src/extensions';
describe('Extension tests', () => { describe('Extension tests', () => {
it.each` it.each`
@@ -7,7 +7,6 @@ describe('Extension tests', () => {
${'none'} | ${'7.4'} | ${'Disable-AllShared'} ${'none'} | ${'7.4'} | ${'Disable-AllShared'}
${':intl'} | ${'7.4'} | ${'Disable-Extension intl'} ${':intl'} | ${'7.4'} | ${'Disable-Extension intl'}
${'ast-beta'} | ${'7.4'} | ${'Add-Extension ast beta'} ${'ast-beta'} | ${'7.4'} | ${'Add-Extension ast beta'}
${'ast-stable'} | ${'7.4'} | ${'Add-Extension ast stable'}
${'blackfire'} | ${'7.3'} | ${'Add-Blackfire blackfire'} ${'blackfire'} | ${'7.3'} | ${'Add-Blackfire blackfire'}
${'blackfire-1.31.0'} | ${'7.3'} | ${'Add-Blackfire blackfire-1.31.0'} ${'blackfire-1.31.0'} | ${'7.3'} | ${'Add-Blackfire blackfire-1.31.0'}
${'grpc-1.2.3'} | ${'7.4'} | ${'Add-Extension grpc stable 1.2.3'} ${'grpc-1.2.3'} | ${'7.4'} | ${'Add-Extension grpc stable 1.2.3'}
@@ -108,7 +107,6 @@ describe('Extension tests', () => {
${'pecl_http'} | ${'7.3'} | ${'add_http'} ${'pecl_http'} | ${'7.3'} | ${'add_http'}
${'relay-1.2.3'} | ${'7.4'} | ${'add_relay relay-1.2.3'} ${'relay-1.2.3'} | ${'7.4'} | ${'add_relay relay-1.2.3'}
${'sqlite'} | ${'7.2'} | ${'add_extension sqlite3'} ${'sqlite'} | ${'7.2'} | ${'add_extension sqlite3'}
${'xdebug2'} | ${'7.4'} | ${'add_brew_extension xdebug2 zend_extension 2.9.8'}
${'zephir_parser-v1.2.3'} | ${'7.2'} | ${'add_zephir_parser zephir_parser-v1.2.3'} ${'zephir_parser-v1.2.3'} | ${'7.2'} | ${'add_zephir_parser zephir_parser-v1.2.3'}
`( `(
'checking addExtensionOnDarwin for extension $extension on version $version', 'checking addExtensionOnDarwin for extension $extension on version $version',
+5 -17
View File
@@ -1,19 +1,6 @@
import * as fetch from '../src/fetch.js'; import * as fetch from '../src/fetch';
import nock from 'nock'; import nock from 'nock';
beforeAll(() => nock.disableNetConnect());
afterEach(() => {
const pending = nock.pendingMocks();
nock.cleanAll();
expect(pending).toEqual([]);
});
afterAll(() => {
nock.enableNetConnect();
nock.restore();
});
it('checking fetch', async () => { it('checking fetch', async () => {
const host_url = 'https://example.com'; const host_url = 'https://example.com';
const manifest_url = host_url + '/manifest'; const manifest_url = host_url + '/manifest';
@@ -22,8 +9,9 @@ it('checking fetch', async () => {
nock(host_url) nock(host_url)
.get('/manifest') .get('/manifest')
.reply(200, {latest: 'latest'}) .reply(200, {latest: 'latest'})
.get('/manifest') .get('/manifest', '', {
.matchHeader('authorization', 'Bearer invalid_token') reqheaders: {authorization: 'Bearer invalid_token'}
})
.reply(401, {error: '401: Unauthorized'}) .reply(401, {error: '401: Unauthorized'})
.get('/ping') .get('/ping')
.twice() .twice()
@@ -48,7 +36,7 @@ it('checking fetch', async () => {
expect(response.data).toBe(undefined); expect(response.data).toBe(undefined);
response = await fetch.fetch(manifest_url, 'invalid_token'); response = await fetch.fetch(manifest_url, 'invalid_token');
expect(response.error).toBe('401: Unauthorized'); expect(response.error).not.toBe(undefined);
expect(response.data).toBe(undefined); expect(response.data).toBe(undefined);
response = await fetch.fetch(host_url + '/error'); response = await fetch.fetch(host_url + '/error');
+5 -7
View File
@@ -1,11 +1,12 @@
import {jest} from '@jest/globals'; import * as install from '../src/install';
import * as utils from '../src/utils';
/** /**
* Mock install.ts * Mock install.ts
*/ */
jest.unstable_mockModule('../src/install.js', () => ({ jest.mock('../src/install', () => ({
getScript: jest getScript: jest
.fn<typeof import('../src/install.js').getScript>() .fn()
.mockImplementation(async (os: string): Promise<string> => { .mockImplementation(async (os: string): Promise<string> => {
const filename = os + (await utils.scriptExtension(os)); const filename = os + (await utils.scriptExtension(os));
const version: string = await utils.parseVersion( const version: string = await utils.parseVersion(
@@ -35,7 +36,7 @@ jest.unstable_mockModule('../src/install.js', () => ({
/** /**
* Mock fetch.ts * Mock fetch.ts
*/ */
jest.unstable_mockModule('../src/fetch.js', () => ({ jest.mock('../src/fetch', () => ({
fetch: jest.fn().mockImplementation(() => { fetch: jest.fn().mockImplementation(() => {
return { return {
data: '{ "latest": "8.3", "lowest": "8.1", "highest": "8.3", "nightly": "8.4", "5.x": "5.6" }' data: '{ "latest": "8.3", "lowest": "8.1", "highest": "8.3", "nightly": "8.4", "5.x": "5.6" }'
@@ -43,9 +44,6 @@ jest.unstable_mockModule('../src/fetch.js', () => ({
}) })
})); }));
const utils = await import('../src/utils.js');
const install = await import('../src/install.js');
describe('Install', () => { describe('Install', () => {
it.each` it.each`
version | os | extension_csv | ini_file | ini_values_csv | coverage_driver | tools | output version | os | extension_csv | ini_file | ini_values_csv | coverage_driver | tools | output
+1 -14
View File
@@ -1,19 +1,6 @@
import * as packagist from '../src/packagist.js'; import * as packagist from '../src/packagist';
import nock from 'nock'; import nock from 'nock';
beforeAll(() => nock.disableNetConnect());
afterEach(() => {
const pending = nock.pendingMocks();
nock.cleanAll();
expect(pending).toEqual([]);
});
afterAll(() => {
nock.enableNetConnect();
nock.restore();
});
describe('search function', () => { describe('search function', () => {
const mockResponse = { const mockResponse = {
packages: { packages: {
+73 -246
View File
@@ -1,6 +1,6 @@
import {jest} from '@jest/globals'; import * as fs from 'fs';
import fs from 'fs'; import * as tools from '../src/tools';
import type {ToolData, ToolInput} from '../src/tools.js'; import {ToolData, ToolInput} from '../src/tools';
function getData(data: Partial<ToolData>): ToolData { function getData(data: Partial<ToolData>): ToolData {
const tool = data.tool || 'tool'; const tool = data.tool || 'tool';
@@ -40,12 +40,16 @@ function unsetComposerAuthEnv(): void {
/** /**
* Mock fetch.ts * Mock fetch.ts
*/ */
jest.unstable_mockModule('../src/fetch.js', () => ({ jest.mock('../src/fetch', () => ({
fetch: jest fetch: jest
.fn<typeof import('../src/fetch.js').fetch>() .fn()
.mockImplementation( .mockImplementation(
async (url: string, token?: string): Promise<Record<string, string>> => { async (url: string, token?: string): Promise<Record<string, string>> => {
if (url.includes('atom') && !url.includes('no-')) { if (url.includes('deployer')) {
return {
data: '[{"version": "1.2.3", "url": "https://deployer.org/releases/v1.2.3/deployer.phar"}]'
};
} else if (url.includes('atom') && !url.includes('no-')) {
return { return {
data: '"releases/tag/1.2.3", "releases/tag/3.2.1", "releases/tag/2.3.1"' data: '"releases/tag/1.2.3", "releases/tag/3.2.1", "releases/tag/2.3.1"'
}; };
@@ -82,9 +86,9 @@ jest.unstable_mockModule('../src/fetch.js', () => ({
) )
})); }));
jest.unstable_mockModule('../src/packagist.js', () => ({ jest.mock('../src/packagist', () => ({
search: jest search: jest
.fn<typeof import('../src/packagist.js').search>() .fn()
.mockImplementation( .mockImplementation(
async ( async (
package_name: string, package_name: string,
@@ -98,10 +102,6 @@ jest.unstable_mockModule('../src/packagist.js', () => ({
) )
})); }));
const tools = await import('../src/tools.js');
afterEach(() => jest.restoreAllMocks());
describe('Tools tests', () => { describe('Tools tests', () => {
it.each` it.each`
token | version token | version
@@ -222,51 +222,17 @@ describe('Tools tests', () => {
}); });
it.each` it.each`
release | expected_release | checksum | error input_list | filtered_list
${'tool:1.2.3'} | ${'tool:1.2.3'} | ${undefined} | ${undefined} ${'a, b'} | ${'composer, a, b'}
${'tool:1.2.3@sha256:' + 'a'.repeat(64)} | ${'tool:1.2.3'} | ${'sha256:' + 'a'.repeat(64)} | ${undefined} ${'a, b, composer'} | ${'composer, a, b'}
${'tool:1.2.3@sha256:' + 'A'.repeat(64)} | ${'tool:1.2.3'} | ${'sha256:' + 'a'.repeat(64)} | ${undefined} ${'a, b, composer:1.2.3'} | ${'composer:1.2.3, a, b'}
${'tool:1.2.3@SHA256:' + 'a'.repeat(64)} | ${'tool:1.2.3'} | ${'sha256:' + 'a'.repeat(64)} | ${undefined} ${'a, b, composer:v1.2.3'} | ${'composer:1.2.3, a, b'}
${'tool:1.2.3@sha512:' + 'b'.repeat(128)} | ${'tool:1.2.3'} | ${'sha512:' + 'b'.repeat(128)} | ${undefined} ${'a, b, composer:snapshot'} | ${'composer:snapshot, a, b'}
${'tool:v1.2.3-beta.1+build.2@sha256:' + 'a'.repeat(64)} | ${'tool:v1.2.3-beta.1+build.2'} | ${'sha256:' + 'a'.repeat(64)} | ${undefined} ${'a, b, composer:preview'} | ${'composer:preview, a, b'}
${'composer:2.9.8@sha256:' + 'c'.repeat(64)} | ${'composer:2.9.8'} | ${'sha256:' + 'c'.repeat(64)} | ${undefined} ${'a, b, composer:1'} | ${'composer:1, a, b'}
${'tool:1.2.3@sha256:xyz'} | ${'tool:1.2.3'} | ${undefined} | ${'Invalid sha256 checksum, expected 64 hexadecimal characters'} ${'a, b, composer:2'} | ${'composer:2, a, b'}
${'tool:1.2.3@sha256:' + 'a'.repeat(63)} | ${'tool:1.2.3'} | ${undefined} | ${'Invalid sha256 checksum, expected 64 hexadecimal characters'} ${'a, b, composer:v1'} | ${'composer:1, a, b'}
${'tool:1.2.3@sha512:' + 'b'.repeat(64)} | ${'tool:1.2.3'} | ${undefined} | ${'Invalid sha512 checksum, expected 128 hexadecimal characters'} ${'a, b, composer:v2'} | ${'composer:2, a, b'}
${'tool:1.2.3@sha384:' + 'b'.repeat(96)} | ${'tool:1.2.3'} | ${undefined} | ${'Unsupported checksum algorithm sha384, expected sha256 or sha512'}
${'tool:1.2.3@md5:' + 'b'.repeat(32)} | ${'tool:1.2.3'} | ${undefined} | ${'Unsupported checksum algorithm md5, expected sha256 or sha512'}
${'tool:1.2.3@sha256' + 'a'.repeat(64)} | ${'tool:1.2.3'} | ${undefined} | ${'Invalid checksum syntax, expected @sha256:<hash> or @sha512:<hash>'}
${'tool:1.0@dev'} | ${'tool:1.0@dev'} | ${undefined} | ${undefined}
`(
'checking extractChecksum: $release',
({release, expected_release, checksum, error}) => {
expect(tools.extractChecksum(release)).toStrictEqual({
release: expected_release,
...(checksum !== undefined && {checksum}),
...(error !== undefined && {error})
});
}
);
it.each`
input_list | filtered_list
${'a, b'} | ${'composer, a, b'}
${'a, b, composer'} | ${'composer, a, b'}
${'a, b, composer:1.2.3'} | ${'composer:1.2.3, a, b'}
${'a, b, composer:v1.2.3'} | ${'composer:1.2.3, a, b'}
${'a, b, composer:snapshot'} | ${'composer:snapshot, a, b'}
${'a, b, composer:preview'} | ${'composer:preview, a, b'}
${'a, b, composer:1'} | ${'composer:1, a, b'}
${'a, b, composer:2'} | ${'composer:2, a, b'}
${'a, b, composer:v1'} | ${'composer:1, a, b'}
${'a, b, composer:v2'} | ${'composer:2, a, b'}
${'a, b, composer:2.7.1@sha256:' + 'a'.repeat(64)} | ${'composer:2.7.1@sha256:' + 'a'.repeat(64) + ', a, b'}
${'a, b, composer:v2.7.1@sha256:' + 'a'.repeat(64)} | ${'composer:2.7.1@sha256:' + 'a'.repeat(64) + ', a, b'}
${'a, b, composer:2.7.1@SHA256:' + 'a'.repeat(64)} | ${'composer:2.7.1@SHA256:' + 'a'.repeat(64) + ', a, b'}
${'a, b, composer:2.7.1@sha384:' + 'a'.repeat(96)} | ${'composer:2.7.1@sha384:' + 'a'.repeat(96) + ', a, b'}
${'a, b, composer:2.7.1@md5:' + 'a'.repeat(32)} | ${'composer:2.7.1@md5:' + 'a'.repeat(32) + ', a, b'}
${'a, b, composer:2.7.1@sha256' + 'a'.repeat(64)} | ${'composer:2.7.1@sha256' + 'a'.repeat(64) + ', a, b'}
${'a, b, composer@sha256:' + 'a'.repeat(64)} | ${'composer@sha256:' + 'a'.repeat(64) + ', a, b'}
`('checking filterList $input_list', async ({input_list, filtered_list}) => { `('checking filterList $input_list', async ({input_list, filtered_list}) => {
expect(await tools.filterList(input_list.split(', '))).toStrictEqual( expect(await tools.filterList(input_list.split(', '))).toStrictEqual(
filtered_list.split(', ') filtered_list.split(', ')
@@ -338,23 +304,6 @@ describe('Tools tests', () => {
expect(await tools.addArchive(data)).toContain(script); expect(await tools.addArchive(data)).toContain(script);
}); });
it.each`
os | script
${'linux'} | ${'add_tool https://example.com/tool.phar tool "-v" sha256:' + 'a'.repeat(64)}
${'darwin'} | ${'add_tool https://example.com/tool.phar tool "-v" sha256:' + 'a'.repeat(64)}
${'win32'} | ${'Add-Tool https://example.com/tool.phar tool "-v" sha256:' + 'a'.repeat(64)}
`('checking addArchive with checksum: $os', async ({os, script}) => {
const data = getData({
tool: 'tool',
version: '1.2.3',
version_parameter: JSON.stringify('-v'),
os: os,
url: 'https://example.com/tool.phar'
});
data.checksum = 'sha256:' + 'a'.repeat(64);
expect(await tools.addArchive(data)).toContain(script);
});
it.each` it.each`
os | release | scope | script os | release | scope | script
${'linux'} | ${'tool:1.2.3'} | ${'global'} | ${'add_composer_tool tool tool:1.2.3 user/ global'} ${'linux'} | ${'tool:1.2.3'} | ${'global'} | ${'add_composer_tool tool tool:1.2.3 user/ global'}
@@ -381,56 +330,6 @@ describe('Tools tests', () => {
} }
); );
it.each`
release | resolved
${'phpstan'} | ${'latest/download'}
${'phpstan:0.12.68'} | ${'download/0.12.68'}
${'phpstan:^0.12.68'} | ${'download/0.12.68'}
${'phpstan:0.12'} | ${'download/1.2.3'}
${'phpstan:0.12.x'} | ${'download/1.2.3'}
${'phpstan:0.12.*'} | ${'download/1.2.3'}
`(
'resolving PHPStan PHAR fallback for $release',
async ({release, resolved}) => {
unsetComposerAuthEnv();
for (const os of ['linux', 'darwin', 'win32']) {
const data = await tools.getData(release, '8.0', os);
const script = await tools.addPackage(data);
expect(script).toContain(
'scoped https://github.com/phpstan/phpstan/releases/' +
resolved +
'/phpstan.phar "-V"'
);
expect(data.type).toBe('composer');
expect(data.release).toContain('phpstan');
}
}
);
it('keeps Composer available when the fallback version lookup fails', async () => {
process.env['GITHUB_TOKEN'] = 'invalid_token';
const data = await tools.getData('phpstan:0.12', '8.0', 'linux');
expect(await tools.addPackage(data)).toBe(
'add_composer_tool phpstan "phpstan:0.12.*" phpstan/ scoped'
);
unsetComposerAuthEnv();
});
it('uses fallback settings independently of the Composer repository', async () => {
const data = await tools.getData('vendor/tool:1.2.3', '8.0', 'linux', {
fallback: {
type: 'phar',
repository: 'releases/tool',
domain: 'https://example.com',
extension: '.phar',
version_prefix: 'v'
}
});
expect(await tools.addPackage(data)).toBe(
'add_composer_tool tool tool:1.2.3 vendor/ global https://example.com/releases/tool/v1.2.3/tool.phar ""'
);
});
it.each` it.each`
version | php_version | os | script version | php_version | os | script
${'latest'} | ${'8.0'} | ${'linux'} | ${'add_tool https://github.com/phar-io/phive/releases/download/3.2.1/phive-3.2.1.phar phive'} ${'latest'} | ${'8.0'} | ${'linux'} | ${'add_tool https://github.com/phar-io/phive/releases/download/3.2.1/phive-3.2.1.phar phive'}
@@ -481,15 +380,13 @@ describe('Tools tests', () => {
it.each` it.each`
version | url version | url
${'latest'} | ${'https://github.com/deployphp/deployer/releases/latest/download/deployer.phar,https://deployer.org/deployer.phar deployer'} ${'latest'} | ${'https://deployer.org/deployer.phar'}
${'7.5.12'} | ${'https://github.com/deployphp/deployer/releases/download/v7.5.12/deployer.phar,https://deployer.org/releases/v7.5.12/deployer.phar deployer'} ${'1.2.3'} | ${'https://deployer.org/releases/v1.2.3/deployer.phar'}
${'6.8.0'} | ${'https://github.com/deployphp/deployer/releases/download/v6.8.0/deployer.phar,https://deployer.org/releases/v6.8.0/deployer.phar deployer'} ${'3.2.1'} | ${'Version missing in deployer manifest'}
`('checking addDeployer: $version', async ({version, url}) => { `('checking addDeployer: $version', async ({version, url}) => {
const data = getData({ const data = getData({
tool: 'deployer', tool: 'deployer',
domain: 'https://deployer.org', domain: 'https://deployer.org',
repository: 'deployphp/deployer',
version_prefix: 'v',
version: version version: version
}); });
expect(await tools.addDeployer(data)).toContain(url); expect(await tools.addDeployer(data)).toContain(url);
@@ -579,11 +476,30 @@ describe('Tools tests', () => {
}); });
it('checking affected composer version with CRLF ranges', async () => { it('checking affected composer version with CRLF ranges', async () => {
jest let affected = false;
.spyOn(fs, 'readFileSync') let fixed = true;
.mockReturnValue('1.0.0-0 1.10.28\r\n2.0.0-0 2.2.28\r\n2.3.0-0 2.9.8'); await jest.isolateModulesAsync(async () => {
expect(tools.skipGitHubAuthForComposerVersion('2.9.7')).toBe(true); jest.doMock('fs', () => ({
expect(tools.skipGitHubAuthForComposerVersion('2.9.8')).toBe(false); ...jest.requireActual('fs'),
readFileSync: (
filePath: fs.PathOrFileDescriptor,
options?: unknown
) => {
if (String(filePath).includes('composer-gh-auth-no-op')) {
return '1.0.0-0 1.10.28\r\n2.0.0-0 2.2.28\r\n2.3.0-0 2.9.8';
}
return (jest.requireActual('fs') as typeof fs).readFileSync(
filePath,
options as fs.ObjectEncodingOptions & {flag?: string}
);
}
}));
const isolatedTools = await import('../src/tools');
affected = isolatedTools.skipGitHubAuthForComposerVersion('2.9.7');
fixed = isolatedTools.skipGitHubAuthForComposerVersion('2.9.8');
});
expect(affected).toBe(true);
expect(fixed).toBe(false);
}); });
it.each` it.each`
@@ -669,15 +585,13 @@ describe('Tools tests', () => {
it.each([ it.each([
[ [
'blackfire, blackfire-player, box, churn, cloud-cli, cpx, cs2pr, flex, grpc_php_plugin, mago, name-collision-detector, parallel-lint, php-cs-fixer, php-scoper, phpDocumentor, phplint, phpstan, phpunit, pecl, phing, phinx, phinx:1.2.3, phive, phpunit-bridge, phpunit-polyfills, pint, php-config, phpize, protoc, symfony, vapor, wp, pie', 'blackfire, blackfire-player, box, churn, cs2pr, flex, grpc_php_plugin, mago, name-collision-detector, parallel-lint, php-cs-fixer, php-scoper, phpDocumentor, phplint, phpstan, phpunit, pecl, phing, phinx, phinx:1.2.3, phive, phpunit-bridge, phpunit-polyfills, pint, php-config, phpize, protoc, symfony, vapor, wp, pie',
[ [
'add_tool https://github.com/shivammathur/composer-cache/releases/latest/download/composer-7.4-stable.phar,https://artifacts.setup-php.com/composer/composer-7.4-stable.phar,https://dl.cloudsmith.io/public/shivammathur/composer-cache/raw/files/composer-7.4-stable.phar,https://getcomposer.org/composer-stable.phar composer', 'add_tool https://github.com/shivammathur/composer-cache/releases/latest/download/composer-7.4-stable.phar,https://artifacts.setup-php.com/composer/composer-7.4-stable.phar,https://dl.cloudsmith.io/public/shivammathur/composer-cache/raw/files/composer-7.4-stable.phar,https://getcomposer.org/composer-stable.phar composer',
'add_blackfire', 'add_blackfire',
'add_tool https://get.blackfire.io/blackfire-player-v1.22.0.phar blackfire-player "-V"', 'add_tool https://get.blackfire.io/blackfire-player-v1.22.0.phar blackfire-player "-V"',
'add_tool https://github.com/box-project/box/releases/latest/download/box.phar box "--version"', 'add_tool https://github.com/box-project/box/releases/latest/download/box.phar box "--version"',
'add_tool https://github.com/bmitch/churn-php/releases/latest/download/churn.phar churn "-V"', 'add_tool https://github.com/bmitch/churn-php/releases/latest/download/churn.phar churn "-V"',
'add_composer_tool cloud-cli cloud-cli laravel/ scoped',
'add_tool https://github.com/laravel/cpx/releases/latest/download/cpx cpx "--version"',
'add_tool https://github.com/staabm/annotate-pull-request-from-checkstyle/releases/latest/download/cs2pr cs2pr "-V"', 'add_tool https://github.com/staabm/annotate-pull-request-from-checkstyle/releases/latest/download/cs2pr cs2pr "-V"',
'add_composer_tool flex flex symfony/ global', 'add_composer_tool flex flex symfony/ global',
'add_grpc_php_plugin latest', 'add_grpc_php_plugin latest',
@@ -688,7 +602,7 @@ describe('Tools tests', () => {
'add_tool https://github.com/humbug/php-scoper/releases/latest/download/php-scoper.phar php-scoper "--version"', 'add_tool https://github.com/humbug/php-scoper/releases/latest/download/php-scoper.phar php-scoper "--version"',
'add_tool https://github.com/phpDocumentor/phpDocumentor/releases/latest/download/phpDocumentor.phar phpDocumentor "--version"', 'add_tool https://github.com/phpDocumentor/phpDocumentor/releases/latest/download/phpDocumentor.phar phpDocumentor "--version"',
'add_composer_tool phplint phplint overtrue/', 'add_composer_tool phplint phplint overtrue/',
'add_composer_tool phpstan phpstan phpstan/ scoped', 'add_tool https://github.com/phpstan/phpstan/releases/latest/download/phpstan.phar phpstan "-V"',
'add_tool https://phar.phpunit.de/phpunit-7.4.0.phar,https://phar.phpunit.de/phpunit-7.phar phpunit "--version"', 'add_tool https://phar.phpunit.de/phpunit-7.4.0.phar,https://phar.phpunit.de/phpunit-7.phar phpunit "--version"',
'add_pecl', 'add_pecl',
'add_tool https://www.phing.info/get/phing-latest.phar phing "-v"', 'add_tool https://www.phing.info/get/phing-latest.phar phing "-v"',
@@ -716,7 +630,7 @@ describe('Tools tests', () => {
it.each([ it.each([
[ [
'backward-compatibility-check, behat, blackfire, blackfire-player, churn, composer-dependency-analyser, composer-normalize, composer-require-checker, composer-unused, cpx:2.0.0, cs2pr:1.2.3, ecs, flex, grpc_php_plugin:1.2.3, infection, laravel-cloud, mago:0.26.1, name-collision-detector, phan, phan:1.2.3, phing:1.2.3, phinx, phive:1.2.3, php-config, phpcbf, phpcpd, phpcs, phpdoc, phpize, phpmd, phpspec, phpunit-bridge:5.6, phpunit-polyfills:1.0.1, protoc:v1.2.3, psalm, rector, symfony-cli, vapor-cli, wp-cli, pie', 'backward-compatibility-check, behat, blackfire, blackfire-player, churn, composer-dependency-analyser, composer-normalize, composer-require-checker, composer-unused, cs2pr:1.2.3, ecs, flex, grpc_php_plugin:1.2.3, infection, mago:0.26.1, name-collision-detector, phan, phan:1.2.3, phing:1.2.3, phinx, phive:1.2.3, php-config, phpcbf, phpcpd, phpcs, phpdoc, phpize, phpmd, phpspec, phpunit-bridge:5.6, phpunit-polyfills:1.0.1, protoc:v1.2.3, psalm, rector, symfony-cli, vapor-cli, wp-cli, pie',
[ [
'add_tool https://github.com/shivammathur/composer-cache/releases/latest/download/composer-7.4-stable.phar,https://artifacts.setup-php.com/composer/composer-7.4-stable.phar,https://dl.cloudsmith.io/public/shivammathur/composer-cache/raw/files/composer-7.4-stable.phar,https://getcomposer.org/composer-stable.phar composer', 'add_tool https://github.com/shivammathur/composer-cache/releases/latest/download/composer-7.4-stable.phar,https://artifacts.setup-php.com/composer/composer-7.4-stable.phar,https://dl.cloudsmith.io/public/shivammathur/composer-cache/raw/files/composer-7.4-stable.phar,https://getcomposer.org/composer-stable.phar composer',
'add_composer_tool behat behat behat/ scoped', 'add_composer_tool behat behat behat/ scoped',
@@ -727,12 +641,10 @@ describe('Tools tests', () => {
'add_composer_tool composer-dependency-analyser composer-dependency-analyser shipmonk/ scoped', 'add_composer_tool composer-dependency-analyser composer-dependency-analyser shipmonk/ scoped',
'add_composer_tool composer-require-checker composer-require-checker maglnet/ scoped', 'add_composer_tool composer-require-checker composer-require-checker maglnet/ scoped',
'add_tool https://github.com/composer-unused/composer-unused/releases/latest/download/composer-unused.phar composer-unused "-V"', 'add_tool https://github.com/composer-unused/composer-unused/releases/latest/download/composer-unused.phar composer-unused "-V"',
'add_tool https://github.com/laravel/cpx/releases/download/v2.0.0/cpx cpx "--version"',
'add_tool https://github.com/staabm/annotate-pull-request-from-checkstyle/releases/download/1.2.3/cs2pr cs2pr "-V"', 'add_tool https://github.com/staabm/annotate-pull-request-from-checkstyle/releases/download/1.2.3/cs2pr cs2pr "-V"',
'add_composer_tool flex flex symfony/ global', 'add_composer_tool flex flex symfony/ global',
'add_grpc_php_plugin 1.2.3', 'add_grpc_php_plugin 1.2.3',
'add_tool https://github.com/infection/infection/releases/latest/download/infection.phar infection "-V"', 'add_tool https://github.com/infection/infection/releases/latest/download/infection.phar infection "-V"',
'add_composer_tool cloud-cli cloud-cli laravel/ scoped',
'add_mago 0.26.1', 'add_mago 0.26.1',
'add_composer_tool name-collision-detector name-collision-detector shipmonk/ scoped', 'add_composer_tool name-collision-detector name-collision-detector shipmonk/ scoped',
'add_tool https://github.com/phan/phan/releases/latest/download/phan.phar phan "-v"', 'add_tool https://github.com/phan/phan/releases/latest/download/phan.phar phan "-v"',
@@ -777,7 +689,7 @@ describe('Tools tests', () => {
'blackfire-player is not a windows tool', 'blackfire-player is not a windows tool',
'Add-Tool https://github.com/staabm/annotate-pull-request-from-checkstyle/releases/latest/download/cs2pr cs2pr "-V"', 'Add-Tool https://github.com/staabm/annotate-pull-request-from-checkstyle/releases/latest/download/cs2pr cs2pr "-V"',
'Add-Tool https://github.com/bmitch/churn-php/releases/latest/download/churn.phar churn "-V"', 'Add-Tool https://github.com/bmitch/churn-php/releases/latest/download/churn.phar churn "-V"',
'Add-Tool https://github.com/deployphp/deployer/releases/latest/download/deployer.phar,https://deployer.org/deployer.phar deployer "-V"', 'Add-Tool https://deployer.org/deployer.phar deployer "-V"',
'Tool does_not_exist is not supported', 'Tool does_not_exist is not supported',
'Add-ComposerTool flex flex symfony/ global', 'Add-ComposerTool flex flex symfony/ global',
'Add-Mago', 'Add-Mago',
@@ -862,103 +774,6 @@ describe('Tools tests', () => {
expect(await tools.addTools(tools_csv, '7.4', 'linux')).toContain(script); expect(await tools.addTools(tools_csv, '7.4', 'linux')).toContain(script);
}); });
it.each`
tools_csv | os | script
${'phpunit:9.5.0@sha256:' + 'a'.repeat(64)} | ${'linux'} | ${'add_tool https://phar.phpunit.de/phpunit-9.5.0.phar,https://phar.phpunit.de/phpunit-9.phar phpunit "--version" sha256:' + 'a'.repeat(64)}
${'phpunit:9.5.0@sha256:' + 'a'.repeat(64)} | ${'win32'} | ${'Add-Tool https://phar.phpunit.de/phpunit-9.5.0.phar,https://phar.phpunit.de/phpunit-9.phar phpunit "--version" sha256:' + 'a'.repeat(64)}
${'composer:2.9.8@sha256:' + 'b'.repeat(64)} | ${'linux'} | ${'composer 2.9.8 sha256:' + 'b'.repeat(64)}
${'cs2pr:1.2.3@sha256:' + 'd'.repeat(64)} | ${'linux'} | ${'add_tool https://github.com/staabm/annotate-pull-request-from-checkstyle/releases/download/1.2.3/cs2pr cs2pr "-V" sha256:' + 'd'.repeat(64)}
${'deployer:7.5.12@sha256:' + 'e'.repeat(64)} | ${'linux'} | ${'add_tool https://github.com/deployphp/deployer/releases/download/v7.5.12/deployer.phar,https://deployer.org/releases/v7.5.12/deployer.phar deployer "-V" sha256:' + 'e'.repeat(64)}
${'phive:0.15.3@sha512:' + 'c'.repeat(128)} | ${'darwin'} | ${'add_tool https://github.com/phar-io/phive/releases/download/0.15.3/phive-0.15.3.phar phive "status" sha512:' + 'c'.repeat(128)}
${'phinx:1.2.3@sha256:' + 'a'.repeat(64)} | ${'linux'} | ${'add_log "$cross" "phinx" "Checksum verification is not supported for phinx"'}
${'pecl:1.2.3@sha256:' + 'a'.repeat(64)} | ${'linux'} | ${'add_log "$cross" "pecl" "Checksum verification is not supported for pecl"'}
${'phpunit:9.5.0@sha256:invalid'} | ${'linux'} | ${'add_log "$cross" "phpunit" "Invalid sha256 checksum, expected 64 hexadecimal characters"'}
${'composer:2.9.8@SHA256:' + 'b'.repeat(64)} | ${'linux'} | ${'composer 2.9.8 sha256:' + 'b'.repeat(64)}
${'composer:2.9.8@sha384:' + 'b'.repeat(96)} | ${'linux'} | ${'add_log "$cross" "composer" "Unsupported checksum algorithm sha384, expected sha256 or sha512"'}
${'composer:2.9.8@md5:' + 'b'.repeat(32)} | ${'linux'} | ${'add_log "$cross" "composer" "Unsupported checksum algorithm md5, expected sha256 or sha512"'}
${'composer:2.9.8@sha256' + 'b'.repeat(64)} | ${'linux'} | ${'add_log "$cross" "composer" "Invalid checksum syntax, expected @sha256:<hash> or @sha512:<hash>"'}
`(
'checking addTools with checksum: $tools_csv, $os',
async ({tools_csv, os, script}) => {
expect(await tools.addTools(tools_csv, '7.4', os)).toContain(script);
}
);
describe.each(['linux', 'darwin', 'win32'])(
'Checksum version requirements on %s',
os => {
it.each(['2.9.8+build.1', '2.9.8-rc.1', '2.9.8-rc.1+build.2'])(
'preserves the exact Composer version and checksum for %s',
async version => {
const checksum = 'sha256:' + 'a'.repeat(64);
const release = `composer:${version}@${checksum}`;
expect(await tools.filterList([release])).toEqual([release]);
const script = await tools.addTools(release, '8.4', os);
expect(script).toContain(
`https://github.com/composer/composer/releases/download/${version}/composer.phar`
);
expect(script).toContain(
`https://getcomposer.org/download/${version}/composer.phar`
);
expect(script).toContain(`composer ${version} ${checksum}`);
expect(script).not.toContain('latest');
expect(script).not.toContain('composer-stable.phar');
}
);
it.each([
'',
':latest',
':stable',
':preview',
':snapshot',
':2',
':2.x',
':2.9',
':2.9.x',
':^2.9.8'
])(
'rejects a checksum on a non-full version %s without an unpinned install',
async version => {
for (const tool of ['composer', 'phpunit']) {
const release = `${tool}${version}@sha256:${'a'.repeat(64)}`;
const data = await tools.getData(release, '8.4', os);
expect(data.error).toBe(
'Checksum pinning requires a full version, for example tool:1.2.3'
);
expect(data.url).toBe('');
const script = await tools.addTools(release, '8.4', os);
expect(script).toContain(data.error);
const installations = script
.split('\n')
.filter(line => /^add[-_]tool /i.test(line));
expect(
installations.some(line => new RegExp(` ${tool}( |$)`).test(line))
).toBe(false);
}
}
);
}
);
it.each`
type | tool_function | supported
${'phar'} | ${undefined} | ${true}
${'custom-function'} | ${undefined} | ${true}
${'custom-function'} | ${'composer'} | ${true}
${'custom-function'} | ${'pecl'} | ${false}
${'custom-function'} | ${'dev_tools'} | ${false}
${'composer'} | ${undefined} | ${false}
${'custom-package'} | ${undefined} | ${false}
`(
'checking supportsChecksum: $type, $tool_function',
async ({type, tool_function, supported}) => {
const data = getData({tool: 'tool', type: type});
data.function = tool_function;
expect(await tools.supportsChecksum(data)).toBe(supported);
}
);
it.each` it.each`
tools_csv | token | script tools_csv | token | script
${'cs2pr:1.2'} | ${'invalid_token'} | ${'add_log "$cross" "cs2pr" "Invalid token"'} ${'cs2pr:1.2'} | ${'invalid_token'} | ${'add_log "$cross" "cs2pr" "Invalid token"'}
@@ -982,14 +797,26 @@ describe('Tools tests', () => {
} }
}); });
const readFileSync = fs.readFileSync; let result: string = '';
jest.spyOn(fs, 'readFileSync').mockImplementation((filePath, options) => { await jest.isolateModulesAsync(async () => {
if (String(filePath).includes('tools.json')) { jest.doMock('fs', () => ({
return brokenToolsJson; ...jest.requireActual('fs'),
} readFileSync: (
return readFileSync(filePath, options); filePath: fs.PathOrFileDescriptor,
options?: unknown
) => {
if (String(filePath).includes('tools.json')) {
return brokenToolsJson;
}
return (jest.requireActual('fs') as typeof fs).readFileSync(
filePath,
options as fs.ObjectEncodingOptions & {flag?: string}
);
}
}));
const isolatedTools = await import('../src/tools');
result = await isolatedTools.addTools('broken-tool', '7.4', 'linux');
}); });
const result = await tools.addTools('broken-tool', '7.4', 'linux');
expect(result).toContain( expect(result).toContain(
'add_log "$cross" "broken-tool" "broken-tool has no function defined. Please report this issue."' 'add_log "$cross" "broken-tool" "broken-tool has no function defined. Please report this issue."'
+22 -204
View File
@@ -1,13 +1,7 @@
import {fileURLToPath} from 'url';
import {jest} from '@jest/globals';
import fs from 'fs'; import fs from 'fs';
import os from 'os';
import * as path from 'path'; import * as path from 'path';
const fetchMock = jest.fn<typeof import('../src/fetch.js').fetch>(); import * as utils from '../src/utils';
jest.unstable_mockModule('../src/fetch.js', () => ({fetch: fetchMock})); import * as fetchModule from '../src/fetch';
const utils = await import('../src/utils.js');
const dirname = path.dirname(fileURLToPath(import.meta.url));
describe('Utils tests', () => { describe('Utils tests', () => {
it('checking readEnv', async () => { it('checking readEnv', async () => {
@@ -45,22 +39,12 @@ describe('Utils tests', () => {
}); });
it('checking parseVersion', async () => { it('checking parseVersion', async () => {
const fetchSpy = fetchMock.mockResolvedValue({ const fetchSpy = jest
data: fs.readFileSync( .spyOn(fetchModule, 'fetch')
path.join(dirname, '../src/configs/php-versions.json'), .mockResolvedValue({data: '{ "latest": "8.1", "5.x": "5.6" }'});
'utf8' expect(await utils.parseVersion('latest')).toBe('8.1');
)
});
expect(await utils.parseVersion('latest')).toBe('8.5');
expect(await utils.parseVersion('nightly')).toBe('8.6');
expect(await utils.parseVersion('master')).toBe('8.7');
expect(await utils.parseVersion('8.7')).toBe('8.7');
expect(await utils.parseVersion('8.7.0')).toBe('8.7');
expect(await utils.parseVersion('7')).toBe('7.0'); expect(await utils.parseVersion('7')).toBe('7.0');
expect(await utils.parseVersion('7.4')).toBe('7.4'); expect(await utils.parseVersion('7.4')).toBe('7.4');
expect(await utils.parseVersion('8.10')).toBe('8.10');
expect(await utils.parseVersion('10')).toBe('10.0');
expect(await utils.parseVersion('10.0')).toBe('10.0');
expect(await utils.parseVersion('5.x')).toBe('5.6'); expect(await utils.parseVersion('5.x')).toBe('5.6');
expect(await utils.parseVersion('pre')).toBe('pre'); expect(await utils.parseVersion('pre')).toBe('pre');
expect(await utils.parseVersion('pre-installed')).toBe('pre'); expect(await utils.parseVersion('pre-installed')).toBe('pre');
@@ -70,16 +54,11 @@ describe('Utils tests', () => {
await expect(utils.parseVersion('foo')).rejects.toThrow( await expect(utils.parseVersion('foo')).rejects.toThrow(
'Invalid PHP version:' 'Invalid PHP version:'
); );
await expect(utils.parseVersion('8.4\n$(id)')).rejects.toThrow(
'Invalid PHP version:'
);
for (const latest of ['8.1.0', 'pre', 8.4, ['8.4']]) { fetchSpy.mockResolvedValue({data: '{ "latest": "8.1.0" }'});
fetchSpy.mockResolvedValue({data: JSON.stringify({latest})}); await expect(utils.parseVersion('latest')).rejects.toThrow(
await expect(utils.parseVersion('latest')).rejects.toThrow( 'Invalid PHP version in manifest:'
'Invalid PHP version in manifest:' );
);
}
fetchSpy.mockReset(); fetchSpy.mockReset();
fetchSpy.mockResolvedValueOnce({}).mockResolvedValueOnce({}); fetchSpy.mockResolvedValueOnce({}).mockResolvedValueOnce({});
@@ -238,9 +217,9 @@ describe('Utils tests', () => {
}); });
it('checking suppressOutput', async () => { it('checking suppressOutput', async () => {
expect(await utils.suppressOutput('win32')).toEqual(' >$null 2>&1'); expect(await utils.suppressOutput('win32')).toEqual(' ');
expect(await utils.suppressOutput('linux')).toEqual(' >/dev/null 2>&1'); expect(await utils.suppressOutput('linux')).toEqual(' ');
expect(await utils.suppressOutput('darwin')).toEqual(' >/dev/null 2>&1'); expect(await utils.suppressOutput('darwin')).toEqual(' ');
expect(await utils.suppressOutput('openbsd')).toContain( expect(await utils.suppressOutput('openbsd')).toContain(
'Platform openbsd is not supported' 'Platform openbsd is not supported'
); );
@@ -332,8 +311,8 @@ describe('Utils tests', () => {
"Could not find '.phpenv-version' file." "Could not find '.phpenv-version' file."
); );
const existsSync = jest.spyOn(fs, 'existsSync').mockReturnValue(false); const existsSync = jest.spyOn(fs, 'existsSync').mockImplementation();
const readFileSync = jest.spyOn(fs, 'readFileSync').mockReturnValue(''); const readFileSync = jest.spyOn(fs, 'readFileSync').mockImplementation();
existsSync.mockReturnValue(true); existsSync.mockReturnValue(true);
readFileSync.mockReturnValue('8.1'); readFileSync.mockReturnValue('8.1');
@@ -353,30 +332,8 @@ describe('Utils tests', () => {
readFileSync.mockReturnValue('ruby 1.2.3\nphp 8.4.2\nnode 20.1.2'); readFileSync.mockReturnValue('ruby 1.2.3\nphp 8.4.2\nnode 20.1.2');
expect(await utils.readPHPVersion()).toBe('8.4.2'); expect(await utils.readPHPVersion()).toBe('8.4.2');
readFileSync.mockReturnValue('ruby 1.2.3\nphp 8.4\nnode 20.1.2');
expect(await utils.readPHPVersion()).toBe('8.4');
readFileSync.mockReturnValue('ruby 1.2.3\nphp latest\nnode 20.1.2');
expect(await utils.readPHPVersion()).toBe('latest');
readFileSync.mockReturnValue(' \t8.4 \t\n');
expect(await utils.readPHPVersion()).toBe('8.4');
readFileSync.mockReturnValue(
'#PHP\r\n\r\nruby 1.2.3\r\n \tphp \t latest \t# version\r\nnode 20.1.2'
);
expect(await utils.readPHPVersion()).toBe('latest');
readFileSync.mockReturnValue('php\n8.4');
await expect(utils.readPHPVersion()).rejects.toThrow('Invalid PHP version');
process.env['php-version-file'] = '.tool-versions';
readFileSync.mockReturnValue("ruby 1.2.3\nphp 8.4';id;#\nnode 20.1.2");
await expect(utils.readPHPVersion()).rejects.toThrow('.tool-versions');
delete process.env['php-version-file'];
existsSync.mockReturnValue(true); existsSync.mockReturnValue(true);
readFileSync.mockReturnValue('php 8.4 8.5'); readFileSync.mockReturnValue('setup-php');
await expect(utils.readPHPVersion()).rejects.toThrow('Invalid PHP version'); await expect(utils.readPHPVersion()).rejects.toThrow('Invalid PHP version');
existsSync.mockReturnValueOnce(false).mockReturnValueOnce(true); existsSync.mockReturnValueOnce(false).mockReturnValueOnce(true);
@@ -399,47 +356,32 @@ describe('Utils tests', () => {
}); });
it('readPHPVersion rejects unsupported values from each source', async () => { it('readPHPVersion rejects unsupported values from each source', async () => {
const existsSync = jest.spyOn(fs, 'existsSync').mockReturnValue(false); const existsSync = jest.spyOn(fs, 'existsSync').mockImplementation();
const readFileSync = jest.spyOn(fs, 'readFileSync').mockReturnValue(''); const readFileSync = jest.spyOn(fs, 'readFileSync').mockImplementation();
process.env['php-version'] = '$0'; process.env['php-version'] = 'bogus';
await expect(utils.readPHPVersion()).rejects.toThrow('php-version input'); await expect(utils.readPHPVersion()).rejects.toThrow('php-version input');
delete process.env['php-version']; delete process.env['php-version'];
existsSync.mockReturnValue(true); existsSync.mockReturnValue(true);
readFileSync.mockReturnValue(';id'); readFileSync.mockReturnValue('bogus');
await expect(utils.readPHPVersion()).rejects.toThrow('.php-version'); await expect(utils.readPHPVersion()).rejects.toThrow('.php-version');
existsSync.mockReturnValueOnce(false).mockReturnValueOnce(true); existsSync.mockReturnValueOnce(false).mockReturnValueOnce(true);
readFileSync.mockReturnValue('{"platform-overrides":{"php":"`w`"}}'); readFileSync.mockReturnValue('{"platform-overrides":{"php":"bogus"}}');
await expect(utils.readPHPVersion()).rejects.toThrow( await expect(utils.readPHPVersion()).rejects.toThrow(
'composer.lock platform-overrides.php' 'composer.lock platform-overrides.php'
); );
existsSync.mockReturnValueOnce(false).mockReturnValueOnce(true);
readFileSync.mockReturnValue('{"platform-overrides":{"php":8.4}}');
await expect(utils.readPHPVersion()).rejects.toThrow(
'composer.lock platform-overrides.php: number'
);
existsSync existsSync
.mockReturnValueOnce(false) .mockReturnValueOnce(false)
.mockReturnValueOnce(false) .mockReturnValueOnce(false)
.mockReturnValueOnce(true); .mockReturnValueOnce(true);
readFileSync.mockReturnValue('{"config":{"platform":{"php":"8.4$(id)"}}}'); readFileSync.mockReturnValue('{"config":{"platform":{"php":"bogus"}}}');
await expect(utils.readPHPVersion()).rejects.toThrow( await expect(utils.readPHPVersion()).rejects.toThrow(
'composer.json config.platform.php' 'composer.json config.platform.php'
); );
existsSync
.mockReturnValueOnce(false)
.mockReturnValueOnce(false)
.mockReturnValueOnce(true);
readFileSync.mockReturnValue('{"config":{"platform":{"php":["8.4"]}}}');
await expect(utils.readPHPVersion()).rejects.toThrow(
'composer.json config.platform.php: object'
);
existsSync.mockClear(); existsSync.mockClear();
readFileSync.mockClear(); readFileSync.mockClear();
}); });
@@ -453,127 +395,3 @@ describe('Utils tests', () => {
expect(script).toEqual('\n$var = command\n'); expect(script).toEqual('\n$var = command\n');
}); });
}); });
describe.each(['linux', 'darwin', 'win32'])(
'Verbose script preparation on %s',
platform => {
let root: string;
let run: string;
let helper: string;
const env = {...process.env};
beforeEach(() => {
jest.restoreAllMocks();
root = fs.mkdtempSync(path.join(os.tmpdir(), 'setup-php-verbose-'));
const scripts = path.join(root, 'src', 'scripts');
const extension = platform === 'win32' ? '.ps1' : '.sh';
fs.mkdirSync(path.join(scripts, 'tools'), {recursive: true});
helper = path.join(scripts, 'tools', 'helper' + extension);
run = path.join(scripts, 'run' + extension);
fs.writeFileSync(helper, 'echo helper-output\n');
fs.writeFileSync(
run,
`. '${helper}' ${platform === 'win32' ? '>$null' : '>/dev/null'} 2>&1\n`
);
delete process.env.verbose;
delete process.env.VERBOSE;
delete process.env.RUNNER_DEBUG;
});
afterEach(() => {
process.env = {...env};
fs.rmSync(root, {recursive: true, force: true});
});
it.each([undefined, '', 'false', 'true', 'v', 'vv', 'vvv', 'invalid'])(
'prepares scripts for verbose=%s',
async verbose => {
if (verbose !== undefined) process.env.verbose = verbose;
const original = fs.readFileSync(run, 'utf8');
const enabled = /^(true|v{1,3})$/.test(verbose || '');
const tracing = /^v{2,3}$/.test(verbose || '');
const prepared = await utils.addVerbose(run, platform);
const script = fs.readFileSync(prepared, 'utf8');
expect(prepared !== run).toBe(enabled);
expect(
script.includes(platform === 'win32' ? '>$null' : '>/dev/null')
).toBe(!enabled);
expect(script.includes('src-verbose')).toBe(enabled);
expect(script.startsWith('. ')).toBe(true);
expect(process.env.SETUP_PHP_TRACE).toBe(
tracing ? String(verbose!.length - 1) : '0'
);
expect(fs.readFileSync(run, 'utf8')).toBe(original);
}
);
it.each(['', ' ', '\t'])(
'handles pipe spacing %j and subsequent quiet runs',
async space => {
const target = platform === 'win32' ? '$null' : '/dev/null';
const pipe = `>${space}${target} 2>&1`;
const probe =
platform === 'win32'
? 'echo probe 2>$null'
: 'command -v sh >/dev/null';
fs.writeFileSync(helper, `echo nested-output ${pipe}\n${probe}\n`);
process.env.VERBOSE = 'true';
const prepared = await utils.addVerbose(run, platform);
expect(
fs.readFileSync(
path.join(path.dirname(prepared), 'tools', path.basename(helper)),
'utf8'
)
).toBe(
`echo nested-output ${platform === 'win32' ? '2>&1 | Out-Host' : ''}\n${probe}\n`
);
expect(fs.readFileSync(helper, 'utf8')).toContain(pipe);
process.env.verbose = 'false';
expect(await utils.addVerbose(run, platform)).toBe(run);
expect(process.env.SETUP_PHP_TRACE).toBe('0');
expect(fs.readFileSync(helper, 'utf8')).toContain(pipe);
}
);
it.each([undefined, 'false', 'true', 'v', 'vv', 'vvv'])(
'enables output for runner debug with verbose=%s',
async verbose => {
process.env.RUNNER_DEBUG = '1';
if (verbose !== undefined) process.env.verbose = verbose;
const prepared = await utils.addVerbose(run, platform);
expect(prepared).not.toBe(run);
expect(fs.readFileSync(prepared, 'utf8')).not.toMatch(
/>\s*(?:\/dev\/null|\$null)\s+2>&1/
);
expect(process.env.SETUP_PHP_TRACE).toBe(
/^v{2,3}$/.test(verbose || '') ? String(verbose!.length - 1) : '0'
);
}
);
(process.platform === 'win32' ? it.skip : it)(
'uses fresh copies without writing through source symlinks',
async () => {
const outside = path.join(root, path.basename(helper));
const original = 'echo original >/dev/null 2>&1\n';
fs.writeFileSync(outside, original);
fs.unlinkSync(helper);
fs.symlinkSync(outside, helper);
process.env.verbose = 'true';
const first = await utils.addVerbose(run, platform);
const second = await utils.addVerbose(run, platform);
expect(first).not.toBe(second);
expect(fs.readFileSync(outside, 'utf8')).toBe(original);
expect(fs.readFileSync(helper, 'utf8')).toBe(original);
expect(
fs.readFileSync(
path.join(path.dirname(first), 'tools', path.basename(helper)),
'utf8'
)
).toBe(
`echo original ${platform === 'win32' ? '2>&1 | Out-Host' : ''}\n`
);
}
);
}
);
+1 -1
View File
File diff suppressed because one or more lines are too long
-3
View File
@@ -1,3 +0,0 @@
{
"type": "module"
}
+1 -6
View File
@@ -1,5 +1,5 @@
import {createRequire} from 'node:module';
import typescriptEslint from '@typescript-eslint/eslint-plugin'; import typescriptEslint from '@typescript-eslint/eslint-plugin';
import {importX} from 'eslint-plugin-import-x';
import jest from 'eslint-plugin-jest'; import jest from 'eslint-plugin-jest';
import prettierRecommended from 'eslint-plugin-prettier/recommended'; import prettierRecommended from 'eslint-plugin-prettier/recommended';
import eslintConfigPrettier from 'eslint-config-prettier'; import eslintConfigPrettier from 'eslint-config-prettier';
@@ -7,11 +7,6 @@ import globals from 'globals';
import tsParser from '@typescript-eslint/parser'; import tsParser from '@typescript-eslint/parser';
import js from '@eslint/js'; import js from '@eslint/js';
// Until import-x supports minimatch 11, use its CommonJS entry point to avoid
// the removed makeRe import in no-internal-modules, unused by these presets.
// https://github.com/un-ts/eslint-plugin-import-x/pull/570
const {importX} = createRequire(import.meta.url)('eslint-plugin-import-x');
export default [ export default [
js.configs.recommended, js.configs.recommended,
...typescriptEslint.configs['flat/recommended'], ...typescriptEslint.configs['flat/recommended'],
+2 -6
View File
@@ -1,15 +1,11 @@
export default { module.exports = {
clearMocks: true, clearMocks: true,
moduleFileExtensions: ['js', 'ts'], moduleFileExtensions: ['js', 'ts'],
extensionsToTreatAsEsm: ['.ts'],
moduleNameMapper: {
'^(\\.{1,2}/.*)\\.js$': '$1'
},
testEnvironment: 'node', testEnvironment: 'node',
testMatch: ['**/*.test.ts'], testMatch: ['**/*.test.ts'],
testRunner: 'jest-circus/runner', testRunner: 'jest-circus/runner',
transform: { transform: {
'^.+\\.ts$': ['ts-jest', {tsconfig: 'tsconfig.test.json', useESM: true}] '^.+\\.ts$': 'ts-jest'
}, },
verbose: true, verbose: true,
collectCoverage: true collectCoverage: true
+974 -1788
View File
File diff suppressed because it is too large Load Diff
+23 -32
View File
@@ -1,9 +1,8 @@
{ {
"name": "setup-php", "name": "setup-php",
"version": "2.40.1", "version": "2.37.2",
"private": false, "private": false,
"description": "Setup PHP for use with GitHub Actions", "description": "Setup PHP for use with GitHub Actions",
"type": "module",
"main": "lib/install.js", "main": "lib/install.js",
"types": "lib/install.d.ts", "types": "lib/install.d.ts",
"directories": { "directories": {
@@ -21,8 +20,7 @@
"format": "prettier --write **/src/*.ts **/__tests__/*.ts && git add -f __tests__/ ", "format": "prettier --write **/src/*.ts **/__tests__/*.ts && git add -f __tests__/ ",
"format-check": "prettier --check **/src/*.ts **/__tests__/*.ts", "format-check": "prettier --check **/src/*.ts **/__tests__/*.ts",
"release": "ncc build -m -o dist && git add -f dist/", "release": "ncc build -m -o dist && git add -f dist/",
"typecheck": "tsc --project tsconfig.test.json --noEmit", "test": "jest"
"test": "node --experimental-vm-modules node_modules/jest/bin/jest.js"
}, },
"repository": { "repository": {
"type": "git", "type": "git",
@@ -36,48 +34,41 @@
"author": "shivammathur", "author": "shivammathur",
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"@actions/exec": "^3.0.0", "@actions/exec": "^2.0.0",
"compare-versions": "^6.1.1" "compare-versions": "^6.1.1"
}, },
"devDependencies": { "devDependencies": {
"@eslint/compat": "^2.1.1", "@eslint/compat": "^2.1.0",
"@eslint/js": "^10.0.1", "@eslint/js": "^10.0.1",
"@types/jest": "^30.0.0", "@types/jest": "^30.0.0",
"@types/node": "^26.6.6", "@types/node": "^25.9.2",
"@typescript-eslint/eslint-plugin": "^8.72.1", "@typescript-eslint/eslint-plugin": "^8.60.1",
"@typescript-eslint/parser": "^8.72.1", "@typescript-eslint/parser": "^8.60.1",
"@typescript/native": "npm:typescript@^7.0.2", "@vercel/ncc": "^0.38.4",
"@vercel/ncc": "^0.45.0", "eslint": "^10.4.1",
"eslint": "^10.14.0",
"eslint-config-prettier": "^10.1.8", "eslint-config-prettier": "^10.1.8",
"eslint-import-resolver-typescript": "^4.4.5", "eslint-import-resolver-typescript": "^4.4.5",
"eslint-plugin-import-x": "^4.17.1", "eslint-plugin-import-x": "^4.16.2",
"eslint-plugin-jest": "^29.17.0", "eslint-plugin-jest": "^29.15.2",
"eslint-plugin-prettier": "^5.5.7", "eslint-plugin-prettier": "^5.5.6",
"globals": "^17.14.0", "globals": "^17.6.0",
"jest": "^30.5.2", "jest": "^30.4.2",
"jest-circus": "^30.5.2", "jest-circus": "^30.4.2",
"nock": "^15.0.5", "nock": "^14.0.15",
"prettier": "^3.9.10", "prettier": "^3.8.3",
"simple-git-hooks": "^2.14.0", "simple-git-hooks": "^2.13.1",
"ts-jest": "^29.4.15", "ts-jest": "^29.4.11",
"typescript": "npm:@typescript/typescript6@^6.0.2" "typescript": "^5.9.3"
}, },
"overrides": { "overrides": {
"deepmerge": "npm:@shivammathur/deepmerge@4.3.2", "test-exclude": "^7.0.1",
"glob": "^14.0.3", "glob": "^13.0.6",
"minimatch": "^11.0.3" "minimatch": "^10.2.1"
}, },
"bugs": { "bugs": {
"url": "https://github.com/shivammathur/setup-php/issues" "url": "https://github.com/shivammathur/setup-php/issues"
}, },
"simple-git-hooks": { "simple-git-hooks": {
"pre-commit": "npm run format && npm run lint && npm run test && npm run build && npm run release" "pre-commit": "npm run format && npm run lint && npm run test && npm run build && npm run release"
},
"allowScripts": {
"@parcel/watcher@2.6.0": true,
"fsevents@2.3.3": true,
"simple-git-hooks@2.14.0": true,
"unrs-resolver@1.12.2": true
} }
} }
+2 -2
View File
@@ -1,4 +1,4 @@
import * as utils from './utils.js'; import * as utils from './utils';
/** /**
* Add script to set custom ini values for unix * Add script to set custom ini values for unix
@@ -17,7 +17,7 @@ export async function addINIValuesUnix(
return ( return (
'echo "' + 'echo "' +
ini_values.map(v => utils.escapeForShell(v, 'linux')).join('\n') + ini_values.map(v => utils.escapeForShell(v, 'linux')).join('\n') +
'" | sudo tee -a "${pecl_file:-${ini_file[@]}}" >/dev/null 2>&1' + '" | sudo tee -a "${pecl_file:-${ini_file[@]}}" ' +
script script
); );
} }
-1
View File
@@ -8,7 +8,6 @@ event=event
excimer=excimer excimer=excimer
expect=expect expect=expect
gearman=gearman gearman=gearman
geos=geos
gmagick=gmagick gmagick=gmagick
gnupg=gnupg gnupg=gnupg
grpc=grpc grpc=grpc
-1
View File
@@ -7,7 +7,6 @@ gmagick=graphicsmagick-libmagick-dev-compat
gnupg=libgpgme-dev gnupg=libgpgme-dev
grpc=libgrpc-dev libprotobuf-dev protobuf-compiler grpc=libgrpc-dev libprotobuf-dev protobuf-compiler
imagick=libmagickwand-dev libmagickcore-dev imagick=libmagickwand-dev libmagickcore-dev
krb5=libkrb5-dev
memcached=libmemcached-dev libevent-dev memcached=libmemcached-dev libevent-dev
protobuf=libprotobuf-dev protobuf-compiler protobuf=libprotobuf-dev protobuf-compiler
rdkafka=librdkafka-dev rdkafka=librdkafka-dev
-1
View File
@@ -11,7 +11,6 @@ grpc=30
http=25 http=25
pecl_http=25 pecl_http=25
pecl-http=25 pecl-http=25
ibm_db2=40
inotify=30 inotify=30
libvirt-php=40 libvirt-php=40
mailparse=25 mailparse=25
+1 -1
View File
@@ -3,7 +3,7 @@
"highest": "8.5", "highest": "8.5",
"latest": "8.5", "latest": "8.5",
"nightly": "8.6", "nightly": "8.6",
"master": "8.7", "master": "8.6",
"5.x": "5.6", "5.x": "5.6",
"7.x": "7.4", "7.x": "7.4",
"8.x": "8.5" "8.x": "8.5"
+15 -71
View File
@@ -3,77 +3,21 @@
{ {
"owner": "phpunit", "owner": "phpunit",
"pattern": [ "pattern": [
{ "regexp": "^\\d+\\)\\s.*$" }, {
{ "regexp": "^(.*Failed\\sasserting\\sthat.*)$", "message": 1 }, "regexp": "^\\d+\\)\\s.*$"
{ "regexp": "^\\s*$" }, },
{ "regexp": "^(.*):(\\d+)$", "file": 1, "line": 2 } {
] "regexp": "^(.*Failed\\sasserting\\sthat.*)$",
}, "message": 1
{ },
"owner": "phpunit-no-blank", {
"pattern": [ "regexp": "^\\s*$"
{ "regexp": "^\\d+\\)\\s.*$" }, },
{ "regexp": "^(.*Failed\\sasserting\\sthat.*)$", "message": 1 }, {
{ "regexp": "^(.*):(\\d+)$", "file": 1, "line": 2 } "regexp": "^(.*):(\\d+)$",
] "file": 1,
}, "line": 2
{ }
"owner": "phpunit-custom-message",
"pattern": [
{ "regexp": "^\\d+\\)\\s.*$" },
{ "regexp": "^(?!.*Failed\\sasserting)(.+)$", "message": 1 },
{ "regexp": "^.*Failed\\sasserting\\sthat.*$" },
{ "regexp": "^(.*):(\\d+)$", "file": 1, "line": 2 }
]
},
{
"owner": "phpunit-custom-message-blank",
"pattern": [
{ "regexp": "^\\d+\\)\\s.*$" },
{ "regexp": "^(?!.*Failed\\sasserting)(.+)$", "message": 1 },
{ "regexp": "^.*Failed\\sasserting\\sthat.*$" },
{ "regexp": "^\\s*$" },
{ "regexp": "^(.*):(\\d+)$", "file": 1, "line": 2 }
]
},
{
"owner": "phpunit-other-blank",
"pattern": [
{ "regexp": "^\\d+\\)\\s.*$" },
{ "regexp": "^(?!.*Failed\\sasserting)(.+)$", "message": 1 },
{ "regexp": "^(?:\\s*|[-+@ ].*)$" },
{ "regexp": "^(.*):(\\d+)$", "file": 1, "line": 2 }
]
},
{
"owner": "phpunit-other",
"pattern": [
{ "regexp": "^\\d+\\)\\s.*$" },
{ "regexp": "^(?!.*Failed\\sasserting)(.+)$", "message": 1 },
{ "regexp": "^(.*):(\\d+)$", "file": 1, "line": 2 }
]
},
{
"owner": "phpunit-warning",
"severity": "warning",
"pattern": [
{ "regexp": "^There (?:was|were) \\d+ (?:(?:risky|skipped) tests?(?: suites?)?|(?:PHPUnit(?: test runner)? )?warnings?):$" },
{ "regexp": "^(?:(\\s*(/.*|[A-Za-z]:[\\\\/].*):(\\d+)|(?!-+$|There (?:was|were) \\d+ .+:$|\\d+ tests? triggered \\d+ .+:$|OK(?: \\(\\d+ tests?, \\d+ assertions?\\)|, but (?:there were issues|some tests were skipped|incomplete, skipped, or risky tests)!)$|(?:FAILURES|ERRORS|WARNINGS)!$|Tests: \\d+(?:,|\\.?$)|PHPUnit \\d+\\.\\S+ by |Triggered by:$).*)|Triggered by:)$", "message": 1, "file": 2, "line": 3, "loop": true }
]
},
{
"owner": "phpunit-notice",
"severity": "notice",
"pattern": [
{ "regexp": "^There (?:was|were) \\d+ (?:incomplete tests?(?: suites?)?|(?:PHPUnit(?: test runner)? )?notices?):$" },
{ "regexp": "^(?:(\\s*(/.*|[A-Za-z]:[\\\\/].*):(\\d+)|(?!-+$|There (?:was|were) \\d+ .+:$|\\d+ tests? triggered \\d+ .+:$|OK(?: \\(\\d+ tests?, \\d+ assertions?\\)|, but (?:there were issues|some tests were skipped|incomplete, skipped, or risky tests)!)$|(?:FAILURES|ERRORS|WARNINGS)!$|Tests: \\d+(?:,|\\.?$)|PHPUnit \\d+\\.\\S+ by |Triggered by:$).*)|Triggered by:)$", "message": 1, "file": 2, "line": 3, "loop": true }
]
},
{
"owner": "phpunit-issue",
"pattern": [
{ "regexp": "^\\d+ tests? triggered \\d+ (?:PHP(?:Unit)? )?(error|warning|notice)s?:$", "severity": 1 },
{ "regexp": "^(?:\\d+\\)\\s)?(?:(\\s*(/.*|[A-Za-z]:[\\\\/].*):(\\d+)|(?!-+$|There (?:was|were) \\d+ .+:$|\\d+ tests? triggered \\d+ .+:$|OK(?: \\(\\d+ tests?, \\d+ assertions?\\)|, but (?:there were issues|some tests were skipped|incomplete, skipped, or risky tests)!)$|(?:FAILURES|ERRORS|WARNINGS)!$|Tests: \\d+(?:,|\\.?$)|PHPUnit \\d+\\.\\S+ by |Triggered by:$).*)|Triggered by:)$", "message": 1, "file": 2, "line": 3, "loop": true }
] ]
} }
] ]
+5 -24
View File
@@ -42,14 +42,6 @@
"version_prefix": "", "version_prefix": "",
"version_parameter": "diagnose" "version_parameter": "diagnose"
}, },
"cpx": {
"type": "phar",
"repository": "laravel/cpx",
"extension": "",
"domain": "https://github.com",
"version_prefix": "v",
"version_parameter": "--version"
},
"cs2pr": { "cs2pr": {
"type": "phar", "type": "phar",
"repository": "staabm/annotate-pull-request-from-checkstyle", "repository": "staabm/annotate-pull-request-from-checkstyle",
@@ -153,17 +145,12 @@
"version_parameter": "-V" "version_parameter": "-V"
}, },
"phpstan": { "phpstan": {
"type": "composer", "type": "phar",
"repository": "phpstan/phpstan", "repository": "phpstan/phpstan",
"scope": "scoped", "extension": ".phar",
"fallback": { "domain": "https://github.com",
"type": "phar", "version_prefix": "",
"repository": "phpstan/phpstan", "version_parameter": "-V"
"extension": ".phar",
"domain": "https://github.com",
"version_prefix": "",
"version_parameter": "-V"
}
}, },
"pie": { "pie": {
"type": "phar", "type": "phar",
@@ -247,12 +234,6 @@
"repository": "laravel/vapor-cli", "repository": "laravel/vapor-cli",
"scope": "scoped" "scope": "scoped"
}, },
"cloud-cli": {
"type": "composer",
"alias": "laravel-cloud",
"repository": "laravel/cloud-cli",
"scope": "scoped"
},
"rector": { "rector": {
"type": "composer", "type": "composer",
"repository": "rector/rector", "repository": "rector/rector",
+114 -152
View File
@@ -1,5 +1,5 @@
{ {
"$schema": "https://json-schema.org/draft/2020-12/schema", "$schema": "http://json-schema.org/draft-07/schema#",
"$id": "https://raw.githubusercontent.com/shivammathur/setup-php/develop/src/configs/tools_schema.json", "$id": "https://raw.githubusercontent.com/shivammathur/setup-php/develop/src/configs/tools_schema.json",
"type": "object", "type": "object",
"title": "Tools", "title": "Tools",
@@ -14,161 +14,123 @@
"function": "function_name", "function": "function_name",
"repository": "user/tool", "repository": "user/tool",
"packagist": "user/tool", "packagist": "user/tool",
"scope": "scoped", "scope": "global, scoped",
"type": "composer", "type": "phar, composer, custom-package or custom-function",
"version_parameter": "--version", "version_parameter": "--version",
"version_prefix": "v", "version_prefix": "v"
"fallback": {
"type": "phar",
"repository": "user/tool",
"domain": "https://github.com",
"extension": ".phar",
"version_prefix": "v",
"version_parameter": "--version"
}
} }
} }
], ],
"additionalProperties": { "items": {
"$ref": "#/$defs/tool" "properties": {
}, "alias": {
"$defs": { "$id": "#/items/properties/alias",
"tool": { "type": "string",
"type": "object", "title": "The alias schema",
"properties": { "description": "Alias for a tool.",
"alias": { "examples": [
"type": "string", "tool_alias"
"title": "The alias schema", ]
"description": "Alias for a tool.",
"examples": [
"tool_alias"
]
},
"domain": {
"type": "string",
"title": "The domain schema",
"description": "Domain URL of the tool.",
"examples": [
"https://example.com"
]
},
"extension": {
"type": "string",
"title": "The extension schema",
"description": "File extension of the tool.",
"examples": [
".ext"
]
},
"fetch_latest": {
"type": "string",
"title": "The fetch_latest schema",
"description": "Fetch the latest version from GitHub releases.",
"enum": [
"true",
"false"
]
},
"function": {
"type": "string",
"title": "The function schema",
"description": "Function name in tools.ts which returns the script to setup the tool.",
"examples": [
"function_name"
]
},
"repository": {
"type": "string",
"title": "The repository schema",
"description": "GitHub repository of the tool.",
"examples": [
"user/tool"
]
},
"packagist": {
"type": "string",
"title": "The repository schema",
"description": "Packagist repository of the tool in case different from repository.",
"examples": [
"user/tool"
]
},
"scope": {
"type": "string",
"title": "The scope schema",
"description": "Scope of tool installation: global or scoped",
"enum": [
"global",
"scoped"
]
},
"type": {
"type": "string",
"title": "The type schema",
"description": "Type of tool: phar, composer, custom-package or custom-function.",
"enum": [
"phar",
"composer",
"custom-package",
"custom-function"
]
},
"version_parameter": {
"type": "string",
"title": "The version_parameter schema",
"description": "Parameter to get the tool version.",
"examples": [
"--version"
]
},
"version_prefix": {
"type": "string",
"title": "The version_prefix schema",
"description": "Prefix of the version in the download URL.",
"examples": [
"v"
]
},
"fallback": {
"$ref": "#/$defs/pharFallback"
}
}, },
"required": [ "domain": {
"type" "$id": "#/items/properties/domain",
], "type": "string",
"additionalProperties": true "title": "The domain schema",
"description": "Domain URL of the tool.",
"examples": [
"https://example.com"
]
},
"extension": {
"$id": "#/items/properties/extension",
"type": "string",
"title": "The extension schema",
"description": "File extension of the tool.",
"examples": [
".ext"
]
},
"fetch_latest": {
"$id": "#/items/properties/fetch_latest",
"type": "string",
"title": "The fetch_latest schema",
"description": "Fetch the latest version from GitHub releases.",
"enum": [
"true",
"false"
]
},
"function": {
"$id": "#/items/properties/function",
"type": "string",
"title": "The function schema",
"description": "Function name in tools.ts which returns the script to setup the tool.",
"examples": [
"function_name"
]
},
"repository": {
"$id": "#/items/properties/repository",
"type": "string",
"title": "The repository schema",
"description": "GitHub repository of the tool.",
"examples": [
"user/tool"
]
},
"packagist": {
"$id": "#/items/properties/packagist",
"type": "string",
"title": "The repository schema",
"description": "Packagist repository of the tool in case different from repository.",
"examples": [
"user/tool"
]
},
"scope": {
"$id": "#/items/properties/scope",
"type": "string",
"title": "The scope schema",
"description": "Scope of tool installation: global or scoped",
"enum": [
"global",
"scoped"
]
},
"type": {
"$id": "#/items/properties/type",
"type": "string",
"title": "The type schema",
"description": "Type of tool: phar, composer, custom-package or custom-function.",
"enum": [
"phar",
"composer",
"custom-package",
"custom-function"
]
},
"version_parameter": {
"$id": "#/items/properties/version_parameter",
"type": "string",
"title": "The version_parameter schema",
"description": "Parameter to get the tool version.",
"examples": [
"--version"
]
},
"version_prefix": {
"$id": "#/items/properties/version_prefix",
"type": "string",
"title": "The version_prefix schema",
"description": "Prefix of the version in the download URL.",
"examples": [
"v"
]
}
}, },
"pharFallback": { "required": [
"type": "object", "type"
"title": "The fallback schema", ],
"description": "PHAR installation settings used when Composer installation fails.", "additionalProperties": true
"properties": {
"type": {
"const": "phar"
},
"repository": {
"$ref": "#/$defs/tool/properties/repository"
},
"domain": {
"$ref": "#/$defs/tool/properties/domain"
},
"extension": {
"$ref": "#/$defs/tool/properties/extension"
},
"fetch_latest": {
"$ref": "#/$defs/tool/properties/fetch_latest"
},
"version_parameter": {
"$ref": "#/$defs/tool/properties/version_parameter"
},
"version_prefix": {
"$ref": "#/$defs/tool/properties/version_prefix"
}
},
"required": [
"type"
],
"additionalProperties": false
}
} }
} }
+3 -3
View File
@@ -1,6 +1,6 @@
import * as utils from './utils.js'; import * as utils from './utils';
import * as extensions from './extensions.js'; import * as extensions from './extensions';
import * as config from './config.js'; import * as config from './config';
export async function checkXdebugError( export async function checkXdebugError(
extension: string, extension: string,
+4 -13
View File
@@ -1,4 +1,4 @@
import * as utils from './utils.js'; import * as utils from './utils';
/** /**
* Install and enable extensions for darwin * Install and enable extensions for darwin
@@ -84,21 +84,12 @@ export async function addExtensionDarwin(
case /(5\.[3-6]|7\.0)pcov/.test(version_extension): case /(5\.[3-6]|7\.0)pcov/.test(version_extension):
add_script += await utils.getUnsupportedLog('pcov', version, 'darwin'); add_script += await utils.getUnsupportedLog('pcov', version, 'darwin');
return; return;
// match 7.2xdebug2 to 7.4xdebug2
case /^7\.[2-4]xdebug2$/.test(version_extension):
add_script += await utils.joins(
'\nadd_brew_extension',
'xdebug2',
ext_prefix,
'2.9.8'
);
return;
// match brew extensions // match brew extensions
case /(?<!5\.[3-5])(amqp|apcu|brotli|excimer|expect|gmagick|gnupg|grpc|igbinary|imagick|imap|interbase|lua|mailparse|maxminddb|mcrypt|memcache|memcached|mongodb|mongodb1|msgpack|newrelic|oauth|opentelemetry|pdo_firebird|pinba|protobuf|psr|raphf|rdkafka|redis|scalar_objects|seaslog|snmp|spx|ssh2|swoole|uopz|uploadprogress|uuid|vld|xdebug|xdebug2|xhprof|yaml|zmq|zstd)/.test( case /(?<!5\.[3-5])(amqp|apcu|brotli|excimer|expect|gmagick|gnupg|grpc|igbinary|imagick|imap|interbase|mailparse|maxminddb|mcrypt|memcache|memcached|mongodb|mongodb1|msgpack|newrelic|oauth|opentelemetry|pdo_firebird|pinba|protobuf|psr|raphf|rdkafka|redis|scalar_objects|seaslog|snmp|spx|ssh2|swoole|uopz|uploadprogress|uuid|vld|xdebug|xdebug2|xhprof|yaml|zmq|zstd)/.test(
version_extension version_extension
): ):
case /(?<!5\.[3-6])(ds|v8js)/.test(version_extension): case /(?<!5\.[3-6])(ds|v8js)/.test(version_extension):
case /(5\.6|7\.[0-4])(propro)/.test(version_extension): case /(5\.6|7\.[0-4])(propro|lua)/.test(version_extension):
case /(?<!5\.[3-6]|7\.0)pcov/.test(version_extension): case /(?<!5\.[3-6]|7\.0)pcov/.test(version_extension):
case /(?<!5\.[3-6])(ast|vips|xlswriter)/.test(version_extension): case /(?<!5\.[3-6])(ast|vips|xlswriter)/.test(version_extension):
case /^(8\.[0-5])swow$/.test(version_extension): case /^(8\.[0-5])swow$/.test(version_extension):
@@ -180,7 +171,7 @@ export async function addExtensionWindows(
add_script += await utils.joins( add_script += await utils.joins(
'\nAdd-Extension', '\nAdd-Extension',
ext_name, ext_name,
ext_version ext_version.replace('stable', '')
); );
break; break;
// match extensions for compiling from source // match extensions for compiling from source
+9 -12
View File
@@ -1,15 +1,12 @@
import {fileURLToPath} from 'url';
import path from 'path'; import path from 'path';
import {exec} from '@actions/exec';
import fs from 'fs'; import fs from 'fs';
import * as config from './config.js'; import {exec} from '@actions/exec';
import * as core from './core.js'; import * as config from './config';
import * as coverage from './coverage.js'; import * as core from './core';
import * as extensions from './extensions.js'; import * as coverage from './coverage';
import * as tools from './tools.js'; import * as extensions from './extensions';
import * as utils from './utils.js'; import * as tools from './tools';
import * as utils from './utils';
const dirname = path.dirname(fileURLToPath(import.meta.url));
/** /**
* Build the script * Build the script
@@ -19,7 +16,7 @@ const dirname = path.dirname(fileURLToPath(import.meta.url));
export async function getScript(os: string): Promise<string> { export async function getScript(os: string): Promise<string> {
const url = 'https://setup-php.com/sponsor'; const url = 'https://setup-php.com/sponsor';
const filename = os + (await utils.scriptExtension(os)); const filename = os + (await utils.scriptExtension(os));
const script_path = path.join(dirname, '../src/scripts', filename); const script_path = path.join(__dirname, '../src/scripts', filename);
const run_path = script_path.replace(os, 'run'); const run_path = script_path.replace(os, 'run');
const extension_csv: string = utils.sanitizeShellInput( const extension_csv: string = utils.sanitizeShellInput(
await utils.getInput('extensions', false), await utils.getInput('extensions', false),
@@ -50,7 +47,7 @@ export async function getScript(os: string): Promise<string> {
fs.writeFileSync(run_path, script, {mode: 0o755}); fs.writeFileSync(run_path, script, {mode: 0o755});
return await utils.addVerbose(run_path, os); return run_path;
} }
/** /**
+1 -1
View File
@@ -1,5 +1,5 @@
import * as cv from 'compare-versions'; import * as cv from 'compare-versions';
import * as fetch from './fetch.js'; import * as fetch from './fetch';
type RS = Record<string, string>; type RS = Record<string, string>;
type RSRS = Record<string, RS>; type RSRS = Record<string, RS>;
+35 -82
View File
@@ -13,11 +13,11 @@ handle_dependency_extensions() {
suffix="$(get_php_formula_suffix)" suffix="$(get_php_formula_suffix)"
if [[ -n "$suffix" ]]; then if [[ -n "$suffix" ]]; then
brew_opts=(-sf) brew_opts=(-sf)
patch_abstract_file >/dev/null 2>&1 patch_abstract_file
for dependency_extension in "${dependency_extensions[@]}"; do for dependency_extension in "${dependency_extensions[@]}"; do
safe_brew install --skip-link "${brew_opts[@]}" "$ext_tap/$dependency_extension@$version" >/dev/null 2>&1 && safe_brew install --skip-link "${brew_opts[@]}" "$ext_tap/$dependency_extension@$version" &&
brew link --overwrite --force "$dependency_extension@$version" >/dev/null 2>&1 && brew link --overwrite --force "$dependency_extension@$version" &&
copy_brew_extensions "$dependency_extension" || return $? copy_brew_extensions "$dependency_extension"
done done
fi fi
} }
@@ -33,7 +33,7 @@ disable_extension_helper() {
sudo sed -Ei '' "/=(.*\/)?\"?$extension(.so)?$/d" "${ini_file:?}" sudo sed -Ei '' "/=(.*\/)?\"?$extension(.so)?$/d" "${ini_file:?}"
sudo rm -rf "$scan_dir"/*"$extension"* /tmp/php"$version"_extensions sudo rm -rf "$scan_dir"/*"$extension"* /tmp/php"$version"_extensions
mkdir -p /tmp/extdisabled/"$version" mkdir -p /tmp/extdisabled/"$version"
echo '' | sudo tee /tmp/extdisabled/"$version"/"$extension" >/dev/null 2>&1 echo '' | sudo tee /tmp/extdisabled/"$version"/"$extension"
} }
# Function to get extension name from brew formula. # Function to get extension name from brew formula.
@@ -71,42 +71,25 @@ copy_brew_extensions() {
fi fi
} }
# Install an extension and its variant-specific dependencies with the current Brew state.
install_brew_extension() {
local formula=$1
local extension=$2
handle_dependency_extensions "$formula" "$extension" &&
safe_brew install --skip-link "${brew_opts[@]}" "$ext_tap/$formula@$version" &&
brew link --overwrite --force "$formula@$version" &&
copy_brew_extensions "$formula"
}
# Function to install a php extension from shivammathur/extensions tap. # Function to install a php extension from shivammathur/extensions tap.
add_brew_extension() { add_brew_extension() {
formula=$1 formula=$1
prefix=$2 prefix=$2
expected_version=${3:-}
extension="$(get_extension_from_formula "$formula")" extension="$(get_extension_from_formula "$formula")"
enable_extension "$extension" "$prefix" enable_extension "$extension" "$prefix"
if check_extension "$extension" && { [ -z "$expected_version" ] || check_extension_version "$extension" "$expected_version"; }; then if check_extension "$extension"; then
add_log "${tick:?}" "$extension" "Enabled" add_log "${tick:?}" "$extension" "Enabled"
else else
add_brew_tap "$php_tap" add_brew_tap "$php_tap"
add_brew_tap "$ext_tap" add_brew_tap "$ext_tap"
formula="$(get_renamed_formula "$formula")" formula="$(get_renamed_formula "$formula")"
update_dependencies
handle_dependency_extensions "$formula" "$extension"
( (
patch_brew safe_brew install --skip-link "${brew_opts[@]}" "$ext_tap/$formula@$version" &&
# Keep the watchdog, but refresh before retrying a failed first attempt. brew link --overwrite --force "$formula@$version" &&
SETUP_PHP_BREW_RETRY_ATTEMPTS=1 install_brew_extension "$formula" "$extension" || { copy_brew_extensions "$formula"
update_dependencies && install_brew_extension "$formula" "$extension" ) || pecl_install "$extension"
}
) >/dev/null 2>&1 || {
if [ -n "$expected_version" ]; then
pecl_install "$extension-$expected_version" || pecl_install "$extension"
else
pecl_install "$extension"
fi
} >/dev/null 2>&1
add_extension_log "$extension" "Installed and enabled" add_extension_log "$extension" "Installed and enabled"
fi fi
} }
@@ -115,7 +98,7 @@ add_brew_extension() {
patch_abstract_file() { patch_abstract_file() {
abstract_path="$tap_dir"/"$ext_tap"/Abstract/abstract-php-extension.rb abstract_path="$tap_dir"/"$ext_tap"/Abstract/abstract-php-extension.rb
if [[ -e "$abstract_path" && ! -e /tmp/abstract_patch ]]; then if [[ -e "$abstract_path" && ! -e /tmp/abstract_patch ]]; then
echo '' | sudo tee /tmp/abstract_patch >/dev/null 2>&1 echo '' | sudo tee /tmp/abstract_patch
sudo sed -i '' -e "s|php@#{\(.*\)}|php@#{\1}$suffix|g" -e "s|php_version /|\"#{php_version}$suffix\" /|g" "$abstract_path" sudo sed -i '' -e "s|php@#{\(.*\)}|php@#{\1}$suffix|g" -e "s|php_version /|\"#{php_version}$suffix\" /|g" "$abstract_path"
fi fi
} }
@@ -125,9 +108,9 @@ add_extension_helper() {
local extension=$1 local extension=$1
prefix=$2 prefix=$2
if [[ "$version" =~ ${old_versions:?} ]] && [ "$extension" = "imagick" ]; then if [[ "$version" =~ ${old_versions:?} ]] && [ "$extension" = "imagick" ]; then
run_script "php5-darwin" "${version/./}" "$extension" >/dev/null 2>&1 run_script "php5-darwin" "${version/./}" "$extension"
else else
pecl_install "$extension" >/dev/null 2>&1 && pecl_install "$extension" &&
if [[ "$version" =~ ${old_versions:?} ]]; then echo "$prefix=$ext_dir/$extension.so" >>"$ini_file"; fi if [[ "$version" =~ ${old_versions:?} ]]; then echo "$prefix=$ext_dir/$extension.so" >>"$ini_file"; fi
fi fi
add_extension_log "$extension" "Installed and enabled" add_extension_log "$extension" "Installed and enabled"
@@ -141,8 +124,8 @@ add_devtools() {
# Function to handle request to add PECL. # Function to handle request to add PECL.
add_pecl() { add_pecl() {
enable_extension xml extension >/dev/null 2>&1 enable_extension xml extension
configure_pecl >/dev/null 2>&1 configure_pecl
pear_version=$(get_tool_version "pecl" "version") pear_version=$(get_tool_version "pecl" "version")
add_log "${tick:?}" "PECL" "Found PECL $pear_version" add_log "${tick:?}" "PECL" "Found PECL $pear_version"
} }
@@ -167,19 +150,15 @@ patch_brew() {
# Function to update dependencies. # Function to update dependencies.
update_dependencies() { update_dependencies() {
patch_brew
if ! [ -e /tmp/update_dependencies ]; then if ! [ -e /tmp/update_dependencies ]; then
local repos=("$brew_repo") for repo in "$brew_repo" "${core_repo:?}"; do
if [ -n "${HOMEBREW_NO_INSTALL_FROM_API:-}" ]; then if [ -e "$repo" ]; then
repos+=("${core_repo:?}") git_retry -C "$repo" fetch origin main && git -C "$repo" reset --hard origin/main
fi
for repo in "${repos[@]}"; do
if [ -d "$repo" ]; then
git_retry -C "$repo" fetch origin main && git -C "$repo" reset --hard origin/main || return $?
fi fi
done done
echo '' | sudo tee /tmp/update_dependencies >/dev/null 2>&1 echo '' | sudo tee /tmp/update_dependencies
fi fi
patch_brew
} }
# Function to get PHP version if it is already installed using Homebrew. # Function to get PHP version if it is already installed using Homebrew.
@@ -195,49 +174,27 @@ get_brewed_php() {
fi fi
} }
# Function to setup PHP from the cached builds.
setup_cached_versions() {
latest="releases/download/php-$version" run_script \
"php-darwin" "$version" "${debug:?}" "${ts:?}" "" "${INPUT_EXTENSIONS:-}" >/dev/null 2>&1
}
# Function to setup PHP 5.6 and newer using Homebrew. # Function to setup PHP 5.6 and newer using Homebrew.
add_php() { add_php() {
local exit_code php_alias
action=$1 action=$1
existing_version=$2 existing_version=$2
suffix="$(get_php_formula_suffix)" suffix="$(get_php_formula_suffix)"
php_keg="php@$version$suffix" php_keg="php@$version$suffix"
php_formula="shivammathur/php/$php_keg" php_formula="shivammathur/php/$php_keg"
if [[ "$existing_version" = "false" || -n "$suffix" || "$action" = "upgrade" ]]; then if [[ "$existing_version" = "false" || -n "$suffix" || "$action" = "upgrade" ]]; then
if [ "$(uname -m)" = "x86_64" ] || { [ "${runner:?}" != "self-hosted" ] && [ "${use_builds_cache:-true}" != "false" ]; }; then
setup_cached_versions && return 0
[ "$(uname -m)" != "x86_64" ] || return 1
fi
update_dependencies update_dependencies
add_brew_tap "$php_tap" add_brew_tap "$php_tap"
fi fi
# Resolve PHP aliases before invoking brew to avoid scanning unrelated installed formulae.
php_alias="$tap_dir/$php_tap/Aliases/$php_keg"
if [ -L "$php_alias" ]; then
php_keg="$(basename "$(readlink "$php_alias")" .rb)"
php_formula="shivammathur/php/$php_keg"
fi
if [[ "$existing_version" != "false" && -z "$suffix" ]]; then if [[ "$existing_version" != "false" && -z "$suffix" ]]; then
if [ "$action" = "upgrade" ]; then if [ "$action" = "upgrade" ]; then
safe_brew install --only-dependencies "$php_formula" || return $? safe_brew install --only-dependencies "$php_formula"
safe_brew upgrade -f --overwrite "$php_formula" || return $? safe_brew upgrade -f --overwrite "$php_formula"
else else
brew unlink "$php_keg" brew unlink "$php_keg"
fi fi
else else
safe_brew install --only-dependencies "$php_formula" || return $? safe_brew install --only-dependencies "$php_formula"
safe_brew install --skip-link -f --overwrite "$php_formula" 2>/dev/null || { safe_brew install --skip-link -f --overwrite "$php_formula" 2>/dev/null || safe_brew upgrade -f --overwrite "$php_formula"
exit_code=$?
# A timeout has exhausted its retries; do not start another build via upgrade.
[ "$exit_code" -ne 124 ] || return "$exit_code"
safe_brew upgrade -f --overwrite "$php_formula" || return $?
}
fi fi
brew link --force --overwrite "$php_keg" || (sudo chown -R "$(id -un)":"$(id -gn)" "$brew_prefix" && brew link --force --overwrite "$php_keg") brew link --force --overwrite "$php_keg" || (sudo chown -R "$(id -un)":"$(id -gn)" "$brew_prefix" && brew link --force --overwrite "$php_keg")
} }
@@ -266,7 +223,7 @@ add_php_config() {
if [[ "$ini" = "production" || "$ini" = "development" ]]; then if [[ "$ini" = "production" || "$ini" = "development" ]]; then
sudo cp "$ini_dir"/php.ini-"$ini" "$ini_dir"/php.ini sudo cp "$ini_dir"/php.ini-"$ini" "$ini_dir"/php.ini
elif [ "$ini" = "none" ]; then elif [ "$ini" = "none" ]; then
echo '' | sudo tee "${ini_file[@]}" >/dev/null 2>&1 echo '' | sudo tee "${ini_file[@]}"
fi fi
} }
@@ -281,7 +238,7 @@ get_scan_dir() {
# Function to handle self-hosted runner setup. # Function to handle self-hosted runner setup.
self_hosted_helper() { self_hosted_helper() {
sudo mkdir -p /opt/hostedtoolcache >/dev/null 2>&1 || true sudo mkdir -p /opt/hostedtoolcache || true
} }
# Function to Setup PHP. # Function to Setup PHP.
@@ -290,24 +247,18 @@ setup_php() {
php_config="$(command -v php-config 2>/dev/null)" php_config="$(command -v php-config 2>/dev/null)"
update=true update=true
check_pre_installed check_pre_installed
existing_version=$([ "$(uname -m)" != "x86_64" ] && get_brewed_php || echo false) existing_version=$(get_brewed_php)
status="Found" status="Found"
if [[ "$version" =~ ${old_versions:?} ]]; then if [[ "$version" =~ ${old_versions:?} ]]; then
run_script "php5-darwin" "${version/./}" >/dev/null 2>&1 run_script "php5-darwin" "${version/./}"
status="Installed" status="Installed"
elif [[ "${existing_version:0:3}" != "$version" || -n "$(get_php_formula_suffix)" ]]; then elif [ "${existing_version:0:3}" != "$version" ]; then
add_php "install" "$existing_version" >/dev/null 2>&1 || { add_php "install" "$existing_version"
add_log "${cross:?}" "PHP" "Could not install PHP $version"
exit 1
}
status="Installed" status="Installed"
elif [[ "${existing_version:0:3}" = "$version" && "${update:?}" = "true" ]]; then elif [[ "${existing_version:0:3}" = "$version" && "${update:?}" = "true" ]]; then
brew_php_version="$(brew info --json "php@$version" 2>/dev/null | jq -r '.[].versions.stable')" brew_php_version="$(brew info --json "php@$version" 2>/dev/null | jq -r '.[].versions.stable')"
if [ "$brew_php_version" != "$existing_version" ]; then if [ "$brew_php_version" != "$existing_version" ]; then
add_php "upgrade" "$existing_version" >/dev/null 2>&1 || { add_php "upgrade" "$existing_version"
add_log "${cross:?}" "PHP" "Could not upgrade PHP $version"
exit 1
}
status="Upgraded" status="Upgraded"
fi fi
fi fi
@@ -345,6 +296,7 @@ export HOMEBREW_NO_AUTO_UPDATE=1
export HOMEBREW_NO_ENV_HINTS=1 export HOMEBREW_NO_ENV_HINTS=1
export HOMEBREW_NO_INSTALL_CLEANUP=1 export HOMEBREW_NO_INSTALL_CLEANUP=1
export HOMEBREW_NO_INSTALLED_DEPENDENTS_CHECK=1 export HOMEBREW_NO_INSTALLED_DEPENDENTS_CHECK=1
export HOMEBREW_NO_INSTALL_FROM_API=1
# shellcheck source=. # shellcheck source=.
. "${scripts:?}"/unix.sh . "${scripts:?}"/unix.sh
@@ -353,6 +305,7 @@ export HOMEBREW_NO_INSTALLED_DEPENDENTS_CHECK=1
. "${scripts:?}"/tools/add_tools.sh . "${scripts:?}"/tools/add_tools.sh
. "${scripts:?}"/extensions/source.sh . "${scripts:?}"/extensions/source.sh
. "${scripts:?}"/extensions/add_extensions.sh . "${scripts:?}"/extensions/add_extensions.sh
set -x
configure_brew configure_brew
read_env read_env
self_hosted_setup self_hosted_setup
+4 -62
View File
@@ -104,51 +104,11 @@ Function Add-Extension {
[string] [string]
$extension_version = '' $extension_version = ''
) )
$minimum_stability_requested = $PSBoundParameters.ContainsKey('stability') -and $extension_version -eq ''
$extension_backup = ''
$restore_startup_errors = $false
try { try {
$extension_info = Get-PhpExtension -Path $php_dir | Where-Object { $_.Name -eq $extension -or $_.Handle -eq $extension }
$deps_dir = "$ext_dir\$extension-vc$($installed.VCVersion)-$arch" $deps_dir = "$ext_dir\$extension-vc$($installed.VCVersion)-$arch"
New-Item $deps_dir -Type Directory -Force > $null 2>&1 New-Item $deps_dir -Type Directory -Force > $null 2>&1
$cached = $extension_version -ne '' -and (Test-Path "$ext_dir\$extension-$extension_version") if ($null -ne $extension_info) {
$extension_info = $null
if(-not $cached) {
$extension_info = Get-PhpExtension -Path $php_dir | Where-Object { $_.Name -eq $extension -or $_.Handle -eq $extension }
}
# Only suppress startup errors while probing a cached DLL or replacing an installed DLL.
if($cached -or (($minimum_stability_requested -or ($extension_version -ne '' -and $extension_info.Version -ne $extension_version)) -and (Test-Path "$ext_dir\php_$extension.dll"))) {
$startup_errors = Get-PhpIniKey -Key display_startup_errors -Path "$php_dir\php.ini"
if($startup_errors -notmatch '^(0|off|false|no)$') {
$restore_startup_errors = $true
Set-PhpIniKey -Key display_startup_errors -Value Off -Path "$php_dir\php.ini"
}
}
if($cached) {
# Preserve the active DLL before probing a cache entry for another PHP build.
if(Test-Path "$ext_dir\php_$extension.dll") {
$extension_info = Get-PhpExtension -Path "$ext_dir\php_$extension.dll"
$backup_name = if($extension_info.Version) { "$extension-$($extension_info.Version)" } else { "$extension.bak" }
Copy-Item "$ext_dir\php_$extension.dll" "$ext_dir\$backup_name" -Force -ErrorAction Stop
$extension_backup = "$ext_dir\$backup_name"
}
Copy-Item "$ext_dir\$extension-$extension_version" "$ext_dir\php_$extension.dll" -Force
try {
Enable-ExtensionDependencies $extension
Enable-PhpExtension -Extension $extension -Path $php_dir
Set-ExtensionPrerequisites $extension
$cached_extension = Get-PhpExtension -Path $php_dir | Where-Object { ($_.Name -eq $extension -or $_.Handle -eq $extension) -and $_.State -eq 'Enabled' }
if($null -ne $cached_extension) {
Add-Log $tick $extension "Enabled"
return
}
} catch {
Write-Verbose "Could not enable cached ${extension}: $_"
}
# A cached DLL may target another PHP build; install it again if it did not load.
Remove-Item "$ext_dir\php_$extension.dll" -Force
$extension_info = $null
}
if ($null -ne $extension_info -and ($extension_info.State -eq 'Builtin' -or (-not $minimum_stability_requested -and ($extension_version -eq '' -or $extension_info.Version -eq $extension_version)))) {
switch ($extension_info.State) { switch ($extension_info.State) {
'Builtin' { 'Builtin' {
Add-Log $tick $extension "Enabled" Add-Log $tick $extension "Enabled"
@@ -170,41 +130,23 @@ Function Add-Extension {
if ($version -match '8.[1-4]' -and $stability -eq 'stable') { if ($version -match '8.[1-4]' -and $stability -eq 'stable') {
$minimumStability = 'snapshot' $minimumStability = 'snapshot'
} }
$maximumStability = if ($extension_version -eq '') { 'stable' } else { $stability }
$params = @{ Extension = $extension; MinimumStability = $minimumStability; MaximumStability = $maximumStability; Path = $php_dir; AdditionalFilesPath = $deps_dir; NoDependencies = $true } $params = @{ Extension = $extension; MinimumStability = $minimumStability; MaximumStability = $stability; Path = $php_dir; AdditionalFilesPath = $deps_dir; NoDependencies = $true }
if ($extension_version -ne '') if ($extension_version -ne '')
{ {
$params["Version"] = $extension_version $params["Version"] = $extension_version
} }
# If extension for a different version exists # If extension for a different version exists
if(Test-Path $ext_dir\php_$extension.dll) { if(Test-Path $ext_dir\php_$extension.dll) {
# Keep backups outside PhpManager's DLL scan and reuse known versions as cache entries. Move-Item $ext_dir\php_$extension.dll $ext_dir\php_$extension.bak.dll -Force
$backup_name = if($extension_info.Version) { "$extension-$($extension_info.Version)" } else { "$extension.bak" }
Move-Item $ext_dir\php_$extension.dll "$ext_dir\$backup_name" -Force -ErrorAction Stop
$extension_backup = "$ext_dir\$backup_name"
} }
Install-PhpExtension @params Install-PhpExtension @params
Set-ExtensionPrerequisites $extension Set-ExtensionPrerequisites $extension
} }
Add-Log $tick $extension "Installed and enabled" Add-Log $tick $extension "Installed and enabled"
} }
if($extension_version -ne '' -and (Test-Path "$ext_dir\php_$extension.dll")) {
Copy-Item "$ext_dir\php_$extension.dll" "$ext_dir\$extension-$extension_version" -Force
}
} catch { } catch {
if($extension_backup -ne '') {
Copy-Item $extension_backup "$ext_dir\php_$extension.dll" -Force
}
Add-Log $cross $extension "Could not install $extension on PHP $( $installed.FullVersion )" Add-Log $cross $extension "Could not install $extension on PHP $( $installed.FullVersion )"
} finally {
if($restore_startup_errors) {
if($null -eq $startup_errors) {
Set-PhpIniKey -Key display_startup_errors -Delete -Path "$php_dir\php.ini"
} else {
Set-PhpIniKey -Key display_startup_errors -Value $startup_errors -Path "$php_dir\php.ini"
}
}
} }
} }
+32 -74
View File
@@ -21,13 +21,6 @@ check_extension() {
fi fi
} }
# Function to test the loaded version of an extension.
check_extension_version() {
local extension=$1
local ext_version=$2
php -d display_errors=0 -r "exit(phpversion(\$argv[1]) === \$argv[2] ? 0 : 1);" -- "$extension" "$ext_version" >/dev/null 2>&1
}
# Function to check if extension is shared # Function to check if extension is shared
shared_extension() { shared_extension() {
[ -e "${ext_dir:?}/$1.so" ] [ -e "${ext_dir:?}/$1.so" ]
@@ -57,7 +50,7 @@ enable_extension() {
[ -d "$modules_dir" ] && sudo find "$modules_dir" -path "*disabled*$1" -delete [ -d "$modules_dir" ] && sudo find "$modules_dir" -path "*disabled*$1" -delete
enable_extension_dependencies "$1" "$2" enable_extension_dependencies "$1" "$2"
enable_cache_extension_dependencies "$1" "$2" enable_cache_extension_dependencies "$1" "$2"
if ! [[ "${version:?}" =~ ${old_versions:?} ]] && command -v phpenmod >/dev/null 2>&1; then if ! [[ "${version:?}" =~ ${old_versions:?} ]] && command -v phpenmod ; then
sudo sed -Ei "/=(.*\/)?\"?$extension(.so)?\"?$/d" "$pecl_file" sudo sed -Ei "/=(.*\/)?\"?$extension(.so)?\"?$/d" "$pecl_file"
mod="${ini_dir:?}"/../mods-available/"$1".ini mod="${ini_dir:?}"/../mods-available/"$1".ini
if ! [ -e "$mod" ]; then if ! [ -e "$mod" ]; then
@@ -66,7 +59,7 @@ enable_extension() {
[ -n "$mod_priority_line" ] && priority=$(echo "$mod_priority_line" | cut -d'=' -f 2) [ -n "$mod_priority_line" ] && priority=$(echo "$mod_priority_line" | cut -d'=' -f 2)
(echo "; priority=$priority"; echo "$2=${ext_dir:?}/$1.so") | sudo tee "$mod" >/dev/null (echo "; priority=$priority"; echo "$2=${ext_dir:?}/$1.so") | sudo tee "$mod" >/dev/null
fi fi
sudo phpenmod -v "$version" "$1" >/dev/null 2>&1 sudo phpenmod -v "$version" "$1"
else else
echo "$2=${ext_dir:?}/$1.so" | sudo tee -a "${pecl_file:-${ini_file[@]}}" >/dev/null echo "$2=${ext_dir:?}/$1.so" | sudo tee -a "${pecl_file:-${ini_file[@]}}" >/dev/null
fi fi
@@ -78,7 +71,7 @@ enable_extensions() {
local extensions=("$@") local extensions=("$@")
to_wait=() to_wait=()
for ext in "${extensions[@]}"; do for ext in "${extensions[@]}"; do
enable_extension "$ext" extension >/dev/null 2>&1 & enable_extension "$ext" extension &
to_wait+=($!) to_wait+=($!)
done done
wait "${to_wait[@]}" wait "${to_wait[@]}"
@@ -86,7 +79,7 @@ enable_extensions() {
# Function to get a map of extensions and their dependent shared extensions. # Function to get a map of extensions and their dependent shared extensions.
get_extension_map() { get_extension_map() {
php -d'error_reporting=0' "${src:?}"/scripts/extensions/extension_map.php /tmp/map"$version".orig >/dev/null 2>&1 php -d'error_reporting=0' "${src:?}"/scripts/extensions/extension_map.php /tmp/map"$version".orig
} }
# Function to enable extension dependencies which are also extensions. # Function to enable extension dependencies which are also extensions.
@@ -132,7 +125,7 @@ disable_extension() {
disable_all_shared() { disable_all_shared() {
get_extension_map get_extension_map
sudo sed -i.orig -E -e "/^(zend_)?extension\s*=/d" "${ini_file[@]}" "$pecl_file" 2>/dev/null || true sudo sed -i.orig -E -e "/^(zend_)?extension\s*=/d" "${ini_file[@]}" "$pecl_file" 2>/dev/null || true
sudo find "${ini_dir:-$scan_dir}"/.. -name "*.ini" -not -path "*php.ini" -not -path "*phar.ini" -not -path "*pecl.ini" -not -path "*mods-available*" -delete >/dev/null 2>&1 || true sudo find "${ini_dir:-$scan_dir}"/.. -name "*.ini" -not -path "*php.ini" -not -path "*phar.ini" -not -path "*pecl.ini" -not -path "*mods-available*" -delete || true
mkdir -p /tmp/extdisabled/"$version" mkdir -p /tmp/extdisabled/"$version"
sudo rm -f /tmp/php"$version"_extensions sudo rm -f /tmp/php"$version"_extensions
sudo find "$ext_dir" -name '*.so' -print0 | xargs -0 -n 1 basename -s .so | xargs -I{} touch /tmp/extdisabled/"$version"/{} sudo find "$ext_dir" -name '*.so' -print0 | xargs -0 -n 1 basename -s .so | xargs -I{} touch /tmp/extdisabled/"$version"/{}
@@ -146,7 +139,7 @@ configure_pecl() {
for script in pear pecl; do for script in pear pecl; do
sudo "$script" channel-update "$script".php.net sudo "$script" channel-update "$script".php.net
done done
echo '' | sudo tee /tmp/pecl_config >/dev/null 2>&1 echo '' | sudo tee /tmp/pecl_config
fi fi
} }
@@ -165,59 +158,47 @@ add_extension() {
# Function to get the PECL version of an extension. # Function to get the PECL version of an extension.
get_pecl_version() { get_pecl_version() {
local extension=$1 local extension=$1
local requested=${2:-stable} states=("stable" "rc" "preview" "beta" "alpha" "snapshot")
local states=("stable" "rc" "preview" "beta" "alpha" "devel" "snapshot") stability="$(echo "$2" | grep -m 1 -Eio "($(IFS='|' ; echo "${states[*]}"))")"
local stability major_version response pecl_version pattern IFS=' ' read -r -a states <<< "$(echo "${states[@]}" | grep -Eo "$stability.*")"
response=$(get -s -n "" "https://pecl.php.net/rest/r/$extension/allreleases.xml")
if [[ "$requested" =~ ^[0-9] ]]; then
# Preserve exact pins and PECL's case-sensitive archive directory names.
pecl_version=$(echo "$response" | grep -Fio "<v>$requested</v>" | head -n 1 | cut -d '>' -f 2 | cut -d '<' -f 1)
echo "${pecl_version:-$requested}"
return
fi
requested="$(echo "$requested" | tr '[:upper:]' '[:lower:]')"
[[ " ${states[*]} " = *" $requested "* ]] || return 0
IFS=' ' read -r -a states <<< "$(echo "${states[@]}" | grep -Eo ".*$requested")"
stability="$(IFS='|' ; echo "${states[*]}")"
major_version=${3:-'[0-9]+'} major_version=${3:-'[0-9]+'}
pattern="v>($major_version\.[0-9]+(\.[0-9]+)?)[^<]*</v>[[:space:]]*<s>($stability)<" pecl_rest='https://pecl.php.net/rest/r/'
if [[ "$requested" = rc || "$requested" = preview ]]; then response=$(get -s -n "" "$pecl_rest$extension"/allreleases.xml)
pattern="$pattern|v>($major_version\.[0-9]+(\.[0-9]+)?)($stability)[0-9]*<" for state in "${states[@]}"; do
fi pecl_version=$(echo "$response" | grep -m 1 -Eio "($major_version\.[0-9]+\.[0-9]+${state}[0-9]+<)" | cut -d '<' -f 1)
# PECL orders releases by version, so select the first acceptable state. [ -z "$pecl_version" ] && pecl_version=$(echo "$response" | grep -m 1 -Eio "v>(.*)<\/v>.*$state<" | grep -m 1 -Eo "($major_version\.[0-9]+\.[0-9]+.*)<" | cut -d '<' -f 1)
echo "$response" | grep -Eio "$pattern" | head -n 1 | cut -d '>' -f 2 | cut -d '<' -f 1 [ -n "$pecl_version" ] && break;
done
[ -z "$pecl_version" ] && pecl_version=$(echo "$response" | grep -m 1 -Eo "($major_version\.[0-9]+\.[0-9]+)<" | cut -d '<' -f 1)
echo "$pecl_version"
} }
# Function to install PECL extensions and accept default options # Function to install PECL extensions and accept default options
pecl_install() { pecl_install() {
local extension=$1 local extension=$1
local prefix=${2:-extension} local prefix=${2:-extension}
add_pecl >/dev/null 2>&1 add_pecl
disable_extension_helper "${extension%-*}" >/dev/null 2>&1 disable_extension_helper "${extension%-*}"
# Compare version with 8.3 so it runs only on 8.4 and above # Compare version with 8.3 so it runs only on 8.4 and above
# Install using the source interface as it allows for patching. # Install using the source interface as it allows for patching.
if [[ $(printf "%s\n%s" "${version:?}" "8.3" | sort -V | head -n1) != "$version" ]]; then if [[ $(printf "%s\n%s" "${version:?}" "8.3" | sort -V | head -n1) != "$version" ]]; then
extension_version=${extension##*-}; extension_version=${extension##*-};
if [ "$extension_version" = "${extension%-*}" ]; then [ "$extension_version" = "${extension%-*}" ] && extension_version=$(get_pecl_version "$extension" "stable")
extension_version=$(get_pecl_version "$extension" "stable")
[ -n "$extension_version" ] || return 1
fi
add_extension_from_source "${extension%-*}" https://pecl.php.net "${extension%-*}" "${extension%-*}" "$extension_version" "$prefix" pecl add_extension_from_source "${extension%-*}" https://pecl.php.net "${extension%-*}" "${extension%-*}" "$extension_version" "$prefix" pecl
check_extension "${extension%-*}" && return 0 || return 1; check_extension "${extension%-*}" && return 0 || return 1;
else else
cpu_count="$(nproc 2>/dev/null || sysctl -n hw.ncpu 2>/dev/null || echo '1')" cpu_count="$(nproc 2>/dev/null || sysctl -n hw.ncpu 2>/dev/null || echo '1')"
local prefix_opts=() prefix_opts="$(parse_args "$extension" CONFIGURE_PREFIX_OPTS) MAKEFLAGS='-j $cpu_count'"
IFS=' ' read -r -a prefix_opts <<<"$(parse_args "$extension" CONFIGURE_PREFIX_OPTS)"
suffix_opts="$(parse_args "$extension" CONFIGURE_OPTS) $(parse_args "$extension" CONFIGURE_SUFFIX_OPTS)" suffix_opts="$(parse_args "$extension" CONFIGURE_OPTS) $(parse_args "$extension" CONFIGURE_SUFFIX_OPTS)"
IFS=' ' read -r -a libraries <<<"$(parse_args "$extension" LIBS) $(parse_args "$extension" "$(uname -s)"_LIBS)" IFS=' ' read -r -a libraries <<<"$(parse_args "$extension" LIBS) $(parse_args "$extension" "$(uname -s)"_LIBS)"
(( ${#libraries[@]} )) && add_libs "${libraries[@]}" >/dev/null 2>&1 (( ${#libraries[@]} )) && add_libs "${libraries[@]}"
if [ "$version" = "5.3" ]; then if [ "$version" = "5.3" ]; then
yes '' 2>/dev/null | sudo env "${prefix_opts[@]}" MAKEFLAGS="-j $cpu_count" pecl install -f "$extension" >/dev/null 2>&1 yes '' 2>/dev/null | sudo "$prefix_opts" pecl install -f "$extension"
else else
yes '' 2>/dev/null | sudo env "${prefix_opts[@]}" MAKEFLAGS="-j $cpu_count" pecl install -f -D "$(parse_pecl_configure_options "$suffix_opts")" "$extension" >/dev/null 2>&1 yes '' 2>/dev/null | sudo "$prefix_opts" pecl install -f -D "$(parse_pecl_configure_options "$suffix_opts")" "$extension"
fi fi
local exit_code=$? local exit_code=$?
sudo pecl info "$extension" 2>/dev/null | grep -iq 'zend extension' && prefix=zend_extension sudo pecl info "$extension" | grep -iq 'zend extension' && prefix=zend_extension
enable_extension "${extension%-*}" "$prefix" enable_extension "${extension%-*}" "$prefix"
return "$exit_code" return "$exit_code"
fi fi
@@ -228,38 +209,19 @@ add_pecl_extension() {
local extension=$1 local extension=$1
local pecl_version=$2 local pecl_version=$2
local prefix=$3 local prefix=$3
if [[ $pecl_version =~ (alpha|beta|rc|snapshot|preview|devel) ]]; then enable_extension "$extension" "$prefix"
if [[ $pecl_version =~ .*(alpha|beta|rc|snapshot|preview).* ]]; then
pecl_version=$(get_pecl_version "$extension" "$pecl_version") pecl_version=$(get_pecl_version "$extension" "$pecl_version")
fi fi
# Cache versioned extensions using suffixless copies in extension_dir. ext_version=$(php -r "echo phpversion('$extension');")
if [ -n "$pecl_version" ] && [ -e "${ext_dir:?}/$extension-$pecl_version" ]; then
sudo cp "${ext_dir:?}/$extension-$pecl_version" "${ext_dir:?}/$extension.so"
sudo rm -f /tmp/php"${version:?}"_extensions
fi
enable_extension "$extension" "$prefix"
ext_version=$(php -d display_errors=0 -r "echo phpversion('$extension');" 2>/dev/null)
if check_extension "$extension" && [[ -z "$pecl_version" || (-n "$pecl_version" && "${ext_version/-/}" == "$pecl_version") ]]; then if check_extension "$extension" && [[ -z "$pecl_version" || (-n "$pecl_version" && "${ext_version/-/}" == "$pecl_version") ]]; then
[ -n "$pecl_version" ] && sudo cp "${ext_dir:?}/$extension.so" "${ext_dir:?}/$extension-$pecl_version" 2>/dev/null || true
add_log "${tick:?}" "$extension" "Enabled" add_log "${tick:?}" "$extension" "Enabled"
else else
[ -n "$pecl_version" ] && sudo rm -f "${ext_dir:?}/$extension-$pecl_version"
[ -n "$pecl_version" ] && pecl_version="-$pecl_version" [ -n "$pecl_version" ] && pecl_version="-$pecl_version"
pecl_install "$extension$pecl_version" || ( [ "${fail_fast:?}" = "false" ] && add_extension "$extension" "$(get_extension_prefix "$extension")" >/dev/null 2>&1) pecl_install "$extension$pecl_version" || ( [ "${fail_fast:?}" = "false" ] && add_extension "$extension" "$(get_extension_prefix "$extension")" )
if ! extension_version="$(php -d display_errors=0 -d display_startup_errors=0 -r "echo phpversion('$extension'); exit(extension_loaded('$extension') ? 0 : 1);" 2>/dev/null)"; then extension_version="$(php -r "echo phpversion('$extension');")"
add_log "${cross:?}" "$extension" "Could not install $extension on PHP ${semver:?}"
return
fi
if [ -n "$pecl_version" ] && [ "${extension_version/-/}" != "${pecl_version#-}" ]; then
[ "${fail_fast:?}" = "true" ] && add_log "${cross:?}" "$extension-$extension_version" "Installed and enabled, but $extension$pecl_version was requested"
add_log "!" "$extension-$extension_version" "Installed and enabled, but $extension$pecl_version was requested"
echo "::warning::Installed $extension-$extension_version, but $extension$pecl_version was requested"
return
fi
if [ -n "$pecl_version" ] && [ "${extension_version/-/}" = "${pecl_version#-}" ]; then
sudo cp "${ext_dir:?}/$extension.so" "${ext_dir:?}/$extension$pecl_version" 2>/dev/null || true
fi
[ -n "$extension_version" ] && extension_version="-$extension_version" [ -n "$extension_version" ] && extension_version="-$extension_version"
add_log "${tick:?}" "$extension$extension_version" "Installed and enabled" add_extension_log "$extension$extension_version" "Installed and enabled"
fi fi
} }
@@ -269,10 +231,6 @@ add_unstable_extension() {
local stability=$2 local stability=$2
local prefix=$3 local prefix=$3
pecl_version=$(get_pecl_version "$extension" "$stability") pecl_version=$(get_pecl_version "$extension" "$stability")
if [ -z "$pecl_version" ]; then
add_log "${cross:?}" "$extension-$stability" "No release found with minimum stability $stability"
return
fi
add_pecl_extension "$extension" "$pecl_version" "$prefix" add_pecl_extension "$extension" "$pecl_version" "$prefix"
} }
+3 -3
View File
@@ -19,11 +19,11 @@ add_blackfire() {
extension_version=$(get -s -n "" https://blackfire.io/api/v1/releases | grep -Eo 'php":"([0-9]+.[0-9]+.[0-9]+)' | cut -d '"' -f 3) extension_version=$(get -s -n "" https://blackfire.io/api/v1/releases | grep -Eo 'php":"([0-9]+.[0-9]+.[0-9]+)' | cut -d '"' -f 3)
fi fi
fi fi
get -q -n "${ext_dir:?}/blackfire.so" https://packages.blackfire.io/binaries/blackfire-php/"$extension_version"/blackfire-php-"$platform"_"$arch_name"-php-"$no_dot_version".so >/dev/null 2>&1 get -q -n "${ext_dir:?}/blackfire.so" https://packages.blackfire.io/binaries/blackfire-php/"$extension_version"/blackfire-php-"$platform"_"$arch_name"-php-"$no_dot_version".so
fi fi
if [ -e "${ext_dir:?}/blackfire.so" ]; then if [ -e "${ext_dir:?}/blackfire.so" ]; then
disable_extension xdebug >/dev/null 2>&1 disable_extension xdebug
disable_extension pcov >/dev/null 2>&1 disable_extension pcov
enable_extension blackfire extension enable_extension blackfire extension
add_extension_log blackfire "$status" add_extension_log blackfire "$status"
else else
+9 -19
View File
@@ -7,8 +7,8 @@ add_couchbase_clibs() {
else else
release=$(get -s -n "" "$trunk"/latest | grep -Eo -m 1 "[0-9]+\.[0-9]+\.[0-9]+" | head -n 1) release=$(get -s -n "" "$trunk"/latest | grep -Eo -m 1 "[0-9]+\.[0-9]+\.[0-9]+" | head -n 1)
fi fi
[[ "$VERSION_ID" = "24.04" || "$VERSION_ID" = "26.04" ]] && vid=22.04 || vid="$VERSION_ID" [ "$VERSION_ID" = "24.04" ] && vid=22.04 || vid="$VERSION_ID"
[[ "$VERSION_CODENAME" = "noble" || "$VERSION_CODENAME" = "resolute" ]] && vcn=jammy || vcn="$VERSION_CODENAME" [ "$VERSION_CODENAME" = "noble" ] && vcn=jammy || vcn="$VERSION_CODENAME"
deb_url="$trunk/download/$release/libcouchbase-${release}_ubuntu${vid/./}_${vcn}_amd64.tar" deb_url="$trunk/download/$release/libcouchbase-${release}_ubuntu${vid/./}_${vcn}_amd64.tar"
get -q -n /tmp/libcouchbase.tar "$deb_url" get -q -n /tmp/libcouchbase.tar "$deb_url"
if ! [ -e /tmp/libcouchbase.tar ] || ! file /tmp/libcouchbase.tar | grep -q 'tar archive'; then if ! [ -e /tmp/libcouchbase.tar ] || ! file /tmp/libcouchbase.tar | grep -q 'tar archive'; then
@@ -22,9 +22,9 @@ add_couchbase_clibs() {
} }
add_old_libssl() { add_old_libssl() {
if [[ "$VERSION_ID" = "24.04" || "$VERSION_ID" = "26.04" ]]; then if [[ "$VERSION_ID" = "24.04" ]]; then
get -q -n /tmp/libssl.deb http://archive.ubuntu.com/ubuntu/pool/main/o/openssl/libssl1.1_1.1.1f-1ubuntu2_amd64.deb get -q -n /tmp/libssl.deb http://archive.ubuntu.com/ubuntu/pool/main/o/openssl/libssl1.1_1.1.1f-1ubuntu2_amd64.deb
([ -e /tmp/libssl.deb ] && sudo dpkg -i /tmp/libssl.deb) || add_extension_log "couchbase" "Could not install libssl1.1" [ -e /tmp/libssl.deb ] && sudo dpkg -i /tmp/libssl.deb || add_extension_log "couchbase" "Could not install libssl1.1"
fi fi
} }
@@ -59,32 +59,22 @@ add_couchbase() {
ext=$(get_couchbase_version) ext=$(get_couchbase_version)
fi fi
if [[ "$ext" =~ couchbase-[2-3].+ ]]; then if [[ "$ext" =~ couchbase-[2-3].+ ]]; then
export COUCHBASE_CONFIGURE_PREFIX_OPTS="${COUCHBASE_CONFIGURE_PREFIX_OPTS:-} SED=sed CFLAGS=-Wno-error=incompatible-pointer-types" add_couchbase_clibs "$ext"
add_couchbase_clibs "$ext" >/dev/null 2>&1
else else
add_couchbase_cxxlibs >/dev/null 2>&1 add_couchbase_cxxlibs
if [[ "$ext" =~ ^couchbase-4\.1\. ]]; then
export COUCHBASE_CONFIGURE_PREFIX_OPTS="${COUCHBASE_CONFIGURE_PREFIX_OPTS:-} COUCHBASE_CMAKE_EXTRA=-DCMAKE_POLICY_VERSION_MINIMUM=3.5"
fi
fi fi
enable_extension "couchbase" "extension" enable_extension "couchbase" "extension"
if check_extension "couchbase"; then if check_extension "couchbase"; then
add_log "${tick:?}" "couchbase" "Enabled" add_log "${tick:?}" "couchbase" "Enabled"
else else
local install_method=pecl_install
if [ "$ext" = "couchbase" ]; then if [ "$ext" = "couchbase" ]; then
ext="couchbase-$(get_pecl_version "couchbase" "stable")" ext="couchbase-$(get_pecl_version "couchbase" "stable")"
n_proc="$(nproc)" n_proc="$(nproc)"
export COUCHBASE_SUFFIX_OPTS="CMAKE_BUILD_TYPE=Release" export COUCHBASE_SUFFIX_OPTS="CMAKE_BUILD_TYPE=Release"
export CMAKE_BUILD_PARALLEL_LEVEL="$n_proc" export CMAKE_BUILD_PARALLEL_LEVEL="$n_proc"
install_method=add_extension_from_source add_extension_from_source couchbase https://pecl.php.net couchbase couchbase "${ext##*-}" extension pecl
elif [[ "$ext" =~ ^couchbase-4\.1\. ]]; then
install_method=add_extension_from_source
fi
if [ "$install_method" = add_extension_from_source ]; then
add_extension_from_source couchbase https://pecl.php.net couchbase couchbase "${ext##*-}" extension pecl >/dev/null 2>&1
else else
"$install_method" "${ext}" >/dev/null 2>&1 pecl_install "${ext}"
fi fi
add_extension_log "couchbase" "Installed and enabled" add_extension_log "couchbase" "Installed and enabled"
fi fi
@@ -103,6 +93,6 @@ add_couchbase() {
fi fi
add_brew_extension couchbase extension add_brew_extension couchbase extension
find "${brew_prefix:?}/lib" "${brew_prefix:?}/opt/couchbase@${version:?}" "${brew_prefix:?}/Cellar/couchbase@${version:?}" \ find "${brew_prefix:?}/lib" "${brew_prefix:?}/opt/couchbase@${version:?}" "${brew_prefix:?}/Cellar/couchbase@${version:?}" \
-name 'libcouchbase_php*.dylib' -exec sudo cp {} "${ext_dir:?}" \; >/dev/null 2>&1 -name 'libcouchbase_php*.dylib' -exec sudo cp {} "${ext_dir:?}" \;
fi fi
} }
+1 -1
View File
@@ -42,7 +42,7 @@ add_cubrid_helper() {
add_cubrid() { add_cubrid() {
ext=$1 ext=$1
status='Enabled' status='Enabled'
add_cubrid_helper "$ext" >/dev/null 2>&1 add_cubrid_helper "$ext"
add_extension_log "$ext" "$status" add_extension_log "$ext" "$status"
check_extension "$ext" && add_license_log check_extension "$ext" && add_license_log
} }
+2 -2
View File
@@ -39,9 +39,9 @@ add_event() {
add_log "${tick:?}" "event" "Enabled" add_log "${tick:?}" "event" "Enabled"
else else
if ! [[ "${version:?}" =~ ${old_versions:?} ]] && [ "$os" = "Darwin" ]; then if ! [[ "${version:?}" =~ ${old_versions:?} ]] && [ "$os" = "Darwin" ]; then
add_brew_extension event extension >/dev/null 2>&1 add_brew_extension event extension
else else
add_event_helper "$ext" >/dev/null 2>&1 add_event_helper "$ext"
fi fi
add_extension_log "event" "Installed and enabled" add_extension_log "event" "Installed and enabled"
fi fi
+3 -3
View File
@@ -15,12 +15,12 @@ add_firebird() {
else else
if [ "$(uname -s)" = "Linux" ]; then if [ "$(uname -s)" = "Linux" ]; then
if [[ "${version:?}" =~ 5.3|${php_builder_versions:?} ]]; then if [[ "${version:?}" =~ 5.3|${php_builder_versions:?} ]]; then
add_firebird_helper /usr >/dev/null 2>&1 add_firebird_helper /usr
else else
add_pdo_extension firebird >/dev/null 2>&1 add_pdo_extension firebird
fi fi
else else
add_brew_extension pdo_firebird extension >/dev/null 2>&1 add_brew_extension pdo_firebird extension
fi fi
add_extension_log pdo_firebird "Installed and enabled" add_extension_log pdo_firebird "Installed and enabled"
fi fi
+1 -1
View File
@@ -19,7 +19,7 @@ add_gearman_helper() {
add_gearman() { add_gearman() {
status="Enabled" status="Enabled"
if [ "$(uname -s)" = 'Linux' ]; then if [ "$(uname -s)" = 'Linux' ]; then
add_gearman_helper >/dev/null 2>&1 add_gearman_helper
add_extension_log "gearman" "$status" add_extension_log "gearman" "$status"
else else
add_brew_extension gearman extension add_brew_extension gearman extension
+4 -10
View File
@@ -1,12 +1,8 @@
# Helper function to compile and install geos # Helper function to compile and install geos
add_geos_helper() { add_geos_helper() {
if [[ "$os" = "Linux" || "${version:?}" =~ 5.[3-5] ]]; then export GEOS_LINUX_LIBS='libgeos-dev'
export GEOS_LINUX_LIBS='libgeos-dev' export GEOS_DARWIN_LIBS='geos'
export GEOS_DARWIN_LIBS='geos' add_extension_from_source geos https://github.com libgeos php-geos 1.0.0 extension get
add_extension_from_source geos https://github.com libgeos php-geos 1.0.0 extension get
else
add_brew_extension geos extension
fi
} }
# Function to add geos # Function to add geos
@@ -15,9 +11,7 @@ add_geos() {
if check_extension "geos"; then if check_extension "geos"; then
add_log "${tick:?}" "geos" "Enabled" add_log "${tick:?}" "geos" "Enabled"
else else
add_geos_helper >/dev/null 2>&1 add_geos_helper
add_extension_log "geos" "Installed and enabled" add_extension_log "geos" "Installed and enabled"
fi fi
} }
os="$(uname -s)"
+4 -4
View File
@@ -42,12 +42,12 @@ Function Repair-ICU() {
} }
Function Add-Http() { Function Add-Http() {
Add-Extension iconv >$null 2>&1 Add-Extension iconv
Add-Extension raphf >$null 2>&1 Add-Extension raphf
if($version -lt '8.0') { if($version -lt '8.0') {
Add-Extension propro >$null 2>&1 Add-Extension propro
} }
Add-Extension pecl_http >$null 2>&1 Add-Extension pecl_http
Repair-ICU Repair-ICU
Add-ExtensionLog http "Installed and enabled" Add-ExtensionLog http "Installed and enabled"
} }
+3 -3
View File
@@ -75,7 +75,7 @@ add_http_latest() {
if [ "$os" = "Linux" ]; then if [ "$os" = "Linux" ]; then
add_http_dependencies add_http_dependencies
package="php$version-http" package="php$version-http"
add_ppa ondrej/php >/dev/null 2>&1 || update_ppa ondrej/php add_ppa ondrej/php || update_ppa ondrej/php
(check_package "$package" && install_packages "$package") || add_http_helper "$(get_http_version)" "$os" (check_package "$package" && install_packages "$package") || add_http_helper "$(get_http_version)" "$os"
else else
if ! [[ "${version:?}" =~ ${old_versions:?} ]]; then if ! [[ "${version:?}" =~ ${old_versions:?} ]]; then
@@ -103,9 +103,9 @@ add_http() {
ext=$1 ext=$1
status="Enabled" status="Enabled"
if [[ "$ext" =~ ^(pecl_http|http)$ ]]; then if [[ "$ext" =~ ^(pecl_http|http)$ ]]; then
add_http_latest >/dev/null 2>&1 add_http_latest
else else
add_http_version "$ext" >/dev/null 2>&1 add_http_version "$ext"
fi fi
add_extension_log "http" "$status" add_extension_log "http" "$status"
} }
+3 -14
View File
@@ -35,15 +35,6 @@ get_cli_archive() {
esac esac
} }
# Function to add the libxml2 ABI name expected by the IBM Db2 CLI driver.
add_ibm_libxml2_link() {
local libxml2
if ! ldconfig -p 2>/dev/null | grep -q 'libxml2\.so\.2 '; then
libxml2=$(ldconfig -p 2>/dev/null | awk '$1 == "libxml2.so.16" {print $NF; exit}')
[ -n "$libxml2" ] && sudo ln -sfn "$libxml2" "$(dirname "$libxml2")/libxml2.so.2"
fi
}
# Function to install IBM Db2 CLI driver. # Function to install IBM Db2 CLI driver.
add_cli_driver() { add_cli_driver() {
local os arch archive url tmp libs local os arch archive url tmp libs
@@ -67,11 +58,10 @@ add_cli_driver() {
if [ "$os" = "Linux" ]; then if [ "$os" = "Linux" ]; then
echo "$ibm_cli/lib" | sudo tee /etc/ld.so.conf.d/ibm_db2.conf >/dev/null echo "$ibm_cli/lib" | sudo tee /etc/ld.so.conf.d/ibm_db2.conf >/dev/null
sudo ldconfig sudo ldconfig
add_ibm_libxml2_link
else else
libs='/usr/local/lib' libs='/usr/local/lib'
sudo mkdir -p "$libs" sudo mkdir -p "$libs"
sudo ln -sf "$ibm_cli"/lib/*.dylib "$libs" >/dev/null 2>&1 || true sudo ln -sf "$ibm_cli"/lib/*.dylib "$libs" || true
fi fi
} }
@@ -88,7 +78,6 @@ add_ibm_helper() {
else else
configure_flag="--with-pdo-ibm=$IBM_DB_HOME" configure_flag="--with-pdo-ibm=$IBM_DB_HOME"
fi fi
read -r "${ext}_CONFIGURE_PREFIX_OPTS" <<< "SED=sed"
read -r "${ext}_CONFIGURE_OPTS" <<< "--with-php-config=$(command -v php-config) $configure_flag" read -r "${ext}_CONFIGURE_OPTS" <<< "--with-php-config=$(command -v php-config) $configure_flag"
patch_phpize patch_phpize
add_extension_from_source "$ext" https://github.com php "pecl-database-$ext" master extension get add_extension_from_source "$ext" https://github.com php "pecl-database-$ext" master extension get
@@ -104,11 +93,11 @@ add_ibm() {
status='Enabled' status='Enabled'
ibm_home='/opt/ibm' ibm_home='/opt/ibm'
ibm_cli=$ibm_home/clidriver ibm_cli=$ibm_home/clidriver
if ! add_cli_driver >/dev/null 2>&1; then if ! add_cli_driver ; then
add_log "${cross:?}" "$ext" "IBM Db2 CLI driver is not available on $(uname -s)/$(uname -m)" add_log "${cross:?}" "$ext" "IBM Db2 CLI driver is not available on $(uname -s)/$(uname -m)"
return 1 return 1
fi fi
add_ibm_helper >/dev/null 2>&1 add_ibm_helper
add_extension_log "$ext" "$status" add_extension_log "$ext" "$status"
check_extension "$ext" && add_license_log check_extension "$ext" && add_license_log
} }
+1 -1
View File
@@ -17,7 +17,7 @@ add_intl() {
add_log "${cross:?}" "intl" "ICU $icu is not supported for PHP $version" add_log "${cross:?}" "intl" "ICU $icu is not supported for PHP $version"
else else
[ "${ts:?}" = 'zts' ] && suffix='-zts' [ "${ts:?}" = 'zts' ] && suffix='-zts'
install_icu "$icu" >/dev/null 2>&1 install_icu "$icu"
get -q -n "${ext_dir:?}/intl.so" "https://github.com/shivammathur/icu-intl/releases/download/intl-$icu/php${version:?}-intl-$icu$suffix$arch_suffix.so" get -q -n "${ext_dir:?}/intl.so" "https://github.com/shivammathur/icu-intl/releases/download/intl-$icu/php${version:?}-intl-$icu$suffix$arch_suffix.so"
enable_extension intl extension enable_extension intl extension
add_extension_log intl "Installed and enabled with ICU $icu" add_extension_log intl "Installed and enabled with ICU $icu"
+2 -2
View File
@@ -24,10 +24,10 @@ add_ioncube() {
if [ -e "$loader_file" ]; then if [ -e "$loader_file" ]; then
sudo mv /tmp/ioncube/ioncube_loader_"${os_suffix%%_*}_${version:?}$ts_part".so "${ext_dir:?}/ioncube.so" sudo mv /tmp/ioncube/ioncube_loader_"${os_suffix%%_*}_${version:?}$ts_part".so "${ext_dir:?}/ioncube.so"
sudo cp /tmp/ioncube/LICENSE.txt "$ext_dir"/IONCUBE_LICENSE.txt sudo cp /tmp/ioncube/LICENSE.txt "$ext_dir"/IONCUBE_LICENSE.txt
echo "zend_extension=$ext_dir/ioncube.so" | sudo tee "${scan_dir:?}/00-ioncube.ini" >/dev/null 2>&1 echo "zend_extension=$ext_dir/ioncube.so" | sudo tee "${scan_dir:?}/00-ioncube.ini"
fi fi
else else
echo "zend_extension=$ext_dir/ioncube.so" | sudo tee "${scan_dir:?}/00-ioncube.ini" >/dev/null 2>&1 echo "zend_extension=$ext_dir/ioncube.so" | sudo tee "${scan_dir:?}/00-ioncube.ini"
fi fi
add_extension_log "ioncube" "$status" add_extension_log "ioncube" "$status"
check_extension "ioncube" && add_license_log check_extension "ioncube" && add_license_log
+1 -1
View File
@@ -71,7 +71,7 @@ Function Add-Oci() {
} }
} else { } else {
$status = 'Installed and enabled' $status = 'Installed and enabled'
Add-Extension $extension >$null 2>&1 Add-Extension $extension
} }
Add-ExtensionLog $extension $status Add-ExtensionLog $extension $status
Add-LicenseLog Add-LicenseLog
+3 -13
View File
@@ -37,10 +37,6 @@ add_client() {
for icdir in /opt/oracle/instantclient_*; do for icdir in /opt/oracle/instantclient_*; do
sudo mv "$icdir"/* "$oracle_client"/ sudo mv "$icdir"/* "$oracle_client"/
done done
if [ "$os" = "Linux" ]; then
client_library=$(find "$oracle_client" -maxdepth 1 -type f -name 'libclntsh.so.*.1' | sort -V | tail -n1)
[ -n "$client_library" ] && sudo ln -sfn "${client_library##*/}" "$oracle_client/libclntsh.so"
fi
sudo mkdir -p "$libs" sudo mkdir -p "$libs"
sudo ln -sf /opt/oracle/instantclient/*."$lib_ext"* "$libs" sudo ln -sf /opt/oracle/instantclient/*."$lib_ext"* "$libs"
if [ "$os" = "Linux" ]; then if [ "$os" = "Linux" ]; then
@@ -53,13 +49,7 @@ add_client() {
add_oci_helper() { add_oci_helper() {
if ! shared_extension "$ext"; then if ! shared_extension "$ext"; then
status='Installed and enabled' status='Installed and enabled'
local compatibility_flag read -r "${ext}_CONFIGURE_PREFIX_OPTS" <<< "CFLAGS=-Wno-incompatible-function-pointer-types"
if [ "$os" = "Linux" ]; then
compatibility_flag='-Wno-error=incompatible-pointer-types'
else
compatibility_flag='-Wno-incompatible-function-pointer-types'
fi
read -r "${ext}_CONFIGURE_PREFIX_OPTS" <<< "SED=sed CFLAGS=$compatibility_flag"
read -r "${ext}_LINUX_LIBS" <<< "libaio-dev" read -r "${ext}_LINUX_LIBS" <<< "libaio-dev"
read -r "${ext}_CONFIGURE_OPTS" <<< "--with-php-config=$(command -v php-config) --with-${ext/_/-}=instantclient,$oracle_client" read -r "${ext}_CONFIGURE_OPTS" <<< "--with-php-config=$(command -v php-config) --with-${ext/_/-}=instantclient,$oracle_client"
patch_phpize patch_phpize
@@ -82,8 +72,8 @@ add_oci() {
oracle_home='/opt/oracle' oracle_home='/opt/oracle'
oracle_client=$oracle_home/instantclient oracle_client=$oracle_home/instantclient
os=$(uname -s) os=$(uname -s)
add_client >/dev/null 2>&1 add_client
add_oci_helper >/dev/null 2>&1 add_oci_helper
add_extension_log "$ext" "$status" add_extension_log "$ext" "$status"
check_extension "$ext" && add_license_log check_extension "$ext" && add_license_log
} }
@@ -1,12 +0,0 @@
patch_couchbase() {
local operation_queue query_index_manager
operation_queue=src/deps/couchbase-cxx-client/core/mcbp/operation_queue.cxx
query_index_manager=src/deps/couchbase-cxx-client/core/impl/query_index_manager.cxx
if [ -e "$operation_queue" ] && ! grep -q '^#include <algorithm>' "$operation_queue"; then
sed -i.bak '/^#include <memory>/i#include <algorithm>' "$operation_queue"
fi
if [ -e "$query_index_manager" ] && ! grep -q '^#include <algorithm>' "$query_index_manager"; then
sed -i.bak '/^#include <utility>/i#include <algorithm>' "$query_index_manager"
fi
rm -f "$operation_queue.bak" "$query_index_manager.bak"
}
+2 -2
View File
@@ -2,8 +2,8 @@ patch_geos() {
if [[ $(printf '%s\n%s\n' "${version:?}" "7.0" | sort -V | head -n1) == "7.0" ]]; then if [[ $(printf '%s\n%s\n' "${version:?}" "7.0" | sort -V | head -n1) == "7.0" ]]; then
sed -i~ -e "s/, ce->name/, ZSTR_VAL(ce->name)/; s/ulong /zend_ulong /" geos.c sed -i~ -e "s/, ce->name/, ZSTR_VAL(ce->name)/; s/ulong /zend_ulong /" geos.c
fi fi
get -q -n /tmp/php8.patch https://src.fedoraproject.org/rpms/php-geos/raw/2021845a362752948dd0338920f0a0e6b1031b4d/f/0003-add-all-arginfo-and-fix-build-with-PHP-8.patch get -q -n /tmp/php8.patch https://git.remirepo.net/cgit/rpms/php/php-geos.git/plain/0003-add-all-arginfo-and-fix-build-with-PHP-8.patch
get -q -n /tmp/toString.patch https://src.fedoraproject.org/rpms/php-geos/raw/2021845a362752948dd0338920f0a0e6b1031b4d/f/0006-fix-__toString-with-8.2.patch get -q -n /tmp/toString.patch https://git.remirepo.net/cgit/rpms/php/php-geos.git/plain/0006-fix-__toString-with-8.2.patch
patch -p1 < /tmp/php8.patch 2>/dev/null || true patch -p1 < /tmp/php8.patch 2>/dev/null || true
patch -p1 < /tmp/toString.patch 2>/dev/null || true patch -p1 < /tmp/toString.patch 2>/dev/null || true
} }
+2 -2
View File
@@ -36,7 +36,7 @@ add_phalcon_helper() {
add_brew_extension "$extension" extension add_brew_extension "$extension" extension
else else
package="php${version:?}-$extension" package="php${version:?}-$extension"
add_ppa ondrej/php >/dev/null 2>&1 || update_ppa ondrej/php add_ppa ondrej/php || update_ppa ondrej/php
[[ "$extension" =~ phalcon[4|5] ]] && (install_packages "php${version:?}-psr" || pecl_install psr || pecl_install psr-1.1.0) [[ "$extension" =~ phalcon[4|5] ]] && (install_packages "php${version:?}-psr" || pecl_install psr || pecl_install psr-1.1.0)
(check_package "$package" && install_packages "$package") || pecl_install phalcon-"$(get_phalcon_version)" || add_phalcon_from_repo (check_package "$package" && install_packages "$package") || pecl_install phalcon-"$(get_phalcon_version)" || add_phalcon_from_repo
fi fi
@@ -96,7 +96,7 @@ add_phalcon() {
[ "$extension" = "phalcon" ] && extension=phalcon5 [ "$extension" = "phalcon" ] && extension=phalcon5
extension_major_version=${extension: -1} extension_major_version=${extension: -1}
if [[ "$extension_major_version" =~ [3-5] ]]; then if [[ "$extension_major_version" =~ [3-5] ]]; then
add_phalcon"$extension_major_version" >/dev/null 2>&1 add_phalcon"$extension_major_version"
fi fi
add_extension_log "phalcon" "$status" add_extension_log "phalcon" "$status"
} }
+4 -8
View File
@@ -35,7 +35,7 @@ get_openssl_suffix() {
# Change library paths in relay binary. # Change library paths in relay binary.
change_library_paths() { change_library_paths() {
if [ "$os" = "Darwin" ]; then if [ "$os" = "Darwin" ]; then
otool -L "${ext_dir:?}"/relay.so | grep -q 'ssl.3.' && openssl_version='3' || openssl_version='1.1' otool -L "${ext_dir:?}"/relay.so | grep -q 'ssl.1' && openssl_version='1.1' || openssl_version='3'
[ -e "${brew_prefix:?}"/opt/openssl@"$openssl_version" ] || { [ -e "${brew_prefix:?}"/opt/openssl@"$openssl_version" ] || {
safe_brew install --skip-link openssl@"$openssl_version" && safe_brew install --skip-link openssl@"$openssl_version" &&
brew link --overwrite --force openssl@"$openssl_version" brew link --overwrite --force openssl@"$openssl_version"
@@ -63,10 +63,6 @@ add_relay_dependencies() {
# Initialize relay extension ini configuration # Initialize relay extension ini configuration
init_relay_ini() { init_relay_ini() {
without_trace init_relay_ini_helper "$@"
}
init_relay_ini_helper() {
relay_ini=$1 relay_ini=$1
if [ -e "$relay_ini" ]; then if [ -e "$relay_ini" ]; then
if [[ -n "$RELAY_KEY" ]]; then if [[ -n "$RELAY_KEY" ]]; then
@@ -149,14 +145,14 @@ add_relay() {
error="Relay extension is not available for macOS x86_64 architecture" error="Relay extension is not available for macOS x86_64 architecture"
else else
relay_version=$(get_relay_version "$ext") relay_version=$(get_relay_version "$ext")
add_relay_dependencies >/dev/null 2>&1 add_relay_dependencies
if shared_extension relay; then if shared_extension relay; then
message="Enabled" message="Enabled"
else else
add_relay_helper "$arch" >/dev/null 2>&1 add_relay_helper "$arch"
message="Installed and enabled ${relay_version}" message="Installed and enabled ${relay_version}"
fi fi
configure_relay >/dev/null 2>&1 configure_relay
fi fi
add_extension_log relay "$message" "$error" add_extension_log relay "$message" "$error"
} }
+8 -8
View File
@@ -51,7 +51,7 @@ check_lib() {
add_linux_libs() { add_linux_libs() {
local lib=$1 local lib=$1
if ! check_lib "$lib"; then if ! check_lib "$lib"; then
install_packages "$lib" >/dev/null 2>&1 || true install_packages "$lib" || true
fi fi
add_lib_log "$lib" add_lib_log "$lib"
} }
@@ -61,10 +61,10 @@ add_darwin_libs() {
local lib=$1 local lib=$1
if ! check_lib "$lib"; then if ! check_lib "$lib"; then
if [[ "$lib" = *@* ]]; then if [[ "$lib" = *@* ]]; then
safe_brew install --skip-link "$lib" >/dev/null 2>&1 || true safe_brew install --skip-link "$lib" || true
brew link --overwrite --force "$lib" >/dev/null 2>&1 || true brew link --overwrite --force "$lib" || true
else else
safe_brew install "$lib" >/dev/null 2>&1 || true safe_brew install "$lib" || true
fi fi
fi fi
add_lib_log "$lib" add_lib_log "$lib"
@@ -99,7 +99,7 @@ get_libraries() {
run_group() { run_group() {
local command=$1 local command=$1
local log=$2 local log=$2
echo "$command" | sudo tee ./run_group.sh >/dev/null 2>&1 echo "$command" | sudo tee ./run_group.sh
echo "$GROUP$log" echo "$GROUP$log"
. ./run_group.sh . ./run_group.sh
local status=$? local status=$?
@@ -126,7 +126,7 @@ fetch_extension() {
run_group "git clone -nv $url/$org/$repo /tmp/$repo-$release" "git clone" run_group "git clone -nv $url/$org/$repo /tmp/$repo-$release" "git clone"
cd /tmp/"$repo-$release" || exit 1 cd /tmp/"$repo-$release" || exit 1
git checkout -q "$release" git checkout -q "$release"
cd "${sub_dir:-.}" || exit 1 cd "$sub_dir" || exit 1
if [ -e .gitmodules ]; then if [ -e .gitmodules ]; then
jobs="$(grep -c "\[submodule" .gitmodules)" jobs="$(grep -c "\[submodule" .gitmodules)"
run_group "git submodule update --jobs $jobs --init --recursive" "git submodule" run_group "git submodule update --jobs $jobs --init --recursive" "git submodule"
@@ -163,7 +163,7 @@ add_extension_from_source() {
sub_dir="$(parse_args "$extension" PATH)" sub_dir="$(parse_args "$extension" PATH)"
step_log "Setup $slug" step_log "Setup $slug"
( (
add_devtools phpize >/dev/null 2>&1 add_devtools phpize
disable_extension_helper "$extension" disable_extension_helper "$extension"
fetch_extension "$extension" "$fetch" fetch_extension "$extension" "$fetch"
if ! [ "$(find . -maxdepth 1 -name '*.m4' -exec grep -H 'PHP_NEW_EXTENSION' {} \; | wc -l)" != "0" ]; then if ! [ "$(find . -maxdepth 1 -name '*.m4' -exec grep -H 'PHP_NEW_EXTENSION' {} \; | wc -l)" != "0" ]; then
@@ -171,7 +171,7 @@ add_extension_from_source() {
else else
[[ -n "${libraries// }" ]] && run_group "add_libs $libraries" "add libraries" [[ -n "${libraries// }" ]] && run_group "add_libs $libraries" "add libraries"
[ "${debug:?}" = "debug" ] && suffix_opts="$suffix_opts --enable-debug" [ "${debug:?}" = "debug" ] && suffix_opts="$suffix_opts --enable-debug"
patch_extension "$extension" >/dev/null 2>&1 patch_extension "$extension"
run_group "phpize" "phpize" && \ run_group "phpize" "phpize" && \
run_group "sudo $prefix_opts ./configure $suffix_opts $opts" "configure" && \ run_group "sudo $prefix_opts ./configure $suffix_opts $opts" "configure" && \
run_group "sudo $prefix_opts make -j$(nproc 2>/dev/null || sysctl -n hw.ncpu)" "make" && \ run_group "sudo $prefix_opts make -j$(nproc 2>/dev/null || sysctl -n hw.ncpu)" "make" && \
+2 -2
View File
@@ -69,10 +69,10 @@ Function Add-Sqlsrv() {
Add-ExtensionFromGithub $extension > $null 2>&1 Add-ExtensionFromGithub $extension > $null 2>&1
} catch {} } catch {}
if (-not(Test-Extension $extension)) { if (-not(Test-Extension $extension)) {
Add-SqlsrvFromMSGithub $extension >$null 2>&1 Add-SqlsrvFromMSGithub $extension
} }
if (-not(Test-Extension $extension)) { if (-not(Test-Extension $extension)) {
Add-Extension $extension >$null 2>&1 Add-Extension $extension
} }
$status = 'Installed and enabled' $status = 'Installed and enabled'
} }
+1 -1
View File
@@ -77,7 +77,7 @@ Function Add-ZephirParser() {
try { try {
Add-ZephirParserFromGitHub $extension Add-ZephirParserFromGitHub $extension
} catch { } catch {
Add-Extension $extension >$null 2>&1 Add-Extension $extension
} }
} }
Add-ExtensionLog zephir_parser $status Add-ExtensionLog zephir_parser $status
+1 -1
View File
@@ -33,7 +33,7 @@ add_zephir_parser() {
zp_releases=https://github.com/"$repo"/releases zp_releases=https://github.com/"$repo"/releases
if ! shared_extension zephir_parser; then if ! shared_extension zephir_parser; then
message='Installed and enabled' message='Installed and enabled'
add_zephir_parser_helper "$ext" >/dev/null 2>&1 add_zephir_parser_helper "$ext"
else else
message='Enabled' message='Enabled'
enable_extension zephir_parser extension enable_extension zephir_parser extension
+44 -55
View File
@@ -6,32 +6,37 @@ add_sudo() {
fi fi
} }
# Function to select the package installer. # Function to link apt-fast to apt-get
set_apt_install() { link_apt_fast() {
local apt=apt-get if ! command -v apt-fast >/dev/null; then
command -v apt-fast >/dev/null && apt=apt-fast sudo ln -sf /usr/bin/apt-get /usr/bin/apt-fast
apt_install="sudo $debconf_fix $apt install -y --no-install-recommends -o Dpkg::Options::=--force-confnew" trap "sudo rm -f /usr/bin/apt-fast 2>/dev/null" exit
fi
} }
# Function to setup environment for self-hosted runners. # Function to setup environment for self-hosted runners.
self_hosted_helper() { self_hosted_helper() {
sudo mkdir -p /opt/hostedtoolcache >/dev/null 2>&1 || true if ! command -v apt-fast >/dev/null; then
local packages=() sudo ln -sf /usr/bin/apt-get /usr/bin/apt-fast
mapfile -t packages < <(filter_packages apt-transport-https ca-certificates curl file make jq unzip autoconf automake gcc g++ gnupg) trap "sudo rm -f /usr/bin/apt-fast 2>/dev/null" exit
if [ "${#packages[@]}" -gt 0 ]; then
install_packages "${packages[@]}"
fi fi
sudo mkdir -p /opt/hostedtoolcache || true
install_packages apt-transport-https ca-certificates curl file make jq unzip autoconf automake gcc g++ gnupg
} }
# Function to fix broken packages. # Function to fix broken packages.
fix_broken_packages() { fix_broken_packages() {
sudo apt --fix-broken install -o Dpkg::Options::=--force-confnew >/dev/null 2>&1 sudo apt --fix-broken install
} }
# Function to install a package # Function to install a package
install_packages() { install_packages() {
packages=("$@") packages=("$@")
$apt_install "${packages[@]}" >/dev/null 2>&1 || (update_lists && fix_broken_packages && $apt_install "${packages[@]}" >/dev/null 2>&1) if ! [ -e /etc/dpkg/dpkg.cfg.d/force-confnew ]; then
echo "force-confnew" | sudo tee /etc/dpkg/dpkg.cfg.d/force-confnew
trap "sudo rm -f /etc/dpkg/dpkg.cfg.d/force-confnew 2>/dev/null" exit
fi
$apt_install "${packages[@]}" || (update_lists && fix_broken_packages && $apt_install "${packages[@]}" )
} }
# Function to disable an extension. # Function to disable an extension.
@@ -43,10 +48,10 @@ disable_extension_helper() {
disable_extension_dependents "$extension" disable_extension_dependents "$extension"
fi fi
sudo sed -Ei "/=(.*\/)?\"?$extension(.so)?\"?$/d" "${ini_file[@]}" "$pecl_file" sudo sed -Ei "/=(.*\/)?\"?$extension(.so)?\"?$/d" "${ini_file[@]}" "$pecl_file"
sudo find "$ini_dir"/.. -name "*-$extension.ini" -not -path "*phar.ini" -not -path "*pecl.ini" -not -path "*mods-available*" -delete >/dev/null 2>&1 || true sudo find "$ini_dir"/.. -name "*-$extension.ini" -not -path "*phar.ini" -not -path "*pecl.ini" -not -path "*mods-available*" -delete || true
sudo rm -f /tmp/php"$version"_extensions sudo rm -f /tmp/php"$version"_extensions
mkdir -p /tmp/extdisabled/"$version" mkdir -p /tmp/extdisabled/"$version"
echo '' | sudo tee /tmp/extdisabled/"$version"/"$extension" >/dev/null 2>&1 echo '' | sudo tee /tmp/extdisabled/"$version"/"$extension"
} }
# Function to add PDO extension. # Function to add PDO extension.
@@ -59,7 +64,7 @@ add_pdo_extension() {
ext_name=$1 ext_name=$1
if shared_extension pdo; then if shared_extension pdo; then
disable_extension_helper pdo disable_extension_helper pdo
echo "extension=pdo.so" | sudo tee "${ini_file[@]/php.ini/conf.d/10-pdo.ini}" >/dev/null 2>&1 echo "extension=pdo.so" | sudo tee "${ini_file[@]/php.ini/conf.d/10-pdo.ini}"
fi fi
if [ "$ext" = "mysql" ]; then if [ "$ext" = "mysql" ]; then
enable_extension "mysqlnd" "extension" enable_extension "mysqlnd" "extension"
@@ -67,15 +72,15 @@ add_pdo_extension() {
elif [ "$ext" = "dblib" ]; then elif [ "$ext" = "dblib" ]; then
ext_name="sybase" ext_name="sybase"
elif [ "$ext" = "firebird" ]; then elif [ "$ext" = "firebird" ]; then
install_packages libfbclient2 >/dev/null 2>&1 install_packages libfbclient2
enable_extension "pdo_firebird" "extension" enable_extension "pdo_firebird" "extension"
ext_name="interbase" ext_name="interbase"
elif [ "$ext" = "sqlite" ]; then elif [ "$ext" = "sqlite" ]; then
ext="sqlite3" ext="sqlite3"
ext_name="sqlite3" ext_name="sqlite3"
fi fi
add_extension "$ext_name" "extension" >/dev/null 2>&1 add_extension "$ext_name" "extension"
add_extension "$pdo_ext" "extension" >/dev/null 2>&1 add_extension "$pdo_ext" "extension"
add_extension_log "$pdo_ext" "Enabled" add_extension_log "$pdo_ext" "Enabled"
fi fi
} }
@@ -85,26 +90,11 @@ check_package() {
apt-cache policy "$1" 2>/dev/null | grep -q 'Candidate' apt-cache policy "$1" 2>/dev/null | grep -q 'Candidate'
} }
# Function to filter out installed packages
filter_packages() {
[ "$#" -gt 0 ] || return 0
local package architecture status
local -A installed=()
while IFS=$'\t' read -r package architecture status; do
[[ "$status" = [ih]'i ' ]] && status=1 || status=0
installed["$package"]=$(( ${installed["$package"]:-1} && status ))
installed["$package:$architecture"]=$status
done < <(dpkg-query -W -f='${Package}\t${Architecture}\t${db:Status-Abbrev}\n' -- "$@" 2>/dev/null)
for package in "$@"; do
[ "${installed[$package]:-0}" -eq 1 ] || printf '%s\n' "$package"
done
}
# Helper function to add an extension. # Helper function to add an extension.
add_extension_helper() { add_extension_helper() {
local extension=$1 local extension=$1
packages=(php"$version"-"$extension") packages=(php"$version"-"$extension")
add_ppa ondrej/php >/dev/null 2>&1 || update_ppa ondrej/php add_ppa ondrej/php || update_ppa ondrej/php
[ "${debug:?}" = "debug" ] && check_package php"$version"-"$extension"-dbgsym && packages+=(php"$version"-"$extension"-dbgsym) [ "${debug:?}" = "debug" ] && check_package php"$version"-"$extension"-dbgsym && packages+=(php"$version"-"$extension"-dbgsym)
(check_package "${packages[0]}" && install_packages "${packages[@]}") || pecl_install "$extension" (check_package "${packages[0]}" && install_packages "${packages[@]}") || pecl_install "$extension"
add_extension_log "$extension" "Installed and enabled" add_extension_log "$extension" "Installed and enabled"
@@ -118,7 +108,7 @@ add_devtools() {
install_packages "php$version-dev" install_packages "php$version-dev"
fi fi
switch_version "phpize" "php-config" switch_version "phpize" "php-config"
add_extension xml extension >/dev/null 2>&1 add_extension xml extension
add_log "${tick:?}" "$tool" "Added $tool $semver" add_log "${tick:?}" "$tool" "Added $tool $semver"
} }
@@ -169,7 +159,7 @@ register_alternative() {
fi fi
link="$(alternative_link "$tool")" link="$(alternative_link "$tool")"
priority="${version//./}" priority="${version//./}"
sudo update-alternatives --install "$link" "$tool" "$target" "$priority" >/dev/null 2>&1 sudo update-alternatives --install "$link" "$tool" "$target" "$priority"
} }
# Function to register and switch an alternative. # Function to register and switch an alternative.
@@ -179,16 +169,16 @@ set_alternative() {
target="$(alternative_target "$tool")" target="$(alternative_target "$tool")"
[ -e "$target" ] || return 0 [ -e "$target" ] || return 0
register_alternative "$tool" || return 1 register_alternative "$tool" || return 1
sudo update-alternatives --set "$tool" "$target" >/dev/null 2>&1 sudo update-alternatives --set "$tool" "$target"
} }
# Function to add PECL. # Function to add PECL.
add_pecl() { add_pecl() {
add_devtools phpize >/dev/null 2>&1 add_devtools phpize
if ! command -v pecl >/dev/null; then if ! command -v pecl >/dev/null; then
install_packages php-pear install_packages php-pear
fi fi
configure_pecl >/dev/null 2>&1 configure_pecl
pear_version=$(get_tool_version "pecl" "version") pear_version=$(get_tool_version "pecl" "version")
add_log "${tick:?}" "PECL" "Added PECL $pear_version" add_log "${tick:?}" "PECL" "Added PECL $pear_version"
} }
@@ -217,7 +207,7 @@ get_php_packages() {
# Function to install packaged PHP # Function to install packaged PHP
add_packaged_php() { add_packaged_php() {
add_ppa ondrej/php >/dev/null 2>&1 || update_ppa ondrej/php add_ppa ondrej/php || update_ppa ondrej/php
IFS=' ' read -r -a packages <<<"$(get_php_packages)" IFS=' ' read -r -a packages <<<"$(get_php_packages)"
install_packages "${packages[@]}" install_packages "${packages[@]}"
} }
@@ -236,12 +226,12 @@ update_php() {
# Function to install PHP. # Function to install PHP.
add_php() { add_php() {
if [ "${runner:?}" = "self-hosted" ] || [ "${use_builds_cache:-true}" = "false" ]; then if [ "${runner:?}" = "self-hosted" ] || [ "${use_package_cache:-true}" = "false" ]; then
if [[ "$version" =~ ${php_builder_versions:?} || "$ts" = "zts" ]]; then if [[ "$version" =~ ${php_builder_versions:?} || "$ts" = "zts" ]]; then
setup_php_builder setup_php_builder
else else
add_packaged_php add_packaged_php
switch_version >/dev/null 2>&1 switch_version
add_pecl add_pecl
fi fi
elif [[ "$version" =~ ${old_versions:?} ]]; then elif [[ "$version" =~ ${old_versions:?} ]]; then
@@ -254,7 +244,7 @@ add_php() {
# Function to ini file for pear and link it to each SAPI. # Function to ini file for pear and link it to each SAPI.
link_pecl_file() { link_pecl_file() {
echo '' | sudo tee "$pecl_file" >/dev/null 2>&1 echo '' | sudo tee "$pecl_file"
for file in "${ini_file[@]}"; do for file in "${ini_file[@]}"; do
sapi_scan_dir="$(realpath -m "$(dirname "$file")")/conf.d" sapi_scan_dir="$(realpath -m "$(dirname "$file")")/conf.d"
if [ "$sapi_scan_dir" != "$scan_dir" ] && ! [ -h "$sapi_scan_dir" ]; then if [ "$sapi_scan_dir" != "$scan_dir" ] && ! [ -h "$sapi_scan_dir" ]; then
@@ -287,29 +277,26 @@ add_php_config() {
elif [ "$ini" = "development" ]; then elif [ "$ini" = "development" ]; then
echo "${ini_file[@]}" | xargs -n 1 -P 6 sudo cp "$php_lib_dir"/php.ini-development echo "${ini_file[@]}" | xargs -n 1 -P 6 sudo cp "$php_lib_dir"/php.ini-development
elif [ "$ini" = "none" ]; then elif [ "$ini" = "none" ]; then
echo '' | sudo tee "${ini_file[@]}" >/dev/null 2>&1 echo '' | sudo tee "${ini_file[@]}"
fi fi
echo "$ini" | sudo tee "$current_ini" >/dev/null 2>&1 echo "$ini" | sudo tee "$current_ini"
} }
# Function to Setup PHP # Function to Setup PHP
setup_php() { setup_php() {
step_log "Setup PHP" step_log "Setup PHP"
if [ "${builds_cache_warning:-false}" = "true" ]; then
add_log "!" "PHP" "Cached PHP builds are experimental on this runner and may fail to install"
fi
sudo mkdir -m 777 -p /var/run /run/php sudo mkdir -m 777 -p /var/run /run/php
php_config="$(command -v php-config)" php_config="$(command -v php-config)"
check_pre_installed check_pre_installed
if [[ -z "$php_config" ]] || [ "$(php_semver | cut -c 1-3)" != "$version" ]; then if [[ -z "$php_config" ]] || [ "$(php_semver | cut -c 1-3)" != "$version" ]; then
if [ ! -e "/usr/bin/php$version" ] || [ ! -e "/usr/bin/php-config$version" ]; then if [ ! -e "/usr/bin/php$version" ] || [ ! -e "/usr/bin/php-config$version" ]; then
add_php >/dev/null 2>&1 add_php
else else
if ! [[ "$version" =~ ${old_versions:?} ]]; then if ! [[ "$version" =~ ${old_versions:?} ]]; then
switch_version >/dev/null 2>&1 switch_version
fi fi
if [ "${update:?}" = "true" ]; then if [ "${update:?}" = "true" ]; then
update_php >/dev/null 2>&1 update_php
else else
status="Switched to" status="Switched to"
fi fi
@@ -317,7 +304,7 @@ setup_php() {
php_config="$(command -v php-config)" php_config="$(command -v php-config)"
else else
if [ "$update" = "true" ]; then if [ "$update" = "true" ]; then
update_php >/dev/null 2>&1 update_php
else else
status="Found" status="Found"
fi fi
@@ -337,7 +324,7 @@ setup_php() {
link_pecl_file link_pecl_file
configure_php configure_php
set_output "php-version" "$semver" set_output "php-version" "$semver"
sudo rm -rf /usr/local/bin/phpunit >/dev/null 2>&1 sudo rm -rf /usr/local/bin/phpunit
sudo chmod 777 "${ini_file[@]}" "$pecl_file" "${tool_path_dir:?}" sudo chmod 777 "${ini_file[@]}" "$pecl_file" "${tool_path_dir:?}"
sudo cp "$src"/configs/pm/*.json "$RUNNER_TOOL_CACHE/" sudo cp "$src"/configs/pm/*.json "$RUNNER_TOOL_CACHE/"
add_log "${tick:?}" "PHP" "$status PHP $semver$extra_version" add_log "${tick:?}" "PHP" "$status PHP $semver$extra_version"
@@ -348,10 +335,11 @@ version=${1:-'8.5'}
ini=${2:-'production'} ini=${2:-'production'}
src=${0%/*}/.. src=${0%/*}/..
debconf_fix="DEBIAN_FRONTEND=noninteractive" debconf_fix="DEBIAN_FRONTEND=noninteractive"
apt_install="sudo $debconf_fix apt-fast install -y --no-install-recommends"
scripts="$src"/scripts scripts="$src"/scripts
add_sudo >/dev/null 2>&1 add_sudo
set_apt_install >/dev/null 2>&1 link_apt_fast
. /etc/os-release . /etc/os-release
# shellcheck source=. # shellcheck source=.
@@ -360,6 +348,7 @@ set_apt_install >/dev/null 2>&1
. "${scripts:?}"/tools/add_tools.sh . "${scripts:?}"/tools/add_tools.sh
. "${scripts:?}"/extensions/source.sh . "${scripts:?}"/extensions/source.sh
. "${scripts:?}"/extensions/add_extensions.sh . "${scripts:?}"/extensions/add_extensions.sh
set -x
read_env read_env
self_hosted_setup self_hosted_setup
setup_php setup_php
+46 -135
View File
@@ -87,38 +87,36 @@ Function Write-ComposerGhAuthNoOpWarning() {
# Function to setup authentication in composer. # Function to setup authentication in composer.
Function Set-ComposerAuth() { Function Set-ComposerAuth() {
Invoke-WithoutTrace { $token = if ($env:COMPOSER_TOKEN) { $env:COMPOSER_TOKEN } else { $env:GITHUB_TOKEN }
$token = if ($env:COMPOSER_TOKEN) { $env:COMPOSER_TOKEN } else { $env:GITHUB_TOKEN } if(Test-Path env:COMPOSER_AUTH_JSON) {
if(Test-Path env:COMPOSER_AUTH_JSON) { if(Test-Json -JSON $env:COMPOSER_AUTH_JSON) {
if(Test-Json -JSON $env:COMPOSER_AUTH_JSON) { Set-Content -Path $composer_home\auth.json -Value $env:COMPOSER_AUTH_JSON
Set-Content -Path $composer_home\auth.json -Value $env:COMPOSER_AUTH_JSON } else {
} else { Add-Log "$cross" "composer" "Could not parse COMPOSER_AUTH_JSON as valid JSON"
Add-Log "$cross" "composer" "Could not parse COMPOSER_AUTH_JSON as valid JSON"
}
} }
if($skip_composer_github_auth) { }
Write-ComposerGhAuthNoOpWarning if($skip_composer_github_auth) {
Write-ComposerGhAuthNoOpWarning
}
$composer_auth = @()
if(Test-Path env:PACKAGIST_TOKEN) {
$composer_auth += '"http-basic": {"repo.packagist.com": { "username": "token", "password": "' + $env:PACKAGIST_TOKEN + '"}}'
}
$write_token = $true
if ($token) {
if ($skip_composer_github_auth) {
$write_token = $false
} }
$composer_auth = @() if ($env:GITHUB_SERVER_URL -ne "https://github.com" -and -not(Test-GitHubPublicAccess $token)) {
if(Test-Path env:PACKAGIST_TOKEN) { $write_token = $false
$composer_auth += '"http-basic": {"repo.packagist.com": { "username": "token", "password": "' + $env:PACKAGIST_TOKEN + '"}}'
} }
$write_token = $true if($write_token) {
if ($token) { $composer_auth += '"github-oauth": {"github.com": "' + $token + '"}'
if ($skip_composer_github_auth) {
$write_token = $false
}
if ($env:GITHUB_SERVER_URL -ne "https://github.com" -and -not(Test-GitHubPublicAccess $token)) {
$write_token = $false
}
if($write_token) {
$composer_auth += '"github-oauth": {"github.com": "' + $token + '"}'
}
}
if($composer_auth.length) {
Update-AuthJson $composer_auth
} }
} }
if($composer_auth.length) {
Update-AuthJson $composer_auth
}
} }
# Function to set composer environment variables. # Function to set composer environment variables.
@@ -146,21 +144,6 @@ Function Test-MutableToolUrl() {
return ($Url -match $mutableUrlRegex) -or (($Url -match '\.phar([?#].*)?$') -and -not ($Url -match $versionLikeRegex)) return ($Url -match $mutableUrlRegex) -or (($Url -match '\.phar([?#].*)?$') -and -not ($Url -match $versionLikeRegex))
} }
# Function to verify the checksum of a file.
Function Test-ToolChecksum() {
Param(
[Parameter(Position = 0, Mandatory = $true)]
[string]
$Path,
[Parameter(Position = 1, Mandatory = $true)]
[string]
$Checksum
)
$checksum_parts = $Checksum -split ':'
$actual_checksum = (Get-FileHash -Path $Path -Algorithm $checksum_parts[0]).Hash
return $actual_checksum -eq $checksum_parts[1]
}
# Function to extract tool version. # Function to extract tool version.
Function Get-ToolVersion() { Function Get-ToolVersion() {
Param ( Param (
@@ -217,15 +200,12 @@ Function Add-ToolsHelper() {
$extensions += @('json', 'tokenizer') $extensions += @('json', 'tokenizer')
} elseif($tool -eq "phpDocumentor") { } elseif($tool -eq "phpDocumentor") {
$extensions+=('ctype', 'hash', 'json', 'fileinfo', 'iconv', 'mbstring', 'simplexml', 'xml') $extensions+=('ctype', 'hash', 'json', 'fileinfo', 'iconv', 'mbstring', 'simplexml', 'xml')
Add-Extension fileinfo >$null 2>&1 Add-Extension fileinfo
Copy-Item $bin_dir\phpDocumentor.bat -Destination $bin_dir\phpdoc.bat Copy-Item $bin_dir\phpDocumentor.bat -Destination $bin_dir\phpdoc.bat
} elseif($tool -eq "phpunit") { } elseif($tool -eq "phpunit") {
$extensions += @('dom', 'json', 'libxml', 'mbstring', 'xml', 'xmlwriter') $extensions += @('dom', 'json', 'libxml', 'mbstring', 'xml', 'xmlwriter')
} elseif($tool -eq "phpunit-bridge") { } elseif($tool -eq "phpunit-bridge") {
$extensions += @('dom', 'pdo', 'tokenizer', 'xmlwriter') $extensions += @('dom', 'pdo', 'tokenizer', 'xmlwriter')
} elseif($tool -eq "cloud-cli") {
$extensions += @('fileinfo', 'sockets')
Copy-Item $env:cloud_cli_bin\cloud.bat -Destination $env:cloud_cli_bin\cloud-cli.bat
} elseif($tool -eq "vapor-cli") { } elseif($tool -eq "vapor-cli") {
$extensions += @('fileinfo', 'json', 'mbstring', 'zip', 'simplexml') $extensions += @('fileinfo', 'json', 'mbstring', 'zip', 'simplexml')
Copy-Item $env:vapor_cli_bin\vapor.bat -Destination $env:vapor_cli_bin\vapor-cli.bat Copy-Item $env:vapor_cli_bin\vapor.bat -Destination $env:vapor_cli_bin\vapor-cli.bat
@@ -233,30 +213,10 @@ Function Add-ToolsHelper() {
Copy-Item $bin_dir\wp-cli.bat -Destination $bin_dir\wp.bat Copy-Item $bin_dir\wp-cli.bat -Destination $bin_dir\wp.bat
} }
foreach($extension in $extensions) { foreach($extension in $extensions) {
Add-Extension $extension >$null 2>&1 Add-Extension $extension
} }
} }
# Function to find the newest stable release containing a tool asset.
Function Get-LastRelease($url) {
$releases_url = $url.Split('/latest/download/')[0]
$asset = $url.Split('/')[-1]
$page = 1
do {
$releases = (Get-File -Url "${releases_url}?page=$page&q=prerelease%3Afalse").Content
foreach ($match in [regex]::Matches($releases, 'src="([^"]+/releases/expanded_assets/[^"]+)"')) {
$assets_url = $match.Groups[1].Value
if (-not $assets_url.StartsWith("$releases_url/expanded_assets/")) { continue }
$download_path = $assets_url.Substring('https://github.com'.Length).Replace('/expanded_assets/', '/download/') + "/$asset"
$assets = (Get-File -Url $assets_url).Content
if ($assets.Contains("href=`"$download_path`"")) {
return "https://github.com$download_path"
}
}
$page++
} while ($releases.Contains('class="next_page"'))
}
# Function to add tools. # Function to add tools.
Function Add-Tool() { Function Add-Tool() {
Param ( Param (
@@ -269,18 +229,8 @@ Function Add-Tool() {
[Parameter(Position = 2, Mandatory = $false)] [Parameter(Position = 2, Mandatory = $false)]
$ver_param, $ver_param,
[Parameter(Position = 3, Mandatory = $false)] [Parameter(Position = 3, Mandatory = $false)]
$skip_composer_github_auth, $skip_composer_github_auth
[Parameter(Position = 4, Mandatory = $false)]
$checksum
) )
$checksum_regex = '^sha(256|512):[0-9a-fA-F]+$'
if("$ver_param" -match $checksum_regex) {
$checksum = $ver_param
$ver_param = $null
} elseif("$skip_composer_github_auth" -match $checksum_regex) {
$checksum = $skip_composer_github_auth
$skip_composer_github_auth = $null
}
if($tool -eq "composer") { if($tool -eq "composer") {
$script:skip_composer_github_auth = $skip_composer_github_auth -eq 'true' $script:skip_composer_github_auth = $skip_composer_github_auth -eq 'true'
} }
@@ -295,12 +245,7 @@ Function Add-Tool() {
$use_cache = -not (Test-MutableToolUrl $urls[0]) $use_cache = -not (Test-MutableToolUrl $urls[0])
$status_code = 200 $status_code = 200
if ($use_cache -and (Test-Path $cache_path -PathType Leaf)) { if ($use_cache -and (Test-Path $cache_path -PathType Leaf)) {
if($checksum -and -not(Test-ToolChecksum $cache_path $checksum)) { Copy-Item $cache_path -Destination $tool_path -Force
Remove-Item $cache_path -Force -ErrorAction SilentlyContinue
$status_code = 'checksum_mismatch'
} else {
Copy-Item $cache_path -Destination $tool_path -Force
}
} else { } else {
$backup_path = "$tool_path.bak" $backup_path = "$tool_path.bak"
if (Test-Path $tool_path) { Copy-Item $tool_path -Destination $backup_path -Force } if (Test-Path $tool_path) { Copy-Item $tool_path -Destination $backup_path -Force }
@@ -308,45 +253,30 @@ Function Add-Tool() {
try { try {
$status_code = (Invoke-WebRequest -Passthru -Uri $url -OutFile $tool_path).StatusCode $status_code = (Invoke-WebRequest -Passthru -Uri $url -OutFile $tool_path).StatusCode
} catch { } catch {
$status_code = 0 if($url -match '.*github.com.*releases.*latest.*') {
if($url -match '^https://github\.com/[^/]+/[^/]+/releases/latest/download/[^/?#]+$') {
try { try {
$release_url = Get-LastRelease $url $url = $url.replace("releases/latest/download", "releases/download/" + ([regex]::match((Get-File -Url ($url.split('/release')[0] + "/releases")).Content, "([0-9]+\.[0-9]+\.[0-9]+)/" + ($url.Substring($url.LastIndexOf("/") + 1))).Groups[0].Value).split('/')[0])
if ($release_url) { $status_code = (Invoke-WebRequest -Passthru -Uri $url -OutFile $tool_path).StatusCode
$url = $release_url
$status_code = (Invoke-WebRequest -Passthru -Uri $url -OutFile $tool_path).StatusCode
}
} catch { } catch {
$status_code = 0 $status_code = 0
} }
} else {
$status_code = 0
} }
} }
if($status_code -eq 200 -and (Test-Path $tool_path)) { if($status_code -eq 200 -and (Test-Path $tool_path)) {
if ($use_cache) {
Copy-Item $tool_path -Destination $cache_path -Force
}
break break
} }
} }
if($status_code -eq 200 -and (Test-Path $tool_path)) {
if($checksum -and -not(Test-ToolChecksum $tool_path $checksum)) {
Remove-Item @($tool_path, $cache_path) -Force -ErrorAction SilentlyContinue
$status_code = 'checksum_mismatch'
} elseif($use_cache) {
Copy-Item $tool_path -Destination $cache_path -Force
}
}
if ($status_code -ne 200 -and (Test-Path $backup_path)) { if ($status_code -ne 200 -and (Test-Path $backup_path)) {
Copy-Item $backup_path -Destination $tool_path -Force Copy-Item $backup_path -Destination $tool_path -Force
} }
Remove-Item $backup_path -Force -ErrorAction SilentlyContinue Remove-Item $backup_path -Force -ErrorAction SilentlyContinue
} }
if($status_code -eq 'checksum_mismatch') {
if($tool -eq "composer") {
$env:fail_fast = 'true'
}
Add-Log $cross $tool "Checksum verification failed for $tool"
return
}
$escaped_tool = [regex]::Escape($tool) $escaped_tool = [regex]::Escape($tool)
if (((Get-ChildItem -Path $bin_dir/* | Where-Object Name -Match "^$escaped_tool(\.exe|\.phar)?$").Count -gt 0)) { if (((Get-ChildItem -Path $bin_dir/* | Where-Object Name -Match "^$escaped_tool(\.exe|\.phar)?$").Count -gt 0)) {
$bat_content = @() $bat_content = @()
@@ -356,7 +286,7 @@ Function Add-Tool() {
$bat_content += "php %BIN_TARGET% %*" $bat_content += "php %BIN_TARGET% %*"
Set-Content -Path $bin_dir\$tool.bat -Value $bat_content Set-Content -Path $bin_dir\$tool.bat -Value $bat_content
Add-ToolsHelper $tool Add-ToolsHelper $tool
Add-ToProfile $current_profile $tool "New-Alias $tool $bin_dir\$tool.bat" >$null 2>&1 Add-ToProfile $current_profile $tool "New-Alias $tool $bin_dir\$tool.bat"
$tool_version = Get-ToolVersion $tool $ver_param $tool_version = Get-ToolVersion $tool $ver_param
Add-Log $tick $tool "Added $tool $tool_version" Add-Log $tick $tool "Added $tool $tool_version"
} else { } else {
@@ -394,36 +324,26 @@ Function Add-ComposerToolHelper() {
Remove-Item -Path $composer_lock -Force Remove-Item -Path $composer_lock -Force
} }
if((composer global show $prefix$tool $tool_version -a 2>&1 | findstr '^type *: *composer-plugin') -and ($composer_args -ne '')) { if((composer global show $prefix$tool $tool_version -a 2>&1 | findstr '^type *: *composer-plugin') -and ($composer_args -ne '')) {
composer global config --no-plugins allow-plugins."$prefix$tool" true >$null 2>&1 composer global config --no-plugins allow-plugins."$prefix$tool" true
}
composer global require $prefix$release $composer_args >$null 2>&1
if($LASTEXITCODE -ne 0) {
return
} }
composer global require $prefix$release $composer_args
return composer global show $prefix$tool 2>&1 | findstr '^versions' return composer global show $prefix$tool 2>&1 | findstr '^versions'
} else { } else {
$release_stream = [System.IO.MemoryStream]::New([System.Text.Encoding]::ASCII.GetBytes($release)) $release_stream = [System.IO.MemoryStream]::New([System.Text.Encoding]::ASCII.GetBytes($release))
$scoped_dir_suffix = (Get-FileHash -InputStream $release_stream -Algorithm sha256).Hash $scoped_dir_suffix = (Get-FileHash -InputStream $release_stream -Algorithm sha256).Hash
$scoped_dir = "$composer_bin\_tools\$tool-$scoped_dir_suffix" $scoped_dir = "$composer_bin\_tools\$tool-$scoped_dir_suffix"
$unix_scoped_dir = $scoped_dir.replace('\', '/') $unix_scoped_dir = $scoped_dir.replace('\', '/')
if(-not(Test-Path $scoped_dir\vendor\autoload.php)) { if(-not(Test-Path $scoped_dir)) {
New-Item -ItemType Directory -Force -Path $scoped_dir > $null 2>&1 New-Item -ItemType Directory -Force -Path $scoped_dir > $null 2>&1
Set-Content -Path $scoped_dir\composer.json -Value "{}" Set-Content -Path $scoped_dir\composer.json -Value "{}"
if((composer show $prefix$tool $tool_version -d $unix_scoped_dir -a 2>&1 | findstr '^type *: *composer-plugin') -and ($composer_args -ne '')) { if((composer show $prefix$tool $tool_version -d $unix_scoped_dir -a 2>&1 | findstr '^type *: *composer-plugin') -and ($composer_args -ne '')) {
composer config -d $unix_scoped_dir --no-plugins allow-plugins."$prefix$tool" true >$null 2>&1 composer config -d $unix_scoped_dir --no-plugins allow-plugins."$prefix$tool" true
} }
composer require $prefix$release -d $unix_scoped_dir $composer_args >$null 2>&1 composer require $prefix$release -d $unix_scoped_dir $composer_args
if($LASTEXITCODE -ne 0) {
return
}
}
$log = composer show $prefix$tool -d $unix_scoped_dir 2>&1 | findstr '^versions'
if(-not $log) {
return
} }
[System.Environment]::SetEnvironmentVariable(($tool.replace('-', '_') + '_bin'), "$scoped_dir\vendor\bin") [System.Environment]::SetEnvironmentVariable(($tool.replace('-', '_') + '_bin'), "$scoped_dir\vendor\bin")
Add-Path $scoped_dir\vendor\bin Add-Path $scoped_dir\vendor\bin
return $log return composer show $prefix$tool -d $unix_scoped_dir 2>&1 | findstr '^versions'
} }
} }
@@ -449,13 +369,7 @@ Function Add-ComposerTool() {
[ValidateNotNull()] [ValidateNotNull()]
[ValidateLength(1, [int]::MaxValue)] [ValidateLength(1, [int]::MaxValue)]
[string] [string]
$scope, $scope
[Parameter(Position = 4, Mandatory = $false)]
[string]
$fallback_url,
[Parameter(Position = 5, Mandatory = $false)]
[string]
$fallback_version_parameter
) )
$composer_args = "" $composer_args = ""
if($composer_version.split('.')[0] -ne "1") { if($composer_version.split('.')[0] -ne "1") {
@@ -471,13 +385,10 @@ Function Add-ComposerTool() {
if(Test-Path $composer_bin\composer) { if(Test-Path $composer_bin\composer) {
Copy-Item -Path "$bin_dir\composer" -Destination "$composer_bin\composer" -Force Copy-Item -Path "$bin_dir\composer" -Destination "$composer_bin\composer" -Force
} }
Add-ToolsHelper $tool
if($log) { if($log) {
$tool_version = Get-ToolVersion "Write-Output" "$log" $tool_version = Get-ToolVersion "Write-Output" "$log"
Add-ToolsHelper $tool
Add-Log $tick $tool "Added $tool $tool_version" Add-Log $tick $tool "Added $tool $tool_version"
} elseif($fallback_url) {
Add-Log "!" $tool "Could not setup $tool using Composer. Falling back to PHAR."
Add-Tool $fallback_url $tool $fallback_version_parameter
} else { } else {
Add-Log $cross $tool "Could not setup $tool" Add-Log $cross $tool "Could not setup $tool"
} }
+24 -87
View File
@@ -69,7 +69,7 @@ update_auth_json() {
# Function to check if public GitHub token authentication is possible. # Function to check if public GitHub token authentication is possible.
can_access_public_github() { can_access_public_github() {
curl --fail -s -H "Authorization: token $1" 'https://api.github.com/' >/dev/null 2>&1 curl --fail -s -H "Authorization: token $1" 'https://api.github.com/'
} }
composer_gh_auth_no_op() { composer_gh_auth_no_op() {
@@ -85,10 +85,6 @@ composer_gh_auth_no_op() {
# Function to setup authentication in composer. # Function to setup authentication in composer.
set_composer_auth() { set_composer_auth() {
without_trace set_composer_auth_helper
}
set_composer_auth_helper() {
token="${COMPOSER_TOKEN:-$GITHUB_TOKEN}" token="${COMPOSER_TOKEN:-$GITHUB_TOKEN}"
if [ -n "${COMPOSER_AUTH_JSON:-}" ]; then if [ -n "${COMPOSER_AUTH_JSON:-}" ]; then
if printf '%s' "$COMPOSER_AUTH_JSON" | jq -e . >/dev/null; then if printf '%s' "$COMPOSER_AUTH_JSON" | jq -e . >/dev/null; then
@@ -131,7 +127,7 @@ set_composer_env() {
add_env_path "$composer_env" add_env_path "$composer_env"
if [ -n "$COMPOSER_ALLOW_PLUGINS" ]; then if [ -n "$COMPOSER_ALLOW_PLUGINS" ]; then
echo "$COMPOSER_ALLOW_PLUGINS" | tr ',' '\n' | sed 's/^[[:space:]]*//;s/[[:space:]]*$//' | grep -v '^$' | while IFS= read -r plugin; do echo "$COMPOSER_ALLOW_PLUGINS" | tr ',' '\n' | sed 's/^[[:space:]]*//;s/[[:space:]]*$//' | grep -v '^$' | while IFS= read -r plugin; do
composer global config --no-plugins "allow-plugins.$plugin" true >/dev/null 2>&1 composer global config --no-plugins "allow-plugins.$plugin" true
done done
fi fi
} }
@@ -189,9 +185,6 @@ add_tools_helper() {
if [ -e "$tool_path_dir"/phpunit ] && [ -d "$composer_bin" ]; then if [ -e "$tool_path_dir"/phpunit ] && [ -d "$composer_bin" ]; then
sudo cp "$tool_path_dir"/phpunit "$composer_bin" sudo cp "$tool_path_dir"/phpunit "$composer_bin"
fi fi
elif [ "$tool" = "cloud-cli" ]; then
extensions+=(dom fileinfo iconv sockets tokenizer)
sudo ln -s "$scoped_dir"/vendor/bin/cloud "$scoped_dir"/vendor/bin/cloud-cli 2>/dev/null || true
elif [ "$tool" = "vapor-cli" ]; then elif [ "$tool" = "vapor-cli" ]; then
extensions+=(fileinfo json mbstring zip simplexml) extensions+=(fileinfo json mbstring zip simplexml)
sudo ln -s "$scoped_dir"/vendor/bin/vapor "$scoped_dir"/vendor/bin/vapor-cli 2>/dev/null || true sudo ln -s "$scoped_dir"/vendor/bin/vapor "$scoped_dir"/vendor/bin/vapor-cli 2>/dev/null || true
@@ -199,28 +192,7 @@ add_tools_helper() {
sudo ln -s "$tool_path" "$tool_path_dir"/"${tool%-*}" 2>/dev/null || true sudo ln -s "$tool_path" "$tool_path_dir"/"${tool%-*}" 2>/dev/null || true
fi fi
for extension in "${extensions[@]}"; do for extension in "${extensions[@]}"; do
add_extension "$extension" extension >/dev/null 2>&1 add_extension "$extension" extension
done
}
# Function to find the newest stable release containing a tool asset.
get_last_release() {
local releases_url="${1%/latest/download/*}"
local asset="${1##*/}"
local page=1 releases assets_url tag download_path
while true; do
releases=$(get -s -n "" "$releases_url?page=$page&q=prerelease%3Afalse") || return 1
while IFS= read -r assets_url; do
[[ "$assets_url" = "$releases_url/expanded_assets/"* ]] || continue
tag="${assets_url#"$releases_url/expanded_assets/"}"
download_path="${releases_url#https://github.com}/download/$tag/$asset"
if get -s -n "" "$assets_url" | grep -Fq "href=\"$download_path\""; then
printf 'https://github.com%s\n' "$download_path"
return 0
fi
done <<< "$(printf '%s' "$releases" | grep -Eo 'src="[^"]+/releases/expanded_assets/[^"]+"' | cut -d '"' -f 2)"
[[ "$releases" = *'class="next_page"'* ]] || return 1
page=$((page + 1))
done done
} }
@@ -229,15 +201,8 @@ add_tool() {
url=$1 url=$1
tool=$2 tool=$2
ver_param=$3 ver_param=$3
checksum=
local arg
for arg in "$@"; do
[[ "$arg" =~ ^sha(256|512):[0-9a-fA-F]+$ ]] && checksum="$arg"
done
[[ "$ver_param" =~ ^sha(256|512): ]] && ver_param=
if [ "$tool" = "composer" ]; then if [ "$tool" = "composer" ]; then
skip_composer_github_auth="${4:-false}" skip_composer_github_auth="${4:-false}"
[[ "$skip_composer_github_auth" =~ ^sha(256|512): ]] && skip_composer_github_auth=false
fi fi
tool_path="$tool_path_dir/$tool" tool_path="$tool_path_dir/$tool"
if ! [ -d "$tool_path_dir" ]; then if ! [ -d "$tool_path_dir" ]; then
@@ -255,36 +220,18 @@ add_tool() {
is_mutable_tool_url "${url[0]}" && use_cache=false is_mutable_tool_url "${url[0]}" && use_cache=false
status_code="200" status_code="200"
if [ "$use_cache" = "true" ] && [ -f "$cache_path" ]; then if [ "$use_cache" = "true" ] && [ -f "$cache_path" ]; then
if [ -n "$checksum" ] && ! verify_checksum "$cache_path" "$checksum"; then sudo cp -a "$cache_path" "$tool_path"
sudo rm -f "$cache_path"
status_code="checksum_mismatch"
else
sudo cp -a "$cache_path" "$tool_path"
fi
else else
[ -f "$tool_path" ] && sudo cp -a "$tool_path" "$tool_path.bak" [ -f "$tool_path" ] && sudo cp -a "$tool_path" "$tool_path.bak"
status_code=$(get -v -e "$tool_path" "${url[@]}") status_code=$(get -v -e "$tool_path" "${url[@]}")
if [ "$status_code" != "200" ] && [[ "${url[0]}" =~ ^https://github\.com/[^/]+/[^/]+/releases/latest/download/[^/?#]+$ ]]; then if [ "$status_code" != "200" ] && [[ "${url[0]}" =~ .*github.com.*releases.*latest.* ]]; then
local release_url url[0]="${url[0]//releases\/latest\/download/releases/download/$(get -s -n "" "$(echo "${url[0]}" | cut -d '/' -f '1-5')/releases" | grep -Eo -m 1 "([0-9]+\.[0-9]+\.[0-9]+)/$(echo "${url[0]}" | sed -e "s/.*\///")" | cut -d '/' -f 1)}"
if release_url=$(get_last_release "${url[0]}"); then status_code=$(get -v -e "$tool_path" "${url[0]}")
url[0]="$release_url"
status_code=$(get -v -e "$tool_path" "${url[0]}")
fi
fi fi
if [ "$status_code" = "200" ]; then if [ "$status_code" = "200" ]; then
if [ -n "$checksum" ] && ! verify_checksum "$tool_path" "$checksum"; then [ "$use_cache" = "true" ] && sudo cp -a "$tool_path" "$cache_path"
sudo rm -f "$tool_path" "$cache_path" elif [ -f "$tool_path.bak" ]; then
status_code="checksum_mismatch" sudo mv "$tool_path.bak" "$tool_path"
elif [ "$use_cache" = "true" ]; then
sudo cp -a "$tool_path" "$cache_path"
fi
fi
if [ "$status_code" != "200" ]; then
if [ -f "$tool_path.bak" ]; then
sudo mv "$tool_path.bak" "$tool_path"
else
sudo rm -f "$tool_path"
fi
fi fi
sudo rm -f "$tool_path.bak" sudo rm -f "$tool_path.bak"
fi fi
@@ -297,9 +244,7 @@ add_tool() {
if [ "$tool" = "composer" ]; then if [ "$tool" = "composer" ]; then
export fail_fast=true export fail_fast=true
fi fi
if [ "$status_code" = "checksum_mismatch" ]; then if [ "$status_code" = "404" ]; then
add_log "$cross" "$tool" "Checksum verification failed for $tool"
elif [ "$status_code" = "404" ]; then
add_log "$cross" "$tool" "Failed to download $tool from ${url[*]}" add_log "$cross" "$tool" "Failed to download $tool from ${url[*]}"
else else
add_log "$cross" "$tool" "Could not setup $tool" add_log "$cross" "$tool" "Could not setup $tool"
@@ -317,24 +262,23 @@ add_composer_tool_helper() {
enable_extensions curl mbstring openssl enable_extensions curl mbstring openssl
tool_version=${release##*:}; [ "$tool_version" = "$tool" ] && tool_version="*" tool_version=${release##*:}; [ "$tool_version" = "$tool" ] && tool_version="*"
if [ "$scope" = "global" ]; then if [ "$scope" = "global" ]; then
sudo rm -f "$composer_lock" >/dev/null 2>&1 || true sudo rm -f "$composer_lock" || true
if composer global show "$prefix$tool" "$tool_version" -a 2>&1 | grep -qE '^type *: *composer-plugin' && [ -n "$composer_args" ]; then if composer global show "$prefix$tool" "$tool_version" -a 2>&1 | grep -qE '^type *: *composer-plugin' && [ -n "$composer_args" ]; then
composer global config --no-plugins allow-plugins."$prefix$tool" true >/dev/null 2>&1 composer global config --no-plugins allow-plugins."$prefix$tool" true
fi fi
composer global require "$prefix$release" "$composer_args" >/dev/null 2>&1 || return 1 composer global require "$prefix$release" "$composer_args"
composer global show "$prefix$tool" 2>&1 | grep -E ^versions | sudo tee /tmp/composer.log >/dev/null 2>&1 composer global show "$prefix$tool" 2>&1 | grep -E ^versions | sudo tee /tmp/composer.log
else else
scoped_dir="$composer_bin/_tools/$tool-$(echo -n "$release" | shasum -a 256 | cut -d ' ' -f 1)" scoped_dir="$composer_bin/_tools/$tool-$(echo -n "$release" | shasum -a 256 | cut -d ' ' -f 1)"
if ! [ -f "$scoped_dir/vendor/autoload.php" ]; then if ! [ -d "$scoped_dir" ]; then
mkdir -p "$scoped_dir" mkdir -p "$scoped_dir"
echo '{}' | tee "$scoped_dir/composer.json" >/dev/null echo '{}' | tee "$scoped_dir/composer.json" >/dev/null
if composer show "$prefix$tool" "$tool_version" -d "$scoped_dir" -a 2>&1 | grep -qE '^type *: *composer-plugin' && [ -n "$composer_args" ]; then if composer show "$prefix$tool" "$tool_version" -d "$scoped_dir" -a 2>&1 | grep -qE '^type *: *composer-plugin' && [ -n "$composer_args" ]; then
composer config -d "$scoped_dir" --no-plugins allow-plugins."$prefix$tool" true >/dev/null 2>&1 composer config -d "$scoped_dir" --no-plugins allow-plugins."$prefix$tool" true
fi fi
composer require "$prefix$release" -d "$scoped_dir" "$composer_args" >/dev/null 2>&1 || return 1 composer require "$prefix$release" -d "$scoped_dir" "$composer_args"
composer show "$prefix$tool" -d "$scoped_dir" 2>&1 | grep -E ^versions | sudo tee /tmp/composer.log
fi fi
composer show "$prefix$tool" -d "$scoped_dir" 2>&1 | grep -E ^versions | sudo tee /tmp/composer.log >/dev/null 2>&1
[ -s /tmp/composer.log ] || return 1
add_path "$scoped_dir"/vendor/bin add_path "$scoped_dir"/vendor/bin
fi fi
} }
@@ -345,7 +289,6 @@ add_composer_tool() {
release=$2 release=$2
prefix=$3 prefix=$3
scope=$4 scope=$4
local fallback_url=${5:-} fallback_version_parameter=${6:-}
composer_args= composer_args=
composer_major_version=$(cut -d'.' -f 1 /tmp/composer_version) composer_major_version=$(cut -d'.' -f 1 /tmp/composer_version)
if [ "$composer_major_version" != "1" ]; then if [ "$composer_major_version" != "1" ]; then
@@ -356,17 +299,11 @@ add_composer_tool() {
return return
fi fi
fi fi
sudo rm -f /tmp/composer.log add_composer_tool_helper "$tool" "$release" "$prefix" "$scope" "$composer_args"
if add_composer_tool_helper "$tool" "$release" "$prefix" "$scope" "$composer_args" && [ -s /tmp/composer.log ]; then tool_version=$(get_tool_version cat /tmp/composer.log)
tool_version=$(get_tool_version cat /tmp/composer.log) ([ -s /tmp/composer.log ] && add_log "$tick" "$tool" "Added $tool $tool_version"
add_tools_helper "$tool" ) || add_log "$cross" "$tool" "Could not setup $tool"
add_log "$tick" "$tool" "Added $tool $tool_version" add_tools_helper "$tool"
elif [ -n "$fallback_url" ]; then
add_log "!" "$tool" "Could not setup $tool using Composer. Falling back to PHAR."
add_tool "$fallback_url" "$tool" "$fallback_version_parameter"
else
add_log "$cross" "$tool" "Could not setup $tool"
fi
if [ -e "$composer_bin/composer" ]; then if [ -e "$composer_bin/composer" ]; then
sudo cp -a "$tool_path_dir/composer" "$composer_bin" sudo cp -a "$tool_path_dir/composer" "$composer_bin"
fi fi
+7 -9
View File
@@ -6,16 +6,14 @@ Function Add-Blackfire() {
} }
$cli_version = (Invoke-RestMethod https://blackfire.io/api/v1/releases).cli $cli_version = (Invoke-RestMethod https://blackfire.io/api/v1/releases).cli
$url = "https://packages.blackfire.io/binaries/blackfire/${cli_version}/blackfire-windows_${arch_name}.zip" $url = "https://packages.blackfire.io/binaries/blackfire/${cli_version}/blackfire-windows_${arch_name}.zip"
Get-File -Url $url -OutFile $bin_dir\blackfire.zip >$null 2>&1 Get-File -Url $url -OutFile $bin_dir\blackfire.zip
Expand-Archive -Path $bin_dir\blackfire.zip -DestinationPath $bin_dir -Force >$null 2>&1 Expand-Archive -Path $bin_dir\blackfire.zip -DestinationPath $bin_dir -Force
Add-ToProfile $current_profile 'blackfire' "New-Alias blackfire $bin_dir\blackfire.exe" Add-ToProfile $current_profile 'blackfire' "New-Alias blackfire $bin_dir\blackfire.exe"
Invoke-WithoutTrace { if ((Test-Path env:BLACKFIRE_SERVER_ID) -and (Test-Path env:BLACKFIRE_SERVER_TOKEN)) {
if ((Test-Path env:BLACKFIRE_SERVER_ID) -and (Test-Path env:BLACKFIRE_SERVER_TOKEN)) { blackfire agent:config --server-id=$env:BLACKFIRE_SERVER_ID --server-token=$env:BLACKFIRE_SERVER_TOKEN
blackfire agent:config --server-id=$env:BLACKFIRE_SERVER_ID --server-token=$env:BLACKFIRE_SERVER_TOKEN >$null 2>&1 }
} if ((Test-Path env:BLACKFIRE_CLIENT_ID) -and (Test-Path env:BLACKFIRE_CLIENT_TOKEN)) {
if ((Test-Path env:BLACKFIRE_CLIENT_ID) -and (Test-Path env:BLACKFIRE_CLIENT_TOKEN)) { blackfire client:config --client-id=$env:BLACKFIRE_CLIENT_ID --client-token=$env:BLACKFIRE_CLIENT_TOKEN --ca-cert=$php_dir\ssl\cacert.pem
blackfire client:config --client-id=$env:BLACKFIRE_CLIENT_ID --client-token=$env:BLACKFIRE_CLIENT_TOKEN --ca-cert=$php_dir\ssl\cacert.pem >$null 2>&1
}
} }
Add-Log $tick "blackfire" "Added blackfire $cli_version" Add-Log $tick "blackfire" "Added blackfire $cli_version"
} }
+3 -7
View File
@@ -12,10 +12,6 @@ add_blackfire_darwin() {
} }
blackfire_config() { blackfire_config() {
without_trace blackfire_config_helper
}
blackfire_config_helper() {
if [[ -n $BLACKFIRE_SERVER_ID ]] && [[ -n $BLACKFIRE_SERVER_TOKEN ]]; then if [[ -n $BLACKFIRE_SERVER_ID ]] && [[ -n $BLACKFIRE_SERVER_TOKEN ]]; then
blackfire agent:config --server-id="$BLACKFIRE_SERVER_ID" --server-token="$BLACKFIRE_SERVER_TOKEN" blackfire agent:config --server-id="$BLACKFIRE_SERVER_ID" --server-token="$BLACKFIRE_SERVER_TOKEN"
if [ "$os" = "Linux" ]; then if [ "$os" = "Linux" ]; then
@@ -36,9 +32,9 @@ blackfire_config_helper() {
# Function to add blackfire cli. # Function to add blackfire cli.
add_blackfire() { add_blackfire() {
os="$(uname -s)" os="$(uname -s)"
[ "$os" = "Linux" ] && add_blackfire_linux >/dev/null 2>&1 [ "$os" = "Linux" ] && add_blackfire_linux
[ "$os" = "Darwin" ] && add_blackfire_darwin >/dev/null 2>&1 [ "$os" = "Darwin" ] && add_blackfire_darwin
blackfire_config >/dev/null 2>&1 blackfire_config
tool_version=$(get_tool_version "blackfire" "version") tool_version=$(get_tool_version "blackfire" "version")
add_log "${tick:?}" "blackfire" "Added blackfire $tool_version" add_log "${tick:?}" "blackfire" "Added blackfire $tool_version"
} }
+31 -62
View File
@@ -14,15 +14,15 @@ add_brew_tap() {
tap=$1 tap=$1
if ! [ -d "$tap_dir/$tap" ]; then if ! [ -d "$tap_dir/$tap" ]; then
if [ "${runner:?}" = "self-hosted" ]; then if [ "${runner:?}" = "self-hosted" ]; then
brew tap "$tap" >/dev/null 2>&1 brew tap "$tap"
else else
fetch_brew_tap "$tap" >/dev/null 2>&1 fetch_brew_tap "$tap"
if ! [ -d "$tap_dir/$tap" ]; then if ! [ -d "$tap_dir/$tap" ]; then
brew tap "$tap" >/dev/null 2>&1 brew tap "$tap"
fi fi
fi fi
fi fi
brew trust "$tap" >/dev/null 2>&1 brew trust "$tap"
} }
# Function to get brew prefix. # Function to get brew prefix.
@@ -55,45 +55,25 @@ get_file_mtime() {
fi fi
} }
# Function to list descendants before their parents, including separate sessions. # Function to terminate a process and its direct children.
get_process_tree() { terminate_process_tree() {
local pid=$1 local pid=$1
local children child local children child
children=$(pgrep -P "$pid" 2>/dev/null || true) children=$(pgrep -P "$pid" 2>/dev/null || true)
kill -TERM "$pid" || true
for child in $children; do for child in $children; do
get_process_tree "$child" terminate_process_tree "$child"
done
echo "$pid"
}
# Function to detect Homebrew's source-build worker, even with buffered output.
is_brew_building_from_source() {
local pid
for pid in $(get_process_tree "$1"); do
if ps -ww -p "$pid" -o command= 2>/dev/null | grep -qE '/Homebrew/build[.]rb([[:space:]]|$)'; then
return 0
fi
done
return 1
}
# Function to terminate the entire tree captured before any parents can exit.
terminate_process_tree() {
local pids pid
pids=$(get_process_tree "$1")
for pid in $pids; do
kill -TERM "$pid" >/dev/null 2>&1 || true
done done
sleep 2 sleep 2
for pid in $pids; do kill -KILL "$pid" || true
kill -KILL "$pid" >/dev/null 2>&1 || true for child in $children; do
terminate_process_tree "$child"
done done
} }
# Function to run a command with an inactivity watchdog. # Function to run a command with an inactivity watchdog.
run_with_inactivity_watchdog() { run_with_inactivity_watchdog() {
local timeout_secs="${SETUP_PHP_BREW_INACTIVITY_TIMEOUT:-180}" local timeout_secs="${SETUP_PHP_BREW_INACTIVITY_TIMEOUT:-180}"
local source_timeout_secs="${SETUP_PHP_BREW_SOURCE_INACTIVITY_TIMEOUT:-1800}"
local poll_secs="${SETUP_PHP_BREW_WATCHDOG_POLL:-5}" local poll_secs="${SETUP_PHP_BREW_WATCHDOG_POLL:-5}"
local tmp_dir stdout_fifo stderr_fifo stdout_log stderr_log timeout_file local tmp_dir stdout_fifo stderr_fifo stdout_log stderr_log timeout_file
local command_pid stdout_reader_pid stderr_reader_pid monitor_pid exit_code local command_pid stdout_reader_pid stderr_reader_pid monitor_pid exit_code
@@ -113,39 +93,36 @@ run_with_inactivity_watchdog() {
("$@" >"$stdout_fifo" 2>"$stderr_fifo") & ("$@" >"$stdout_fifo" 2>"$stderr_fifo") &
command_pid=$! command_pid=$!
tee "$stdout_log" <"$stdout_fifo" & (
while IFS= read -r line || [ -n "$line" ]; do
printf '%s\n' "$line"
printf '%s\n' "$line" >>"$stdout_log"
done <"$stdout_fifo"
) &
stdout_reader_pid=$! stdout_reader_pid=$!
tee "$stderr_log" <"$stderr_fifo" >&2 & (
while IFS= read -r line || [ -n "$line" ]; do
printf '%s\n' "$line" >&2
printf '%s\n' "$line" >>"$stderr_log"
done <"$stderr_fifo"
) &
stderr_reader_pid=$! stderr_reader_pid=$!
( (
local last_activity current_activity current_err_activity now local last_activity current_activity current_err_activity now
local building_from_source=false was_building_from_source=false active_timeout_secs
last_activity=$(get_file_mtime "$stdout_log") last_activity=$(get_file_mtime "$stdout_log")
current_err_activity=$(get_file_mtime "$stderr_log") current_err_activity=$(get_file_mtime "$stderr_log")
[ "$current_err_activity" -gt "$last_activity" ] && last_activity="$current_err_activity" [ "$current_err_activity" -gt "$last_activity" ] && last_activity="$current_err_activity"
while kill -0 "$command_pid" >/dev/null 2>&1; do while kill -0 "$command_pid" ; do
sleep "$poll_secs" sleep "$poll_secs"
kill -0 "$command_pid" >/dev/null 2>&1 || break
now=$(date +%s)
active_timeout_secs="$timeout_secs"
building_from_source=false
if is_brew_building_from_source "$command_pid"; then
building_from_source=true
active_timeout_secs="$source_timeout_secs"
fi
if [ "$building_from_source" != "$was_building_from_source" ]; then
last_activity="$now"
was_building_from_source="$building_from_source"
fi
current_activity=$(get_file_mtime "$stdout_log") current_activity=$(get_file_mtime "$stdout_log")
[ "$current_activity" -gt "$last_activity" ] && last_activity="$current_activity" [ "$current_activity" -gt "$last_activity" ] && last_activity="$current_activity"
current_err_activity=$(get_file_mtime "$stderr_log") current_err_activity=$(get_file_mtime "$stderr_log")
[ "$current_err_activity" -gt "$last_activity" ] && last_activity="$current_err_activity" [ "$current_err_activity" -gt "$last_activity" ] && last_activity="$current_err_activity"
now=$(date +%s) now=$(date +%s)
if [ $((now - last_activity)) -ge "$active_timeout_secs" ]; then if [ $((now - last_activity)) -ge "$timeout_secs" ]; then
printf "\nsetup-php: brew produced no output for %ss; terminating...\n" "$active_timeout_secs" >&2 printf "\nsetup-php: brew produced no output for %ss; terminating and retrying...\n" "$timeout_secs" >&2
: >"$timeout_file" : >"$timeout_file"
terminate_process_tree "$command_pid" terminate_process_tree "$command_pid"
break break
@@ -154,15 +131,12 @@ run_with_inactivity_watchdog() {
) & ) &
monitor_pid=$! monitor_pid=$!
exit_code=0 wait "$command_pid"
wait "$command_pid" || exit_code=$? exit_code=$?
# Let timeout cleanup finish killing source-build descendants before retrying.
if [ ! -e "$timeout_file" ]; then
kill "$monitor_pid" >/dev/null 2>&1 || true
fi
wait "$monitor_pid" 2>/dev/null || true
wait "$stdout_reader_pid" 2>/dev/null || true wait "$stdout_reader_pid" 2>/dev/null || true
wait "$stderr_reader_pid" 2>/dev/null || true wait "$stderr_reader_pid" 2>/dev/null || true
kill "$monitor_pid" || true
wait "$monitor_pid" 2>/dev/null || true
if [ -e "$timeout_file" ]; then if [ -e "$timeout_file" ]; then
rm -rf "$tmp_dir" rm -rf "$tmp_dir"
@@ -205,7 +179,7 @@ add_brew() {
brew_prefix="$(get_brew_prefix)" brew_prefix="$(get_brew_prefix)"
if ! [ -d "$brew_prefix"/bin ]; then if ! [ -d "$brew_prefix"/bin ]; then
step_log "Setup Brew" step_log "Setup Brew"
get -s "" "/tmp/install.sh" "https://raw.githubusercontent.com/Homebrew/install/main/install.sh" | bash -s >/dev/null 2>&1 get -s "" "/tmp/install.sh" "https://raw.githubusercontent.com/Homebrew/install/main/install.sh" | bash -s
add_log "${tick:?}" "Brew" "Installed Homebrew" add_log "${tick:?}" "Brew" "Installed Homebrew"
fi fi
add_brew_bins_to_path "$brew_prefix" add_brew_bins_to_path "$brew_prefix"
@@ -225,11 +199,6 @@ configure_brew() {
tap_dir="$brew_repo"/Library/Taps tap_dir="$brew_repo"/Library/Taps
core_repo="$tap_dir"/homebrew/homebrew-core core_repo="$tap_dir"/homebrew/homebrew-core
if [ -d "$core_repo" ]; then
export HOMEBREW_NO_INSTALL_FROM_API=1
else
unset HOMEBREW_NO_INSTALL_FROM_API
fi
export HOMEBREW_CHANGE_ARCH_TO_ARM=1 export HOMEBREW_CHANGE_ARCH_TO_ARM=1
export HOMEBREW_NO_AUTO_UPDATE=1 export HOMEBREW_NO_AUTO_UPDATE=1
export HOMEBREW_NO_ENV_HINTS=1 export HOMEBREW_NO_ENV_HINTS=1
+2 -2
View File
@@ -1,7 +1,7 @@
Function Add-Msys2() { Function Add-Msys2() {
$msys_location = 'C:\msys64' $msys_location = 'C:\msys64'
if (-not(Test-Path $msys_location)) { if (-not(Test-Path $msys_location)) {
choco install msys2 -y >$null 2>&1 choco install msys2 -y
$msys_location = 'C:\tools\msys64' $msys_location = 'C:\tools\msys64'
} }
return $msys_location return $msys_location
@@ -15,7 +15,7 @@ Function Add-GrpcPhpPlugin() {
} else { } else {
$grpc_package = 'mingw-w64-x86_64-grpc' $grpc_package = 'mingw-w64-x86_64-grpc'
} }
$logs = . $msys_location\usr\bin\bash -l -c "pacman -S --noconfirm $grpc_package" >$null 2>&1 $logs = . $msys_location\usr\bin\bash -l -c "pacman -S --noconfirm $grpc_package"
$grpc_version = Get-ToolVersion 'Write-Output' "$logs" $grpc_version = Get-ToolVersion 'Write-Output' "$logs"
Add-Path $msys_location\mingw64\bin Add-Path $msys_location\mingw64\bin
Set-Output grpc_php_plugin_path "$msys_location\mingw64\bin\grpc_php_plugin.exe" Set-Output grpc_php_plugin_path "$msys_location\mingw64\bin\grpc_php_plugin.exe"
+3 -3
View File
@@ -26,7 +26,7 @@ add_grpc_php_plugin_brew() {
configure_brew configure_brew
[ -e /usr/local/bin/protoc ] && sudo mv /usr/local/bin/protoc /tmp/protoc && sudo mv /usr/local/include/google /tmp [ -e /usr/local/bin/protoc ] && sudo mv /usr/local/bin/protoc /tmp/protoc && sudo mv /usr/local/include/google /tmp
safe_brew install grpc safe_brew install grpc
brew link --force --overwrite grpc >/dev/null 2>&1 brew link --force --overwrite grpc
[ -e /tmp/protoc ] && sudo mv /tmp/protoc /usr/local/bin/protoc && sudo mv /tmp/google /usr/local/include/ [ -e /tmp/protoc ] && sudo mv /tmp/protoc /usr/local/bin/protoc && sudo mv /tmp/google /usr/local/include/
grpc_tag="v$(brew info grpc | grep "grpc:" | grep -Eo "[0-9]+\.[0-9]+\.[0-9]+")" grpc_tag="v$(brew info grpc | grep "grpc:" | grep -Eo "[0-9]+\.[0-9]+\.[0-9]+")"
license_path="$(brew --prefix grpc)/LICENSE" license_path="$(brew --prefix grpc)/LICENSE"
@@ -50,9 +50,9 @@ add_grpc_php_plugin() {
grpc_tag=$1 grpc_tag=$1
license_path="" license_path=""
if [ "$grpc_tag" = "latest" ]; then if [ "$grpc_tag" = "latest" ]; then
add_grpc_php_plugin_brew >/dev/null 2>&1 add_grpc_php_plugin_brew
else else
add_grpc_php_plugin_compile >/dev/null 2>&1 add_grpc_php_plugin_compile
fi fi
set_output grpc_php_plugin_path "$(command -v grpc_php_plugin)" set_output grpc_php_plugin_path "$(command -v grpc_php_plugin)"
add_log "${tick:?}" "grpc_php_plugin" "Added grpc_php_plugin ${grpc_tag:1}" add_log "${tick:?}" "grpc_php_plugin" "Added grpc_php_plugin ${grpc_tag:1}"
+2 -2
View File
@@ -28,8 +28,8 @@ Function Add-Mago() {
$arch_name = 'i686' $arch_name = 'i686'
} }
$url = "https://github.com/carthage-software/mago/releases/download/$mago_tag/mago-$mago_tag-$arch_name-pc-windows-msvc.zip" $url = "https://github.com/carthage-software/mago/releases/download/$mago_tag/mago-$mago_tag-$arch_name-pc-windows-msvc.zip"
Get-File -Url $url -OutFile $bin_dir\mago.zip >$null 2>&1 Get-File -Url $url -OutFile $bin_dir\mago.zip
Expand-Archive -Path $bin_dir\mago.zip -DestinationPath $bin_dir\mago -Force >$null 2>&1 Expand-Archive -Path $bin_dir\mago.zip -DestinationPath $bin_dir\mago -Force
Move-Item -Path $bin_dir\mago\mago-$mago_tag-$arch_name-pc-windows-msvc\mago.exe -Destination $bin_dir\mago.exe -Force Move-Item -Path $bin_dir\mago\mago-$mago_tag-$arch_name-pc-windows-msvc\mago.exe -Destination $bin_dir\mago.exe -Force
Add-ToProfile $current_profile 'mago' "New-Alias mago $bin_dir\mago.exe" Add-ToProfile $current_profile 'mago' "New-Alias mago $bin_dir\mago.exe"
Add-Log $tick "mago" "Added mago $mago_tag" Add-Log $tick "mago" "Added mago $mago_tag"
+1 -1
View File
@@ -24,6 +24,6 @@ add_mago() {
sudo tar -xzf /tmp/mago.tar.gz -C /tmp/ sudo tar -xzf /tmp/mago.tar.gz -C /tmp/
sudo mv /tmp/mago-$mago_tag-$arch-$platform/mago /usr/local/bin/mago sudo mv /tmp/mago-$mago_tag-$arch-$platform/mago /usr/local/bin/mago
sudo chmod +x /usr/local/bin/mago sudo chmod +x /usr/local/bin/mago
) >/dev/null 2>&1 )
add_log "${tick:?}" "mago" "Added mago $mago_tag" add_log "${tick:?}" "mago" "Added mago $mago_tag"
} }
+14 -23
View File
@@ -31,7 +31,7 @@ set_base_version() {
else else
set_base_version_codename set_base_version_codename
set_base_version_id set_base_version_id
printf "ID=%s\nVERSION_ID=%s\nVERSION_CODENAME=%s\n" "$ID" "$VERSION_ID" "$VERSION_CODENAME" | tee /tmp/os-release >/dev/null 2>&1 printf "ID=%s\nVERSION_ID=%s\nVERSION_CODENAME=%s\n" "$ID" "$VERSION_ID" "$VERSION_CODENAME" | tee /tmp/os-release
fi fi
} }
@@ -70,8 +70,8 @@ update_lists() {
list="$list_file" list="$list_file"
fi fi
if [ ! -e "$status_file" ]; then if [ ! -e "$status_file" ]; then
update_lists_helper "$list" >/dev/null 2>&1 update_lists_helper "$list"
echo '' | tee "$status_file" >/dev/null 2>&1 echo '' | tee "$status_file"
fi fi
} }
@@ -186,7 +186,7 @@ add_key() {
key_urls+=("$ppa_sp/keys/$ppa.gpg") key_urls+=("$ppa_sp/keys/$ppa.gpg")
[ ! -e "$key_source" ] && get -q -n "$key_file" "${key_urls[@]}" [ ! -e "$key_source" ] && get -q -n "$key_file" "${key_urls[@]}"
if [[ "$(file "$key_file")" =~ .*('Public-Key (old)'|'Secret-Key') ]]; then if [[ "$(file "$key_file")" =~ .*('Public-Key (old)'|'Secret-Key') ]]; then
sudo gpg --batch --yes --dearmor "$key_file" >/dev/null 2>&1 && sudo mv "$key_file".gpg "$key_file" sudo gpg --batch --yes --dearmor "$key_file" && sudo mv "$key_file".gpg "$key_file"
fi fi
} }
@@ -230,7 +230,7 @@ Architectures: $arch
Signed-By: $key_file Signed-By: $key_file
EOF EOF
else else
echo "deb [arch=$arch signed-by=$key_file] $url $suite $components" | sudo tee "$list_dir"/"$list_basename".list >/dev/null 2>&1 echo "deb [arch=$arch signed-by=$key_file] $url $suite $components" | sudo tee "$list_dir"/"$list_basename".list
fi fi
} }
@@ -343,32 +343,23 @@ add_ppa_sp_mirror() {
add_list sp/"$ppa_name" "$ppa_sp/$ppa/ubuntu" "$ppa_sp/$ppa/ubuntu/key.gpg" add_list sp/"$ppa_name" "$ppa_sp/$ppa/ubuntu" "$ppa_sp/$ppa/ubuntu/key.gpg"
} }
add_sury_list() {
ppa=${1:-ondrej/php}
[ "${debug:?}" = "debug" ] && add_list "$ppa" "$sury"/"${ppa##*/}"/ "$sury"/"${ppa##*/}"/apt.gpg "$VERSION_CODENAME" "main/debug"
add_list "$ppa" "$sury"/"${ppa##*/}"/ "$sury"/"${ppa##*/}"/apt.gpg
}
# Function to add a PPA. # Function to add a PPA.
add_ppa() { add_ppa() {
set_base_version set_base_version
ppa=${1:-ondrej/php} ppa=${1:-ondrej/php}
if [[ "$ID" = "ubuntu" || "$ID_LIKE" =~ ubuntu ]] && [[ "$ppa" =~ "ondrej/" ]]; then if [[ "$ID" = "ubuntu" || "$ID_LIKE" =~ ubuntu ]] && [[ "$ppa" =~ "ondrej/" ]]; then
if [ "$VERSION_ID" = "26.04" ]; then if is_ubuntu_ppa_up "$ppa" ; then
add_sury_list [ "${runner:?}" = "self-hosted" ] && find "$list_dir" -type f -name 'sp*' -exec grep -qF "${sp/https:\/\/}" {} \; -delete
[ "${debug:?}" = "debug" ] && add_list "$ppa" "$lpc_ppa/$ppa/ubuntu" "$lpc_ppa/$ppa/ubuntu" "$VERSION_CODENAME" "main/debug"
add_list "$ppa"
elif [ "$ppa" = "ondrej/php" ]; then
add_ppa_sp_mirror "$ppa"
else else
if is_ubuntu_ppa_up "$ppa" ; then add_log "${cross:?}" "$ppa" "PPA $ppa is not available"
[ "${runner:?}" = "self-hosted" ] && find "$list_dir" -type f -name 'sp*' -exec grep -qF "${sp/https:\/\/}" {} \; -delete
[ "${debug:?}" = "debug" ] && add_list "$ppa" "$lpc_ppa/$ppa/ubuntu" "$lpc_ppa/$ppa/ubuntu" "$VERSION_CODENAME" "main/debug"
add_list "$ppa"
elif [ "$ppa" = "ondrej/php" ]; then
add_ppa_sp_mirror "$ppa"
else
add_log "${cross:?}" "$ppa" "PPA $ppa is not available"
fi
fi fi
elif [[ "$ID" = "debian" || "$ID_LIKE" =~ debian ]] && [[ "$ppa" =~ "ondrej/" ]]; then elif [[ "$ID" = "debian" || "$ID_LIKE" =~ debian ]] && [[ "$ppa" =~ "ondrej/" ]]; then
add_sury_list [ "${debug:?}" = "debug" ] && add_list "$ppa" "$sury"/"${ppa##*/}"/ "$sury"/"${ppa##*/}"/apt.gpg "$VERSION_CODENAME" "main/debug"
add_list "$ppa" "$sury"/"${ppa##*/}"/ "$sury"/"${ppa##*/}"/apt.gpg
else else
add_list "$ppa" add_list "$ppa"
fi fi
+2 -2
View File
@@ -29,8 +29,8 @@ Function Add-Protoc() {
$arch_num = '32' $arch_num = '32'
} }
$url = "https://github.com/protocolbuffers/protobuf/releases/download/$protobuf_tag/protoc-$($protobuf_tag -replace 'v', '')-win$arch_num.zip" $url = "https://github.com/protocolbuffers/protobuf/releases/download/$protobuf_tag/protoc-$($protobuf_tag -replace 'v', '')-win$arch_num.zip"
Get-File -Url $url -OutFile $bin_dir\protoc.zip >$null 2>&1 Get-File -Url $url -OutFile $bin_dir\protoc.zip
Expand-Archive -Path $bin_dir\protoc.zip -DestinationPath $bin_dir\protoc -Force >$null 2>&1 Expand-Archive -Path $bin_dir\protoc.zip -DestinationPath $bin_dir\protoc -Force
Move-Item -Path $bin_dir\protoc\bin\protoc.exe -Destination $bin_dir\protoc.exe Move-Item -Path $bin_dir\protoc\bin\protoc.exe -Destination $bin_dir\protoc.exe
Add-ToProfile $current_profile 'protoc' "New-Alias protoc $bin_dir\protoc.exe" Add-ToProfile $current_profile 'protoc' "New-Alias protoc $bin_dir\protoc.exe"
Add-Log $tick "protoc" "Added protoc $($protobuf_tag -replace 'v', '')" Add-Log $tick "protoc" "Added protoc $($protobuf_tag -replace 'v', '')"
+1 -1
View File
@@ -22,7 +22,7 @@ add_protoc() {
get -q -n /tmp/protobuf.zip "https://github.com/protocolbuffers/protobuf/releases/download/$protobuf_tag/protoc-${protobuf_tag:1}-$platform-$arch.zip" get -q -n /tmp/protobuf.zip "https://github.com/protocolbuffers/protobuf/releases/download/$protobuf_tag/protoc-${protobuf_tag:1}-$platform-$arch.zip"
sudo unzip /tmp/protobuf.zip -d /usr/local/ sudo unzip /tmp/protobuf.zip -d /usr/local/
sudo chmod -R 777 /usr/local/bin/protoc /usr/local/include/google sudo chmod -R 777 /usr/local/bin/protoc /usr/local/include/google
) >/dev/null 2>&1 )
add_log "${tick:?}" "protoc" "Added protoc ${protobuf_tag:1}" add_log "${tick:?}" "protoc" "Added protoc ${protobuf_tag:1}"
printf "$GROUP\033[34;1m%s \033[0m\033[90;1m%s \033[0m\n" "protoc" "Click to read the protoc related license information" printf "$GROUP\033[34;1m%s \033[0m\033[90;1m%s \033[0m\n" "protoc" "Click to read the protoc related license information"
curl "${curl_opts[@]:?}" https://raw.githubusercontent.com/protocolbuffers/protobuf/main/LICENSE curl "${curl_opts[@]:?}" https://raw.githubusercontent.com/protocolbuffers/protobuf/main/LICENSE
+1 -1
View File
@@ -31,7 +31,7 @@ add_symfony() {
if ! [[ "$symfony_tag" =~ ^[0-9]+(\.[0-9]+)*$ || "$symfony_tag" == 'latest' ]]; then if ! [[ "$symfony_tag" =~ ^[0-9]+(\.[0-9]+)*$ || "$symfony_tag" == 'latest' ]]; then
add_log "${cross:?}" "symfony-cli" "Version '$symfony_tag' is not valid for symfony-cli" add_log "${cross:?}" "symfony-cli" "Version '$symfony_tag' is not valid for symfony-cli"
else else
add_symfony_helper "$symfony_tag" >/dev/null 2>&1 add_symfony_helper "$symfony_tag"
symfony_path="$(command -v symfony)" symfony_path="$(command -v symfony)"
if [[ -n "$symfony_path" ]]; then if [[ -n "$symfony_path" ]]; then
sudo ln -s "$symfony_path" "${tool_path_dir:?}"/symfony-cli sudo ln -s "$symfony_path" "${tool_path_dir:?}"/symfony-cli
+9 -68
View File
@@ -33,8 +33,6 @@ add_log() {
local message=$3 local message=$3
if [ "$mark" = "$tick" ]; then if [ "$mark" = "$tick" ]; then
printf "\033[32;1m%s \033[0m\033[34;1m%s \033[0m\033[90;1m%s\033[0m\n" "$mark" "$subject" "$message" printf "\033[32;1m%s \033[0m\033[34;1m%s \033[0m\033[90;1m%s\033[0m\n" "$mark" "$subject" "$message"
elif [ "$mark" = "!" ]; then
printf "\033[33;1m%s \033[0m\033[34;1m%s \033[0m\033[90;1m%s\033[0m\n" "$mark" "$subject" "$message"
else else
printf "\033[31;1m%s \033[0m\033[34;1m%s \033[0m\033[90;1m%s\033[0m\n" "$mark" "$subject" "$message" printf "\033[31;1m%s \033[0m\033[34;1m%s \033[0m\033[90;1m%s\033[0m\n" "$mark" "$subject" "$message"
[ "$fail_fast" = "true" ] && exit 1 [ "$fail_fast" = "true" ] && exit 1
@@ -46,58 +44,20 @@ set_output() {
name=$1 name=$1
value=$2 value=$2
if [ "${GITHUB_ACTIONS}" = "true" ]; then if [ "${GITHUB_ACTIONS}" = "true" ]; then
echo "${name}=${value}" | tee -a "$GITHUB_OUTPUT" >/dev/null 2>&1 echo "${name}=${value}" | tee -a "$GITHUB_OUTPUT"
fi fi
} }
# Function to run sensitive code without tracing. Expand tokens inside the function, not its arguments.
without_trace() {
local setup_php_trace_flags=$-
set +x
"$@"
local setup_php_trace_status=$?
[[ "$setup_php_trace_flags" == *x* ]] && set -x
return "$setup_php_trace_status"
}
# Function to check third-party runners eligible for the builds cache.
check_builds_cache_runner() {
local pid=$PPID executable
while [[ "$pid" =~ ^[0-9]+$ && "$pid" -gt 1 ]]; do
executable="$(readlink -f "/proc/$pid/exe")" || return 1
if [[ "$executable" = */bin/Runner.Worker ]]; then
jq -e --arg name "${RUNNER_NAME:-}" \
'.AgentName == $name and (.AgentName | test("^(blacksmith|depot)-"))' \
"${executable%/bin/Runner.Worker}/.runner" >/dev/null 2>&1
return $?
fi
pid="$(awk '$1 == "PPid:" {print $2}' "/proc/$pid/status")" || return 1
done
return 1
}
# Function to read env inputs. # Function to read env inputs.
read_env() { read_env() {
if [[ "${SETUP_PHP_TRACE:-0}" =~ ^[12]$ ]]; then
set -x
fi
update="${update:-${UPDATE:-false}}" update="${update:-${UPDATE:-false}}"
[ "${debug:-${DEBUG:-false}}" = "true" ] && debug=debug && update=true || debug=release [ "${debug:-${DEBUG:-false}}" = "true" ] && debug=debug && update=true || debug=release
[[ "${phpts:-${PHPTS:-nts}}" = "ts" || "${phpts:-${PHPTS:-nts}}" = "zts" ]] && ts=zts && update=true || ts=nts [[ "${phpts:-${PHPTS:-nts}}" = "ts" || "${phpts:-${PHPTS:-nts}}" = "zts" ]] && ts=zts && update=true || ts=nts
fail_fast="${fail_fast:-${FAIL_FAST:-false}}" fail_fast="${fail_fast:-${FAIL_FAST:-false}}"
use_builds_cache="${use_builds_cache:-${use_package_cache:-}}"
[[ ( -z "$ImageOS" && -z "$ImageVersion" ) || [[ ( -z "$ImageOS" && -z "$ImageVersion" ) ||
( -n "$RUNNER_ENVIRONMENT" && "$RUNNER_ENVIRONMENT" = "self-hosted" ) || ( -n "$RUNNER_ENVIRONMENT" && "$RUNNER_ENVIRONMENT" = "self-hosted" ) ||
-n "$ACT" || -n "$CONTAINER" ]] && _runner=self-hosted || _runner=github -n "$ACT" || -n "$CONTAINER" ]] && _runner=self-hosted || _runner=github
runner="${runner:-${RUNNER:-$_runner}}" runner="${runner:-${RUNNER:-$_runner}}"
if [[ $_runner = "self-hosted" && "${use_builds_cache:-false}" = "true" ]]; then
runner=github
if [[ "${ID:-}" = "ubuntu" && -z "$ACT" && -z "$CONTAINER" &&
( -n "${BLACKSMITH_VM_ID:-}" || "${RUNNER_NAME:-}" =~ ^(blacksmith|depot)- ) ]] && check_builds_cache_runner; then
_runner=github
builds_cache_warning=true
fi
fi
tool_path_dir="${setup_php_tools_dir:-${SETUP_PHP_TOOLS_DIR:-/usr/local/bin}}" tool_path_dir="${setup_php_tools_dir:-${SETUP_PHP_TOOLS_DIR:-/usr/local/bin}}"
tool_cache_path_dir="${setup_php_tool_cache_dir:-${SETUP_PHP_TOOL_CACHE_DIR:-${RUNNER_TOOL_CACHE:-/opt/hostedtoolcache}/setup-php/tools}}" tool_cache_path_dir="${setup_php_tool_cache_dir:-${SETUP_PHP_TOOL_CACHE_DIR:-${RUNNER_TOOL_CACHE:-/opt/hostedtoolcache}/setup-php/tools}}"
@@ -110,7 +70,7 @@ read_env() {
if [[ "$runner" = "github" && "${ImageOS}" =~ ubuntu.* ]]; then if [[ "$runner" = "github" && "${ImageOS}" =~ ubuntu.* ]]; then
if ! check_ppa ondrej/php; then if ! check_ppa ondrej/php; then
update=true update=true
echo '' | sudo tee /tmp/sp_update >/dev/null 2>&1 echo '' | sudo tee /tmp/sp_update
elif [ -e /tmp/sp_update ]; then elif [ -e /tmp/sp_update ]; then
update=true update=true
fi fi
@@ -134,7 +94,7 @@ acquire_lock() {
else else
if sudo test -f "$lock_path/pid"; then if sudo test -f "$lock_path/pid"; then
lock_pid=$(sudo cat "$lock_path/pid") lock_pid=$(sudo cat "$lock_path/pid")
if ! ps -p "$lock_pid" >/dev/null 2>&1; then if ! ps -p "$lock_pid" ; then
sudo rm -rf "$lock_path" sudo rm -rf "$lock_path"
continue continue
fi fi
@@ -162,25 +122,6 @@ get_sha256() {
fi fi
} }
# Function to verify the checksum of a file.
# checksum format: sha256:<hash> or sha512:<hash>
verify_checksum() {
local file_path=$1
local checksum=$2
local algo="${checksum%%:*}"
local expected="${checksum#*:}"
local actual=
local hash_command=
if hash_command="$(command -v "${algo}sum")"; then
actual="$(sudo "$hash_command" "$file_path" | cut -d' ' -f1)"
elif hash_command="$(command -v shasum)"; then
actual="$(sudo "$hash_command" -a "${algo#sha}" "$file_path" | cut -d' ' -f1)"
elif hash_command="$(command -v openssl)"; then
actual="$(sudo "$hash_command" dgst -"$algo" "$file_path" | awk '{print $NF}')"
fi
[ -n "$actual" ] && [ "$(echo "$actual" | tr '[:upper:]' '[:lower:]')" = "$(echo "$expected" | tr '[:upper:]' '[:lower:]')" ]
}
# Function to download a file using cURL. # Function to download a file using cURL.
# mode: -s pipe to stdout, -v save file and return status code # mode: -s pipe to stdout, -v save file and return status code
# execute: -e save file as executable # execute: -e save file as executable
@@ -237,7 +178,7 @@ add_path() {
printf '%s\n%s' "$path_to_add" "$(grep -v "^${path_to_add}$" "$GITHUB_PATH" 2>/dev/null)" > "$GITHUB_PATH" printf '%s\n%s' "$path_to_add" "$(grep -v "^${path_to_add}$" "$GITHUB_PATH" 2>/dev/null)" > "$GITHUB_PATH"
else else
profile=$(get_shell_profile) profile=$(get_shell_profile)
([ -e "$profile" ] && grep -q ":$path_to_add\"" "$profile" 2>/dev/null) || echo "export PATH=\"\${PATH:+\${PATH}:}\"$path_to_add" | sudo tee -a "$profile" >/dev/null 2>&1 ([ -e "$profile" ] && grep -q ":$path_to_add\"" "$profile" 2>/dev/null) || echo "export PATH=\"\${PATH:+\${PATH}:}\"$path_to_add" | sudo tee -a "$profile"
fi fi
[[ ":$PATH:" == *":$path_to_add:"* ]] || export PATH="${PATH:+${PATH}:}$path_to_add" [[ ":$PATH:" == *":$path_to_add:"* ]] || export PATH="${PATH:+${PATH}:}$path_to_add"
} }
@@ -259,10 +200,10 @@ add_env() {
env_name=$1 env_name=$1
env_value=$2 env_value=$2
if [[ -n "$GITHUB_ENV" ]]; then if [[ -n "$GITHUB_ENV" ]]; then
echo "$env_name=$env_value" | tee -a "$GITHUB_ENV" >/dev/null 2>&1 echo "$env_name=$env_value" | tee -a "$GITHUB_ENV"
else else
profile=$(get_shell_profile) profile=$(get_shell_profile)
echo "export $env_name=\"$env_value\"" | sudo tee -a "$profile" >/dev/null 2>&1 echo "export $env_name=\"$env_value\"" | sudo tee -a "$profile"
fi fi
export "$env_name"="$env_value" export "$env_name"="$env_value"
} }
@@ -283,7 +224,7 @@ self_hosted_setup() {
add_log "$cross" "PHP" "PHP $version is not supported on self-hosted runner" add_log "$cross" "PHP" "PHP $version is not supported on self-hosted runner"
exit 1 exit 1
else else
self_hosted_helper >/dev/null 2>&1 self_hosted_helper
add_env RUNNER_TOOL_CACHE /opt/hostedtoolcache add_env RUNNER_TOOL_CACHE /opt/hostedtoolcache
fi fi
fi fi
@@ -311,8 +252,8 @@ configure_php() {
[[ "$arch" = "arm64" || "$arch" = "aarch64" ]] && jit_ini="$ini_config_dir"/jit_aarch64.ini || jit_ini="$ini_config_dir"/jit.ini [[ "$arch" = "arm64" || "$arch" = "aarch64" ]] && jit_ini="$ini_config_dir"/jit_aarch64.ini || jit_ini="$ini_config_dir"/jit.ini
jit_config_files=("$jit_ini") jit_config_files=("$jit_ini")
[[ "$version" =~ $xdebug3_versions ]] && ini_config_files+=("$ini_config_dir"/xdebug.ini) [[ "$version" =~ $xdebug3_versions ]] && ini_config_files+=("$ini_config_dir"/xdebug.ini)
cat "${ini_config_files[@]}" | sudo tee -a "${ini_file[@]:?}" >/dev/null 2>&1 cat "${ini_config_files[@]}" | sudo tee -a "${ini_file[@]:?}"
[[ "$version" =~ $jit_versions ]] && cat "${jit_config_files[@]}" | sudo tee -a "${pecl_file:-${ini_file[@]}}" >/dev/null 2>&1 [[ "$version" =~ $jit_versions ]] && cat "${jit_config_files[@]}" | sudo tee -a "${pecl_file:-${ini_file[@]}}"
} }
# Function to get PHP version in semver format. # Function to get PHP version in semver format.
+51 -75
View File
@@ -20,8 +20,6 @@ Function Step-Log($message) {
Function Add-Log($mark, $subject, $message) { Function Add-Log($mark, $subject, $message) {
if ($mark -eq $tick) { if ($mark -eq $tick) {
printf "\033[32;1m%s \033[0m\033[34;1m%s \033[0m\033[90;1m%s \033[0m\n" $mark $subject $message printf "\033[32;1m%s \033[0m\033[34;1m%s \033[0m\033[90;1m%s \033[0m\n" $mark $subject $message
} elseif ($mark -eq "!") {
printf "\033[33;1m%s \033[0m\033[34;1m%s \033[0m\033[90;1m%s \033[0m\n" $mark $subject $message
} else { } else {
printf "\033[31;1m%s \033[0m\033[34;1m%s \033[0m\033[90;1m%s \033[0m\n" $mark $subject $message printf "\033[31;1m%s \033[0m\033[34;1m%s \033[0m\033[90;1m%s \033[0m\n" $mark $subject $message
if($env:fail_fast -eq 'true') { if($env:fail_fast -eq 'true') {
@@ -30,18 +28,6 @@ Function Add-Log($mark, $subject, $message) {
} }
} }
# Function to run sensitive code without tracing. Expand tokens inside the script block.
Function Invoke-WithoutTrace([scriptblock]$Script) {
Set-PSDebug -Off
$previous_trace = $setup_php_trace
$setup_php_trace = 0
try {
& $Script
} finally {
Set-PSDebug -Trace $previous_trace
}
}
# Function to set output on GitHub Actions. # Function to set output on GitHub Actions.
Function Set-Output() { Function Set-Output() {
param( param(
@@ -181,26 +167,6 @@ Function Get-File {
} }
} }
# Function to get an asset name from the PHP builder release manifest.
Function Get-PhpReleaseAsset {
param (
[ValidateSet('php', 'debug')]
[string]$Type,
[ValidateSet('stable', 'dev')]
[string]$Stability = 'stable'
)
if($null -eq $script:php_manifest) {
$script:php_manifest = Invoke-RestMethod "$php_builder/releases/download/php$version/manifest.json"
}
$thread_safety = if($ts) { 'ts' } else { 'nts' }
$asset = $script:php_manifest.$Stability.$Type.$thread_safety.$arch
if($null -eq $asset) {
throw "Asset not found in the php$version release manifest"
}
return $asset
}
# Function to make sure printf is in PATH. # Function to make sure printf is in PATH.
Function Add-Printf { Function Add-Printf {
if (-not(Test-Path "C:\Program Files\Git\usr\bin\printf.exe")) { if (-not(Test-Path "C:\Program Files\Git\usr\bin\printf.exe")) {
@@ -292,30 +258,51 @@ Function Add-PhpConfig {
Get-Content -Path $ini_files | Add-Content -Path $php_dir\php.ini Get-Content -Path $ini_files | Add-Content -Path $php_dir\php.ini
} }
# Function to install PHP directly from the GitHub releases cache. # Function to get PHP from GitHub releases cache
Function Install-PhpFromCache { Function Set-PhpCache {
$asset = Get-PhpReleaseAsset -Type php try {
$url = "$php_builder/releases/download/php$version/$asset" try {
Get-File -Url $url -FallbackUrl $php_windows/releases/archives/$asset -OutFile $php_dir\$asset $release = Invoke-RestMethod https://api.github.com/repos/shivammathur/php-builder-windows/releases/tags/php$version
Set-PhpDownloadCache -Path $php_dir CurrentUser $asset = $release.assets | ForEach-Object {
$php_manager = Get-Module PhpManager if($_.name -match "php-$version.[0-9]+$env:PHPTS-Win32-.*-$arch.zip") {
& $php_manager { return $_.name
param($url, $path) }
$php_version = Get-PhpVersionFromUrl -Url $url -ReleaseState Release } | Select-Object -Last 1
Install-PhpFromUrl -Url $url -Path $path -PhpVersion $php_version -InstallVCRedist $true if($null -eq $asset) {
} $url $php_dir throw "Asset not found"
$ini_path = "$php_dir\php.ini" }
Copy-Item -Path $php_dir\php.ini-production -Destination $ini_path -Force } catch {
Set-PhpIniKey -Key date.timezone -Value UTC -Path $ini_path $release = Get-File -Url $php_builder/releases/expanded_assets/php$version
Set-PhpIniKey -Key default_charset -Value UTF-8 -Path $ini_path $asset = $release.links.href | ForEach-Object {
Set-PhpIniKey -Key extension_dir -Value $ext_dir -Path $ini_path if($_ -match "php-$version.[0-9]+$env:PHPTS-Win32-.*-$arch.zip") {
return $_.split('/')[-1]
}
} | Select-Object -Last 1
}
Get-File -Url $php_builder/releases/download/php$version/$asset -OutFile $php_dir\$asset
Set-PhpDownloadCache -Path $php_dir CurrentUser
} catch { }
} }
# Function to add debug symbols to PHP. # Function to add debug symbols to PHP.
Function Add-DebugSymbols { Function Add-DebugSymbols {
$stability = if ($version -match $nightly_versions) { 'dev' } else { 'stable' } $dev = if ($version -match $nightly_versions) { '-dev' } else { '' }
$asset = Get-PhpReleaseAsset -Type debug -Stability $stability try {
Get-File -Url $php_builder/releases/download/php$version/$asset -FallbackUrl $php_windows/releases/archives/$asset -OutFile $php_dir\$asset $release = Invoke-RestMethod https://api.github.com/repos/shivammathur/php-builder-windows/releases/tags/php$version
$asset = $release.assets | ForEach-Object {
if($_.name -match "php-debug-pack-$version.[0-9]+$dev$env:PHPTS-Win32-.*-$arch.zip") {
return $_.name
}
} | Select-Object -Last 1
} catch {
$release = Get-File -Url $php_builder/releases/expanded_assets/php$version
$asset = $release.links.href | ForEach-Object {
if($_ -match "php-debug-pack-$version.[0-9]+$dev$env:PHPTS-Win32-.*-$arch.zip") {
return $_.split('/')[-1]
}
} | Select-Object -Last 1
}
Get-File -Url $php_builder/releases/download/php$version/$asset -OutFile $php_dir\$asset
Expand-Archive -Path $php_dir\$asset -DestinationPath $php_dir -Force Expand-Archive -Path $php_dir\$asset -DestinationPath $php_dir -Force
Get-ChildItem -Path $php_dir -Filter php_*.pdb | Move-Item -Destination $ext_dir Get-ChildItem -Path $php_dir -Filter php_*.pdb | Move-Item -Destination $ext_dir
} }
@@ -338,8 +325,6 @@ $ext_dir = "$php_dir\ext"
$bin_dir = $php_dir $bin_dir = $php_dir
$github = 'https://github.com' $github = 'https://github.com'
$php_builder = "$github/shivammathur/php-builder-windows" $php_builder = "$github/shivammathur/php-builder-windows"
$php_windows = 'https://downloads.php.net/~windows'
$php_manifest = $null
$current_profile = "$env:TEMP\setup-php.ps1" $current_profile = "$env:TEMP\setup-php.ps1"
$ProgressPreference = 'SilentlyContinue' $ProgressPreference = 'SilentlyContinue'
$jit_versions = '8.[0-9]' $jit_versions = '8.[0-9]'
@@ -347,12 +332,6 @@ $nightly_versions = '8.[6-9]'
$xdebug3_versions = "7.[2-4]|8.[0-9]" $xdebug3_versions = "7.[2-4]|8.[0-9]"
$enable_extensions = ('openssl', 'curl', 'mbstring') $enable_extensions = ('openssl', 'curl', 'mbstring')
$setup_php_trace = 0
if ($env:SETUP_PHP_TRACE -match '^[12]$') {
$setup_php_trace = [int]$env:SETUP_PHP_TRACE
Set-PSDebug -Trace $setup_php_trace
}
$arch = 'x64' $arch = 'x64'
if(-not([Environment]::Is64BitOperatingSystem) -or $version -lt '7.0') { if(-not([Environment]::Is64BitOperatingSystem) -or $version -lt '7.0') {
$arch = 'x86' $arch = 'x86'
@@ -381,7 +360,7 @@ if(-not($env:ImageOS) -and -not($env:ImageVersion)) {
$bin_dir = 'C:\tools\bin' $bin_dir = 'C:\tools\bin'
$php_dir = "$php_dir$version" $php_dir = "$php_dir$version"
$ext_dir = "$php_dir\ext" $ext_dir = "$php_dir\ext"
Get-CleanPSProfile >$null 2>&1 Get-CleanPSProfile
New-Item $bin_dir -Type Directory -Force > $null 2>&1 New-Item $bin_dir -Type Directory -Force > $null 2>&1
Add-Path -PathItem $bin_dir Add-Path -PathItem $bin_dir
if($version -lt 5.6) { if($version -lt 5.6) {
@@ -394,12 +373,12 @@ if(-not($env:ImageOS) -and -not($env:ImageVersion)) {
} }
New-Item $php_dir -Type Directory -Force > $null 2>&1 New-Item $php_dir -Type Directory -Force > $null 2>&1
Add-Path -PathItem $php_dir Add-Path -PathItem $php_dir
setx PHPROOT $php_dir >$null 2>&1 setx PHPROOT $php_dir
Add-Env -EnvName RUNNER_TOOL_CACHE -EnvValue $env:TEMP Add-Env -EnvName RUNNER_TOOL_CACHE -EnvValue $env:TEMP
} else { } else {
$current_profile = "$PSHOME\Profile.ps1" $current_profile = "$PSHOME\Profile.ps1"
if(-not(Test-Path -LiteralPath $current_profile)) { if(-not(Test-Path -LiteralPath $current_profile)) {
New-Item -Path $current_profile -ItemType "file" -Force >$null 2>&1 New-Item -Path $current_profile -ItemType "file" -Force
} }
Add-Path -PathItem $bin_dir -Force Add-Path -PathItem $bin_dir -Force
} }
@@ -408,9 +387,9 @@ $src = Join-Path -Path $PSScriptRoot -ChildPath \..
. $src\scripts\tools\add_tools.ps1 . $src\scripts\tools\add_tools.ps1
. $src\scripts\extensions\add_extensions.ps1 . $src\scripts\extensions\add_extensions.ps1
Add-Printf >$null 2>&1 Add-Printf
Step-Log "Setup PhpManager" Step-Log "Setup PhpManager"
Install-PSPackage PhpManager PhpManager\PhpManager "$github/mlocati/powershell-phpmanager/releases/latest/download/PhpManager.zip" Get-Php >$null 2>&1 Install-PSPackage PhpManager PhpManager\PhpManager "$github/mlocati/powershell-phpmanager/releases/latest/download/PhpManager.zip" Get-Php
Add-Log $tick "PhpManager" "Installed" Add-Log $tick "PhpManager" "Installed"
Step-Log "Setup PHP" Step-Log "Setup PHP"
@@ -439,23 +418,20 @@ if($version -eq 'pre') {
} }
if ($null -eq $installed -or -not("$($installed.Version).".StartsWith(($version -replace '^(\d+(\.\d+)*).*', '$1.'))) -or $ts -ne $installed.ThreadSafe) { if ($null -eq $installed -or -not("$($installed.Version).".StartsWith(($version -replace '^(\d+(\.\d+)*).*', '$1.'))) -or $ts -ne $installed.ThreadSafe) {
if ($version -lt '7.0' -and ($null -eq (Get-Module -ListAvailable -Name VcRedist))) { if ($version -lt '7.0' -and ($null -eq (Get-Module -ListAvailable -Name VcRedist))) {
Install-PSPackage VcRedist VcRedist-4.1.527\VcRedist\VcRedist "$github/aaronparker/VcRedist/archive/v4.1.527.zip" Get-VcList >$null 2>&1 Install-PSPackage VcRedist VcRedist-main\VcRedist\VcRedist "$github/aaronparker/VcRedist/archive/main.zip" Get-VcList
} }
try { try {
if ($version -match $nightly_versions) { if ($version -match $nightly_versions) {
$extra_version = Install-PhpNightly $extra_version = Install-PhpNightly
} else { } else {
try { Set-PhpCache
Install-PhpFromCache > $null 2>&1 Install-Php -Version $version -Architecture $arch -ThreadSafe $ts -InstallVC -Path $php_dir -TimeZone UTC -InitialPhpIni production -Force > $null 2>&1
} catch {
Install-Php -Version $version -Architecture $arch -ThreadSafe $ts -InstallVC -Path $php_dir -TimeZone UTC -InitialPhpIni production -Force > $null 2>&1
}
} }
Add-PhpConfig Add-PhpConfig
} catch { } } catch { }
} else { } else {
if($env:update -eq 'true') { if($env:update -eq 'true') {
Update-Php $php_dir >$null 2>&1 Update-Php $php_dir
$status = "Updated to" $status = "Updated to"
} else { } else {
$status = "Found" $status = "Found"
@@ -473,7 +449,7 @@ if($installed.MajorMinorVersion -ne $version) {
Write-Error "Could not setup PHP $version" -ErrorAction Stop Write-Error "Could not setup PHP $version" -ErrorAction Stop
} }
if($version -lt "5.5") { if($version -lt "5.5") {
('libeay32.dll', 'ssleay32.dll') | ForEach-Object -Parallel { Invoke-WebRequest -Uri "$using:php_builder/releases/download/openssl-1.0.2u/$_" -OutFile $using:php_dir\$_ >$null 2>&1 } ('libeay32.dll', 'ssleay32.dll') | ForEach-Object -Parallel { Invoke-WebRequest -Uri "$using:php_builder/releases/download/openssl-1.0.2u/$_" -OutFile $using:php_dir\$_ }
} elseif($version -lt "8.5") { } elseif($version -lt "8.5") {
$enable_extensions += ('opcache') $enable_extensions += ('opcache')
} }
+43 -153
View File
@@ -1,12 +1,9 @@
import {fileURLToPath} from 'url';
import path from 'path'; import path from 'path';
import fs from 'fs'; import fs from 'fs';
import * as cv from 'compare-versions'; import * as cv from 'compare-versions';
import * as fetch from './fetch.js'; import * as fetch from './fetch';
import * as packagist from './packagist.js'; import * as packagist from './packagist';
import * as utils from './utils.js'; import * as utils from './utils';
const dirname = path.dirname(fileURLToPath(import.meta.url));
/** /**
* Valid function names for custom tool handlers * Valid function names for custom tool handlers
@@ -30,7 +27,6 @@ type ToolFunction =
export interface ToolData { export interface ToolData {
tool: string; tool: string;
version: string; version: string;
checksum?: string;
os: string; os: string;
php_version: string; php_version: string;
github: string; github: string;
@@ -51,7 +47,6 @@ export interface ToolData {
url: string; url: string;
uri?: string; uri?: string;
error?: string; error?: string;
fallback?: ToolFallback;
} }
/** /**
@@ -76,70 +71,6 @@ interface ToolConfig {
version_parameter?: string; version_parameter?: string;
version_prefix?: string; version_prefix?: string;
packagist?: string; packagist?: string;
fallback?: ToolFallback;
}
type ToolFallback = Pick<
ToolConfig,
| 'repository'
| 'domain'
| 'extension'
| 'fetch_latest'
| 'version_parameter'
| 'version_prefix'
> & {type: 'phar'};
/**
* Regex to match a checksum suffix in a tool release - tool:version@sha256:<hash>
*/
const checksum_suffix_regex = /@([a-z][a-z0-9-]*):([^@]*)$/i;
const checksum_like_suffix_regex = /@sha[^@]*$/i;
/**
* Function to parse the checksum suffix in the tool release
*
* @param release
*/
export function extractChecksum(release: string): {
release: string;
checksum?: string;
error?: string;
} {
const matches = release.match(checksum_suffix_regex);
if (!matches) {
const checksum_like_matches = release.match(checksum_like_suffix_regex);
if (checksum_like_matches) {
return {
release: release.slice(0, -checksum_like_matches[0].length),
error:
'Invalid checksum syntax, expected @sha256:<hash> or @sha512:<hash>'
};
}
return {release};
}
release = release.slice(0, -matches[0].length);
const algo = matches[1].toLowerCase();
if (!['sha256', 'sha512'].includes(algo)) {
return {
release,
error: `Unsupported checksum algorithm ${algo}, expected sha256 or sha512`
};
}
const hash = matches[2].toLowerCase();
const hash_length = algo === 'sha256' ? 64 : 128;
if (!new RegExp(`^[a-f0-9]{${hash_length}}$`).test(hash)) {
return {
release,
error: `Invalid ${algo} checksum, expected ${hash_length} hexadecimal characters`
};
}
if (!/^[^:]+:v?\d+\.\d+\.\d+(?:-[\w.-]+)?(?:\+[\w.-]+)?$/.test(release)) {
return {
release,
error: 'Checksum pinning requires a full version, for example tool:1.2.3'
};
}
return {release, checksum: `${algo}:${hash}`};
} }
/** /**
@@ -156,13 +87,21 @@ interface GitHubRef {
}; };
} }
/**
* Deployer manifest entry
*/
interface DeployerManifestEntry {
version: string;
url: string;
}
export function skipGitHubAuthForComposerVersion(version: string): boolean { export function skipGitHubAuthForComposerVersion(version: string): boolean {
if (!/^\d+\.\d+\.\d+(?:-[\w-]+)?$/.test(version)) { if (!/^\d+\.\d+\.\d+(?:-[\w-]+)?$/.test(version)) {
return false; return false;
} }
return fs return fs
.readFileSync( .readFileSync(
path.join(dirname, '../src/configs/composer-gh-auth-no-op'), path.join(__dirname, '../src/configs/composer-gh-auth-no-op'),
'utf8' 'utf8'
) )
.trim() .trim()
@@ -321,18 +260,9 @@ export async function filterList(tools_list: string[]): Promise<string[]> {
const regex_any = /^composer($|:.*)/; const regex_any = /^composer($|:.*)/;
const regex_valid = const regex_valid =
/^composer:?($|preview$|snapshot$|v?\d+(\.\d+)?$|v?\d+\.\d+\.\d+[\w-]*$)/; /^composer:?($|preview$|snapshot$|v?\d+(\.\d+)?$|v?\d+\.\d+\.\d+[\w-]*$)/;
const matches: string[] = tools_list.filter(tool => { const matches: string[] = tools_list.filter(tool => regex_valid.test(tool));
const parsed = extractChecksum(tool);
return (
regex_valid.test(parsed.release) ||
(regex_any.test(parsed.release) &&
(parsed.checksum !== undefined || parsed.error !== undefined))
);
});
let composer = 'composer'; let composer = 'composer';
tools_list = tools_list.filter( tools_list = tools_list.filter(tool => !regex_any.test(tool));
tool => !regex_any.test(extractChecksum(tool).release)
);
switch (true) { switch (true) {
case matches[0] == undefined: case matches[0] == undefined:
break; break;
@@ -405,8 +335,7 @@ export async function getPharUrl(data: ToolData): Promise<string> {
export async function addArchive(data: ToolData): Promise<string> { export async function addArchive(data: ToolData): Promise<string> {
return ( return (
(await utils.getCommand(data.os, 'tool')) + (await utils.getCommand(data.os, 'tool')) +
(await utils.joins(data.url, data.tool, data.version_parameter)) + (await utils.joins(data.url, data.tool, data.version_parameter))
(data.checksum ? ' ' + data.checksum : '')
); );
} }
@@ -421,23 +350,7 @@ export async function addPackage(data: ToolData): Promise<string> {
const args = [parts[1], data.release, parts[0] + '/', data.scope] const args = [parts[1], data.release, parts[0] + '/', data.scope]
.map(a => utils.safeArg(a, data.os)) .map(a => utils.safeArg(a, data.os))
.join(' '); .join(' ');
if (!data.fallback) return command + args; return command + args;
const fallback = await getData(
data.release.replace(/\.\*$/, ''),
data.php_version,
data.os,
data.fallback
);
// A failed version lookup must not prevent a successful Composer install.
if (fallback.error) return command + args;
return (
command +
args +
' ' +
utils.safeArg(fallback.url, data.os) +
' ' +
(fallback.version_parameter || '""')
);
} }
/** /**
@@ -514,7 +427,7 @@ export async function addComposer(data: ToolData): Promise<string> {
case /^1$/.test(channel): case /^1$/.test(channel):
source_url = channel_source_url; source_url = channel_source_url;
break; break;
case /^\d+\.\d+\.\d+(?:-[\w.-]+)?(?:\+[\w.-]+)?$/.test(data.version): case /^\d+\.\d+\.\d+(?:-[\w-]+)?$/.test(data.version):
if (skipGitHubAuthForComposerVersion(data.version)) { if (skipGitHubAuthForComposerVersion(data.version)) {
cleanComposerAuthJson(); cleanComposerAuthJson();
skip_composer_github_auth = ' true'; skip_composer_github_auth = ' true';
@@ -537,17 +450,29 @@ export async function addComposer(data: ToolData): Promise<string> {
* @param data * @param data
*/ */
export async function addDeployer(data: ToolData): Promise<string> { export async function addDeployer(data: ToolData): Promise<string> {
const github_url = await getUrl({ if (data.version === 'latest') {
...data, data.url = data.domain + '/deployer.phar';
domain: data.github, } else {
prefix: 'releases', const manifest = await fetch.fetch('https://deployer.org/manifest.json');
verb: 'download' const version_data: Record<string, DeployerManifestEntry> = JSON.parse(
}); manifest.data
const source_url = );
data.version === 'latest' const version_key: string | undefined = Object.keys(version_data).find(
? `${data.domain}/deployer.phar` (key: string) => {
: `${data.domain}/releases/v${data.version}/deployer.phar`; return version_data[key].version === data.version;
data.url = `${github_url},${source_url}`; }
);
if (version_key) {
data.url = version_data[version_key].url;
} else {
return await utils.addLog(
'$cross',
'deployer',
'Version missing in deployer manifest',
data.os
);
}
}
return await addArchive(data); return await addArchive(data);
} }
@@ -681,15 +606,12 @@ export async function addWPCLI(data: ToolData): Promise<string> {
export async function getData( export async function getData(
release: string, release: string,
php_version: string, php_version: string,
os: string, os: string
overrides: ToolConfig = {}
): Promise<ToolData> { ): Promise<ToolData> {
const json_file_path = path.join(dirname, '../src/configs/tools.json'); const json_file_path = path.join(__dirname, '../src/configs/tools.json');
const json_file: string = fs.readFileSync(json_file_path, 'utf8'); const json_file: string = fs.readFileSync(json_file_path, 'utf8');
const json_objects: Record<string, ToolConfig> = JSON.parse(json_file); const json_objects: Record<string, ToolConfig> = JSON.parse(json_file);
release = release.replace(/\s+/g, ''); release = release.replace(/\s+/g, '');
const checksum_data = extractChecksum(release);
release = checksum_data.release;
const parts: string[] = release.split(':'); const parts: string[] = release.split(':');
const tool = parts[0]; const tool = parts[0];
const version = parts[1]; const version = parts[1];
@@ -714,7 +636,6 @@ export async function getData(
config = {tool}; config = {tool};
} }
} }
config = {...config, ...overrides};
const github = 'https://github.com'; const github = 'https://github.com';
const domain = config.domain ?? github; const domain = config.domain ?? github;
const data: ToolData = { const data: ToolData = {
@@ -740,13 +661,9 @@ export async function getData(
packagist: config.packagist ?? config.repository ?? '', packagist: config.packagist ?? config.repository ?? '',
type: config.type, type: config.type,
function: config.function, function: config.function,
alias: config.alias, alias: config.alias
fallback: config.fallback
}; };
data.checksum = checksum_data.checksum;
data.error = checksum_data.error;
data.release = await getRelease(release, data); data.release = await getRelease(release, data);
if (data.error !== undefined) return data;
data.version = version data.version = version
? await getVersion(version, data) ? await getVersion(version, data)
: await getLatestVersion(data); : await getLatestVersion(data);
@@ -771,25 +688,6 @@ export const functionRecord: Record<
wp_cli: addWPCLI wp_cli: addWPCLI
}; };
/**
* Function to check if a tool supports checksum verification
*
* Only tools downloaded as archives via add_tool support it, so composer
* packages and tools set up using custom package scripts do not.
*
* @param data
*/
export async function supportsChecksum(data: ToolData): Promise<boolean> {
switch (data.type) {
case 'phar':
return true;
case 'custom-function':
return !['pecl', 'dev_tools'].includes(data.function ?? '');
default:
return false;
}
}
/** /**
* Setup tools * Setup tools
* *
@@ -816,14 +714,6 @@ export async function addTools(
case data.error !== undefined: case data.error !== undefined:
script += await utils.addLog('$cross', data.tool, data.error, data.os); script += await utils.addLog('$cross', data.tool, data.error, data.os);
break; break;
case data.checksum !== undefined && !(await supportsChecksum(data)):
script += await utils.addLog(
'$cross',
data.tool,
'Checksum verification is not supported for ' + data.tool,
data.os
);
break;
case 'phar' === data.type: case 'phar' === data.type:
script += await addArchive(data); script += await addArchive(data);
break; break;
+20 -61
View File
@@ -1,10 +1,7 @@
import {fileURLToPath} from 'url';
import fs from 'fs'; import fs from 'fs';
import * as path from 'path'; import * as path from 'path';
import * as core from './core.js'; import * as core from './core';
import * as fetch from './fetch.js'; import * as fetch from './fetch';
const dirname = path.dirname(fileURLToPath(import.meta.url));
/** /**
* Function to read environment variable and return a string value. * Function to read environment variable and return a string value.
@@ -74,13 +71,15 @@ export async function parseVersion(version: string): Promise<string> {
for (const manifestURL of await getManifestURLS()) { for (const manifestURL of await getManifestURLS()) {
const fetchResult = await fetch.fetch(manifestURL); const fetchResult = await fetch.fetch(manifestURL);
if (fetchResult['data'] ?? false) { if (fetchResult['data'] ?? false) {
const resolved: unknown = JSON.parse(fetchResult['data'])[version]; const resolved: string | undefined = JSON.parse(fetchResult['data'])[
version
];
if (resolved === undefined) { if (resolved === undefined) {
throw new Error(`Invalid PHP version: ${version.slice(0, 20)}`); throw new Error(`Invalid PHP version: ${version.slice(0, 20)}`);
} }
if (typeof resolved !== 'string' || !/^\d+\.\d+$/.test(resolved)) { if (!/^\d+\.\d+$/.test(resolved)) {
throw new Error( throw new Error(
`Invalid PHP version in manifest: ${typeof resolved === 'string' ? resolved.slice(0, 10) : typeof resolved}` `Invalid PHP version in manifest: ${resolved.slice(0, 10)}`
); );
} }
return resolved; return resolved;
@@ -91,9 +90,12 @@ export async function parseVersion(version: string): Promise<string> {
if (!/^\d+(\.\d+){0,2}$/.test(version)) { if (!/^\d+(\.\d+){0,2}$/.test(version)) {
throw new Error(`Invalid PHP version: ${version.slice(0, 20)}`); throw new Error(`Invalid PHP version: ${version.slice(0, 20)}`);
} }
return version.includes('.') switch (true) {
? version.split('.').slice(0, 2).join('.') case version.length > 1:
: version + '.0'; return version.slice(0, 3);
default:
return version + '.0';
}
} }
} }
@@ -321,56 +323,15 @@ export async function getExtensionPrefix(extension: string): Promise<string> {
export async function suppressOutput(os: string): Promise<string> { export async function suppressOutput(os: string): Promise<string> {
switch (os) { switch (os) {
case 'win32': case 'win32':
return ' >$null 2>&1'; return ' ';
case 'linux': case 'linux':
case 'darwin': case 'darwin':
return ' >/dev/null 2>&1'; return ' ';
default: default:
return await log('Platform ' + os + ' is not supported', os, 'error'); return await log('Platform ' + os + ' is not supported', os, 'error');
} }
} }
/**
* Prepare verbose runtime scripts without changing the original sources.
*/
export async function addVerbose(
run_path: string,
os: string
): Promise<string> {
const verbose = await readEnv('verbose');
process.env['SETUP_PHP_TRACE'] = /^v{2,3}$/.test(verbose)
? String(verbose.length - 1)
: '0';
if (!/^(true|v{1,3})$/.test(verbose) && process.env['RUNNER_DEBUG'] !== '1') {
return run_path;
}
const extension = await scriptExtension(os);
const src = path.dirname(path.dirname(run_path));
const dest = fs.mkdtempSync(src + '-verbose-');
await fs.promises.cp(src, dest, {recursive: true, dereference: true});
const scripts = path.join(dest, 'scripts');
const verbose_run = path.join(scripts, path.basename(run_path));
const pipe = />[ \t]*(?:\/dev\/null|\$null)[ \t]+2>&1/g;
for (const file of fs.readdirSync(scripts, {
recursive: true,
encoding: 'utf8'
})) {
if (!file.endsWith(extension)) continue;
const filename = path.join(scripts, file);
const original = fs.readFileSync(filename, 'utf8');
// PowerShell's success stream also carries function return values.
let script = original.replace(
pipe,
os === 'win32' ? '2>&1 | Out-Host' : ''
);
if (filename === verbose_run) {
script = script.replaceAll(src, dest);
}
if (script !== original) fs.writeFileSync(filename, script);
}
return verbose_run;
}
/** /**
* Function to get script to log unsupported extensions. * Function to get script to log unsupported extensions.
* *
@@ -480,7 +441,7 @@ export async function customPackage(
const pkg_name: string = pkg.replace(/\d+|(pdo|pecl)[_-]|[_-]db2/, ''); const pkg_name: string = pkg.replace(/\d+|(pdo|pecl)[_-]|[_-]db2/, '');
const script_extension: string = await scriptExtension(os); const script_extension: string = await scriptExtension(os);
const script: string = path.join( const script: string = path.join(
dirname, __dirname,
'../src/scripts/' + type + '/' + pkg_name + script_extension '../src/scripts/' + type + '/' + pkg_name + script_extension
); );
const command: string = await getCommand(os, pkg_name); const command: string = await getCommand(os, pkg_name);
@@ -512,10 +473,10 @@ export async function parseExtensionSource(
const VERSION_INPUT_REGEX = const VERSION_INPUT_REGEX =
/^(latest|lowest|highest|nightly|master|pre|pre-installed|\d+\.x|\d+(\.\d+){0,2})$/; /^(latest|lowest|highest|nightly|master|pre|pre-installed|\d+\.x|\d+(\.\d+){0,2})$/;
function validatePHPVersionInput(version: unknown, source: string): string { function validatePHPVersionInput(version: string, source: string): string {
if (typeof version !== 'string' || !VERSION_INPUT_REGEX.test(version)) { if (!VERSION_INPUT_REGEX.test(version)) {
throw new Error( throw new Error(
`Invalid PHP version in ${source}: ${typeof version === 'string' ? version.slice(0, 20) : typeof version}` `Invalid PHP version in ${source}: ${version.slice(0, 20)}`
); );
} }
return version; return version;
@@ -533,9 +494,7 @@ export async function readPHPVersion(): Promise<string> {
(await getInput('php-version-file', false)) || '.php-version'; (await getInput('php-version-file', false)) || '.php-version';
if (fs.existsSync(versionFile)) { if (fs.existsSync(versionFile)) {
const contents: string = fs.readFileSync(versionFile, 'utf8'); const contents: string = fs.readFileSync(versionFile, 'utf8');
const match = contents.match( const match = contents.match(/^(?:php\s)?(\d+\.\d+\.\d+)$/m);
/^[ \t]*(?:php[ \t]+)?([^\s#]+)[ \t]*(?:#.*)?$/m
);
return validatePHPVersionInput( return validatePHPVersionInput(
match ? match[1] : contents.trim(), match ? match[1] : contents.trim(),
versionFile versionFile
+5 -8
View File
@@ -3,20 +3,17 @@
"declaration": true, "declaration": true,
"esModuleInterop": true, "esModuleInterop": true,
"lib": [ "lib": [
"ES2025" "ES2024"
], ],
"module": "NodeNext", "module": "commonjs",
"moduleResolution": "NodeNext", "moduleResolution": "node",
"noImplicitAny": true, "noImplicitAny": true,
"outDir": "./lib", "outDir": "./lib",
"removeComments": true, "removeComments": true,
"rootDir": "./src", "rootDir": "./src",
"sourceMap": true, "sourceMap": true,
"strict": true, "strict": true,
"target": "ES2025", "target": "ES2024"
"types": [
"node"
]
}, },
"exclude": ["__tests__", "lib", "node_modules"] "exclude": ["__tests__", "lib", "node_modules"]
} }
-14
View File
@@ -1,14 +0,0 @@
{
"extends": "./tsconfig.json",
"compilerOptions": {
"isolatedModules": true,
"noEmit": true,
"rootDir": ".",
"types": [
"jest",
"node"
]
},
"exclude": ["lib", "node_modules"],
"include": ["__tests__/**/*.ts", "src/**/*.ts"]
}