Compare commits

..

22 Commits

Author SHA1 Message Date
Shivam Mathur d76a76348c Limit Windows extension recovery overhead to DLL replacements 2026-09-19 19:47:44 +05:30
dependabot[bot] 84a5f1c061 Bump the github-actions group with 3 updates (#1122)
Bumps the github-actions group with 3 updates: [github/codeql-action/init](https://github.com/github/codeql-action), [github/codeql-action/autobuild](https://github.com/github/codeql-action) and [github/codeql-action/analyze](https://github.com/github/codeql-action).


Updates `github/codeql-action/init` from 4.37.9 to 4.38.0
- [Release notes](https://github.com/github/codeql-action/releases)
- [Changelog](https://github.com/github/codeql-action/blob/main/CHANGELOG.md)
- [Commits](https://github.com/github/codeql-action/compare/cdf488f595d80d6e07e03d4674febd5ab45fa938...b96794f015dfd88f77b49b1c93e0fa7110f94c63)

Updates `github/codeql-action/autobuild` from 4.37.9 to 4.38.0
- [Release notes](https://github.com/github/codeql-action/releases)
- [Changelog](https://github.com/github/codeql-action/blob/main/CHANGELOG.md)
- [Commits](https://github.com/github/codeql-action/compare/cdf488f595d80d6e07e03d4674febd5ab45fa938...b96794f015dfd88f77b49b1c93e0fa7110f94c63)

Updates `github/codeql-action/analyze` from 4.37.9 to 4.38.0
- [Release notes](https://github.com/github/codeql-action/releases)
- [Changelog](https://github.com/github/codeql-action/blob/main/CHANGELOG.md)
- [Commits](https://github.com/github/codeql-action/compare/cdf488f595d80d6e07e03d4674febd5ab45fa938...b96794f015dfd88f77b49b1c93e0fa7110f94c63)

---
updated-dependencies:
- dependency-name: github/codeql-action/init
  dependency-version: 4.38.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: github-actions
- dependency-name: github/codeql-action/autobuild
  dependency-version: 4.38.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: github-actions
- dependency-name: github/codeql-action/analyze
  dependency-version: 4.38.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: github-actions
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-09-19 19:16:55 +05:30
Shivam Mathur 72c642301a Preserve active Windows extensions before probing cached DLLs 2026-09-18 12:01:55 +05:30
Shivam Mathur ed2b57d93d Preserve startup error settings during Windows extension changes 2026-09-18 12:00:30 +05:30
Shivam Mathur 75fa893d48 Improve parsing .php-version and tests 2026-09-17 20:53:52 +05:30
Sviatoslav Abakumov 0bbee91078 Support all valid PHP version file values (#1121)
* Support all valid PHP version file values

Allow version files to use partial versions and aliases accepted by the
php-version input while preserving support for both plain .php-version
files and asdf-style php entries.

* Regenerate bundled action

---------

Co-authored-by: Shivam Mathur <shivam_jpr@hotmail.com>
2026-09-17 20:17:54 +05:30
Shivam Mathur e3f88f3ca7 Enable fileinfo for Laravel Cloud CLI 2026-09-16 18:18:36 +05:30
Shivam Mathur 870fe79ecc Verify cached Windows extensions load before reusing them 2026-09-16 18:18:09 +05:30
Shivam Mathur 25618cc48e Cache replaced Windows extensions by their installed version 2026-09-16 11:25:07 +05:30
Shivam Mathur 5eaed2e30b Validate restored versioned extensions before reporting success 2026-09-16 09:16:04 +05:30
Shivam Mathur 85dc78fbb0 Preserve Composer checksum pins for full version suffixes 2026-09-16 05:37:39 +05:30
Shivam Mathur 83c9e52793 docs: deprecate macOS 14 arm64 runners in support note 2026-09-16 04:14:38 +05:30
Shivam Mathur 9af3b52286 Document deprecated Intel macOS runner support 2026-09-12 00:33:02 +05:30
Shivam Mathur 0e80ac5270 Restore explicit TypeScript checking in CI 2026-09-12 00:33:02 +05:30
Shivam Mathur ea331059db Try the expected extension version before unpinned PECL fallback 2026-09-12 00:33:02 +05:30
Shivam Mathur 3ad6232c89 Preserve PowerShell return values in verbose mode 2026-09-12 00:32:55 +05:30
Shivam Mathur 2ec764e0ab Compare complete Windows extension versions 2026-09-12 00:32:42 +05:30
Shivam Mathur e6ee35895b Require full tool versions for checksum pinning 2026-09-11 20:49:43 +05:30
Shivam Mathur 0c6410c670 Fix Homebrew timeout cleanup and retry propagation 2026-09-11 14:20:07 +05:30
Shivam Mathur 250924180e Add configurable verbosity and guarded shell tracing 2026-09-10 01:29:39 +05:30
Shivam Mathur 63b8b6feda Stop Intel macOS installs when the package cache fails 2026-09-09 09:01:18 +05:30
Shivam Mathur de306754b1 Support php-darwin cache on Intel macOS 2026-09-08 18:05:05 +05:30
21 changed files with 882 additions and 125 deletions
+3 -3
View File
@@ -26,13 +26,13 @@ jobs:
persist-credentials: false persist-credentials: false
- name: Initialize CodeQL - name: Initialize CodeQL
uses: github/codeql-action/init@cdf488f595d80d6e07e03d4674febd5ab45fa938 # v4 uses: github/codeql-action/init@b96794f015dfd88f77b49b1c93e0fa7110f94c63 # 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@cdf488f595d80d6e07e03d4674febd5ab45fa938 # v4 uses: github/codeql-action/autobuild@b96794f015dfd88f77b49b1c93e0fa7110f94c63 # v4
- name: Perform CodeQL Analysis - name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@cdf488f595d80d6e07e03d4674febd5ab45fa938 # v4 uses: github/codeql-action/analyze@b96794f015dfd88f77b49b1c93e0fa7110f94c63 # v4
+3
View File
@@ -52,6 +52,9 @@ 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
+23 -5
View File
@@ -81,6 +81,11 @@ Both `GitHub-hosted` and `self-hosted` runners are supported by `setup-php` on t
| macOS Tahoe 26.x | arm64 | `macos-26` | - | | macOS Tahoe 26.x | arm64 | `macos-26` | - |
| macOS Sequoia 15.x | arm64 | `macos-latest` or `macos-15` | - | | macOS Sequoia 15.x | arm64 | `macos-latest` or `macos-15` | - |
| macOS Sonoma 14.x | arm64 | `macos-14` | - | | macOS Sonoma 14.x | arm64 | `macos-14` | - |
| 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
@@ -272,7 +277,7 @@ These tools can be set up globally using the `tools` input. It accepts a string
tools: composer:2.9.8@sha256:59b2c50e10cafa0d8efc19ede9a326d782f096c674a26baf98cf042ce23de890 tools: composer:2.9.8@sha256:59b2c50e10cafa0d8efc19ede9a326d782f096c674a26baf98cf042ce23de890
``` ```
Checksum verification is supported for tools which are downloaded as phar archives. It is not supported for tools set up using `composer` packages or custom package scripts, specifying a checksum for these tools will result in an error. For checksum pinning to be effective, pin the tool to an exact version, as mutable versions like `latest` or `major.minor` can resolve to a different release with a different checksum. 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.
@@ -527,6 +532,13 @@ 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
@@ -655,13 +667,19 @@ jobs:
> Debug your workflow > Debug your workflow
To debug any issues, you can use the `verbose` tag instead of `v2`. - Set the `verbose` environment variable to `true` or `v` to show command output.
- 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@verbose uses: shivammathur/setup-php@v2
with: with:
php-version: '8.5' php-version: '8.5'
env:
verbose: true
``` ```
### Multi-Arch Setup ### Multi-Arch Setup
@@ -995,7 +1013,7 @@ Examples of using `setup-php` with various PHP frameworks and packages.
- 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 is 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 `verbose` tag can be used temporarily. It outputs all the logs and is also synced with the latest releases. - For debugging any issues, use the [`verbose` environment variable](#verbose-setup).
- 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 the 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.
@@ -1058,7 +1076,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 sharing 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.
+73 -15
View File
@@ -222,20 +222,21 @@ describe('Tools tests', () => {
}); });
it.each` it.each`
release | expected_release | checksum | error release | expected_release | checksum | error
${'tool:1.2.3'} | ${'tool:1.2.3'} | ${undefined} | ${undefined} ${'tool:1.2.3'} | ${'tool:1.2.3'} | ${undefined} | ${undefined}
${'tool:1.2.3@sha256:' + 'a'.repeat(64)} | ${'tool:1.2.3'} | ${'sha256:' + 'a'.repeat(64)} | ${undefined} ${'tool:1.2.3@sha256:' + 'a'.repeat(64)} | ${'tool:1.2.3'} | ${'sha256:' + 'a'.repeat(64)} | ${undefined}
${'tool:1.2.3@sha256:' + 'A'.repeat(64)} | ${'tool:1.2.3'} | ${'sha256:' + 'a'.repeat(64)} | ${undefined} ${'tool:1.2.3@sha256:' + 'A'.repeat(64)} | ${'tool:1.2.3'} | ${'sha256:' + 'a'.repeat(64)} | ${undefined}
${'tool:1.2.3@SHA256:' + 'a'.repeat(64)} | ${'tool:1.2.3'} | ${'sha256:' + 'a'.repeat(64)} | ${undefined} ${'tool:1.2.3@SHA256:' + 'a'.repeat(64)} | ${'tool:1.2.3'} | ${'sha256:' + 'a'.repeat(64)} | ${undefined}
${'tool:1.2.3@sha512:' + 'b'.repeat(128)} | ${'tool:1.2.3'} | ${'sha512:' + 'b'.repeat(128)} | ${undefined} ${'tool:1.2.3@sha512:' + 'b'.repeat(128)} | ${'tool:1.2.3'} | ${'sha512:' + 'b'.repeat(128)} | ${undefined}
${'composer:2.9.8@sha256:' + 'c'.repeat(64)} | ${'composer:2.9.8'} | ${'sha256:' + 'c'.repeat(64)} | ${undefined} ${'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}
${'tool:1.2.3@sha256:xyz'} | ${'tool:1.2.3'} | ${undefined} | ${'Invalid sha256 checksum, expected 64 hexadecimal characters'} ${'composer:2.9.8@sha256:' + 'c'.repeat(64)} | ${'composer:2.9.8'} | ${'sha256:' + 'c'.repeat(64)} | ${undefined}
${'tool:1.2.3@sha256:' + 'a'.repeat(63)} | ${'tool:1.2.3'} | ${undefined} | ${'Invalid sha256 checksum, expected 64 hexadecimal characters'} ${'tool:1.2.3@sha256:xyz'} | ${'tool:1.2.3'} | ${undefined} | ${'Invalid sha256 checksum, expected 64 hexadecimal characters'}
${'tool:1.2.3@sha512:' + 'b'.repeat(64)} | ${'tool:1.2.3'} | ${undefined} | ${'Invalid sha512 checksum, expected 128 hexadecimal characters'} ${'tool:1.2.3@sha256:' + 'a'.repeat(63)} | ${'tool:1.2.3'} | ${undefined} | ${'Invalid sha256 checksum, expected 64 hexadecimal characters'}
${'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@sha512:' + 'b'.repeat(64)} | ${'tool:1.2.3'} | ${undefined} | ${'Invalid sha512 checksum, expected 128 hexadecimal characters'}
${'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@sha384:' + 'b'.repeat(96)} | ${'tool:1.2.3'} | ${undefined} | ${'Unsupported checksum algorithm sha384, 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.2.3@md5:' + 'b'.repeat(32)} | ${'tool:1.2.3'} | ${undefined} | ${'Unsupported checksum algorithm md5, expected sha256 or sha512'}
${'tool:1.0@dev'} | ${'tool:1.0@dev'} | ${undefined} | ${undefined} ${'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', 'checking extractChecksum: $release',
({release, expected_release, checksum, error}) => { ({release, expected_release, checksum, error}) => {
@@ -836,7 +837,7 @@ describe('Tools tests', () => {
${'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)} ${'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)}
${'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)} ${'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"'} ${'phinx:1.2.3@sha256:' + 'a'.repeat(64)} | ${'linux'} | ${'add_log "$cross" "phinx" "Checksum verification is not supported for phinx"'}
${'pecl@sha256:' + 'a'.repeat(64)} | ${'linux'} | ${'add_log "$cross" "pecl" "Checksum verification is not supported for pecl"'} ${'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"'} ${'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@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@sha384:' + 'b'.repeat(96)} | ${'linux'} | ${'add_log "$cross" "composer" "Unsupported checksum algorithm sha384, expected sha256 or sha512"'}
@@ -849,6 +850,63 @@ describe('Tools tests', () => {
} }
); );
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` it.each`
type | tool_function | supported type | tool_function | supported
${'phar'} | ${undefined} | ${true} ${'phar'} | ${undefined} | ${true}
+495 -9
View File
@@ -1,4 +1,6 @@
import fs from 'fs'; import fs from 'fs';
import os from 'os';
import {spawnSync} from 'child_process';
import * as path from 'path'; import * as path from 'path';
import * as utils from '../src/utils'; import * as utils from '../src/utils';
import * as fetchModule from '../src/fetch'; import * as fetchModule from '../src/fetch';
@@ -54,12 +56,17 @@ 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(
fetchSpy.mockResolvedValue({data: '{ "latest": "8.1.0" }'}); 'Invalid PHP version:'
await expect(utils.parseVersion('latest')).rejects.toThrow(
'Invalid PHP version in manifest:'
); );
for (const latest of ['8.1.0', 'pre', 8.4, ['8.4']]) {
fetchSpy.mockResolvedValue({data: JSON.stringify({latest})});
await expect(utils.parseVersion('latest')).rejects.toThrow(
'Invalid PHP version in manifest:'
);
}
fetchSpy.mockReset(); fetchSpy.mockReset();
fetchSpy.mockResolvedValueOnce({}).mockResolvedValueOnce({}); fetchSpy.mockResolvedValueOnce({}).mockResolvedValueOnce({});
await expect(utils.parseVersion('latest')).rejects.toThrow( await expect(utils.parseVersion('latest')).rejects.toThrow(
@@ -332,8 +339,30 @@ 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('setup-php'); readFileSync.mockReturnValue('php 8.4 8.5');
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);
@@ -359,29 +388,44 @@ describe('Utils tests', () => {
const existsSync = jest.spyOn(fs, 'existsSync').mockImplementation(); const existsSync = jest.spyOn(fs, 'existsSync').mockImplementation();
const readFileSync = jest.spyOn(fs, 'readFileSync').mockImplementation(); const readFileSync = jest.spyOn(fs, 'readFileSync').mockImplementation();
process.env['php-version'] = 'bogus'; process.env['php-version'] = '$0';
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('bogus'); readFileSync.mockReturnValue(';id');
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":"bogus"}}'); readFileSync.mockReturnValue('{"platform-overrides":{"php":"`w`"}}');
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":"bogus"}}}'); readFileSync.mockReturnValue('{"config":{"platform":{"php":"8.4$(id)"}}}');
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();
}); });
@@ -395,3 +439,445 @@ describe('Utils tests', () => {
expect(script).toEqual('\n$var = command\n'); expect(script).toEqual('\n$var = command\n');
}); });
}); });
const hasPwsh =
spawnSync('pwsh', ['-NoProfile', '-Command', 'exit 0']).status === 0;
const scripts = path.join(__dirname, '../src/scripts');
const unixInit = fs.readFileSync(path.join(scripts, 'unix.sh'), 'utf8');
const windowsSource = fs.readFileSync(path.join(scripts, 'win32.ps1'), 'utf8');
const windowsInit = [
windowsSource.match(/Function Invoke-WithoutTrace[\s\S]*?\n}/)![0],
windowsSource.match(
/\$setup_php_trace = 0\r?\nif \(\$env:SETUP_PHP_TRACE[\s\S]*?\n}/
)![0]
].join('\n');
describe.each(['linux', 'darwin', 'win32'])(
'Verbose scripts 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});
const init = path.join(scripts, 'init' + extension);
fs.writeFileSync(
init,
platform === 'win32'
? windowsInit
: unixInit + '\nrunner=self-hosted read_env\n'
);
helper = path.join(scripts, 'tools', 'helper' + extension);
run = path.join(scripts, 'run' + extension);
fs.writeFileSync(helper, 'echo helper-output\n');
fs.writeFileSync(
run,
`. '${init}'\n. '${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);
if (platform === 'win32' ? hasPwsh : process.platform !== 'win32') {
const result = spawnSync(
platform === 'win32' ? 'pwsh' : 'bash',
platform === 'win32'
? ['-NoProfile', '-File', prepared]
: [prepared],
{encoding: 'utf8', env: process.env}
);
expect(result.status).toBe(0);
expect(/helper-output\r?\n/.test(result.stdout)).toBe(enabled);
expect(
platform === 'win32'
? result.stdout.includes('DEBUG:')
: result.stderr.includes('+ ')
).toBe(tracing);
}
}
);
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);
const shell = platform === 'win32' ? 'pwsh' : 'bash';
if (platform === 'win32' ? hasPwsh : process.platform !== 'win32') {
const result = spawnSync(
shell,
platform === 'win32'
? ['-NoProfile', '-File', prepared]
: [prepared],
{encoding: 'utf8', env: process.env}
);
expect(result.status).toBe(0);
expect(result.stdout).toMatch(/nested-output\r?\n/);
}
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'
);
}
);
it.each(['true', 'vv', 'vvv'])(
'protects nested sensitive calls and restores tracing for verbose=%s',
async verbose => {
const windows = platform === 'win32';
if (windows ? !hasPwsh : process.platform === 'win32') return;
process.env.verbose = verbose;
process.env.GITHUB_TOKEN = 'example-github-token';
process.env.TRACE_TEST_OUTPUT = path.join(root, 'tokens');
fs.writeFileSync(
helper,
windows
? `$result = 0
try {
Invoke-WithoutTrace {
Invoke-WithoutTrace {
$token = $env:GITHUB_TOKEN
Set-Content $env:TRACE_TEST_OUTPUT $token
}
$token = $env:GITHUB_TOKEN
Add-Content $env:TRACE_TEST_OUTPUT $token
if ($env:TRACE_TEST_STATUS -ne '0') { throw 'example-failure' }
}
} catch {
if ($_.Exception.Message -ne 'example-failure') { throw }
$result = [int]$env:TRACE_TEST_STATUS
}
$after_wrapper = 'after-wrapper'
Write-Output $after_wrapper
Write-Output "status=$result"
`
: `inner_sensitive() {
token="$GITHUB_TOKEN"
printf '%s\\n' "$token" > "$TRACE_TEST_OUTPUT"
return "$TRACE_TEST_STATUS"
}
outer_sensitive() {
without_trace inner_sensitive
local result=$?
token="$GITHUB_TOKEN"
printf '%s\\n' "$token" >> "$TRACE_TEST_OUTPUT"
return "$result"
}
without_trace outer_sensitive
result=$?
echo "\${token:+state-preserved}"
echo after-wrapper
exit "$result"
`
);
const prepared = await utils.addVerbose(run, platform);
for (const status of [0, 37]) {
const result = spawnSync(
windows ? 'pwsh' : 'bash',
windows ? ['-NoProfile', '-File', prepared] : [prepared],
{
encoding: 'utf8',
env: {...process.env, TRACE_TEST_STATUS: String(status)}
}
);
expect(result.status).toBe(windows ? 0 : status);
expect(result.stdout + result.stderr).not.toContain(
'example-github-token'
);
expect(result.stdout).toContain('after-wrapper');
expect(
windows
? /DEBUG:.*Write-Output \$after_wrapper/.test(result.stdout)
: result.stderr.includes('+ echo after-wrapper')
).toBe(verbose !== 'true');
if (windows) {
expect(result.stdout).toContain('status=' + status);
expect(/DEBUG:\s+!\s+SET \$after_wrapper/.test(result.stdout)).toBe(
verbose === 'vvv'
);
} else {
expect(result.stdout).toContain('state-preserved');
}
expect(
fs
.readFileSync(process.env.TRACE_TEST_OUTPUT!, 'utf8')
.trim()
.split(/\r?\n/)
).toEqual(['example-github-token', 'example-github-token']);
}
}
);
it.each(['true', 'vv', 'vvv'])(
'keeps Blackfire credentials out of traces for verbose=%s',
async verbose => {
const windows = platform === 'win32';
if (windows ? !hasPwsh : process.platform === 'win32') return;
process.env.verbose = verbose;
process.env.TRACE_TEST_OUTPUT = path.join(root, 'blackfire-config');
process.env.BLACKFIRE_SERVER_ID = 'example-blackfire-server-id';
process.env.BLACKFIRE_SERVER_TOKEN = 'example-blackfire-server-token';
process.env.BLACKFIRE_CLIENT_ID = 'example-blackfire-client-id';
process.env.BLACKFIRE_CLIENT_TOKEN = 'example-blackfire-client-token';
fs.writeFileSync(
helper,
fs.readFileSync(
path.join(
scripts,
'tools',
'blackfire' + (windows ? '.ps1' : '.sh')
),
'utf8'
) +
(windows
? `
function Invoke-RestMethod { @{cli='1.2.3'} }
function Get-File {}
function Expand-Archive {}
function Add-ToProfile {}
function Add-Log {}
function blackfire { Add-Content $env:TRACE_TEST_OUTPUT ($args -join ' ') }
$version = '8.4'
$bin_dir = 'unused'
Add-Blackfire
Write-Output after-blackfire
`
: `
blackfire() { printf '%s\\n' "$@" >> "$TRACE_TEST_OUTPUT"; }
os=Test
blackfire_config
echo after-blackfire
`)
);
const prepared = await utils.addVerbose(run, platform);
const result = spawnSync(
windows ? 'pwsh' : 'bash',
windows ? ['-NoProfile', '-File', prepared] : [prepared],
{encoding: 'utf8', env: process.env}
);
expect(result.status).toBe(0);
expect(result.stdout + result.stderr).not.toContain(
'example-blackfire-'
);
expect(result.stdout).toContain('after-blackfire');
expect(
windows
? /DEBUG:.*Write-Output after-blackfire/.test(result.stdout)
: result.stderr.includes('+ echo after-blackfire')
).toBe(verbose !== 'true');
const config = fs.readFileSync(process.env.TRACE_TEST_OUTPUT!, 'utf8');
for (const value of [
'server-id',
'server-token',
'client-id',
'client-token'
]) {
expect(config).toContain('example-blackfire-' + value);
}
}
);
it('keeps Composer credentials out of traces and resumes tracing', async () => {
if (platform === 'win32' ? !hasPwsh : process.platform === 'win32')
return;
process.env.verbose = 'vvv';
process.env.GITHUB_TOKEN = 'example-github-token';
process.env.COMPOSER_TOKEN = 'example-composer-token';
process.env.PACKAGIST_TOKEN = 'example-packagist-token';
process.env.COMPOSER_AUTH_JSON =
'{"bearer":{"example.org":"example-json-token"}}';
process.env.GITHUB_SERVER_URL = 'https://github.com';
const windows = platform === 'win32';
const source = fs.readFileSync(
path.join(scripts, 'tools', 'add_tools' + (windows ? '.ps1' : '.sh')),
'utf8'
);
fs.writeFileSync(
helper,
source +
(windows
? `\n$composer_home='${root}'\nSet-ComposerAuth\nWrite-Output after-auth\n`
: `\ncomposer_home='${root}'\nset_composer_auth\necho after-auth\n`)
);
const prepared = await utils.addVerbose(run, platform);
const result = spawnSync(
windows ? 'pwsh' : 'bash',
windows ? ['-NoProfile', '-File', prepared] : [prepared],
{encoding: 'utf8', env: process.env}
);
expect(result.status).toBe(0);
expect(result.stdout + result.stderr).not.toMatch(
/example-(github|composer|packagist|json)-token/
);
expect(windows ? result.stdout : result.stderr).toMatch(
windows ? /DEBUG:.*Write-Output after-auth/ : /\+ echo after-auth/
);
const auth = JSON.parse(
fs.readFileSync(path.join(root, 'auth.json'), 'utf8')
);
expect(auth['github-oauth']['github.com']).toBe('example-composer-token');
expect(auth['http-basic']['repo.packagist.com'].password).toBe(
'example-packagist-token'
);
expect(auth.bearer['example.org']).toBe('example-json-token');
});
if (platform !== 'win32') {
(process.platform === 'win32' ? it.skip : it).each([
['exit 37', 37],
['set -e\nfalse', 1]
])('preserves shell termination for %s', async (failure, status) => {
process.env.verbose = 'vvv';
process.env.GITHUB_TOKEN = 'example-github-token';
fs.writeFileSync(
helper,
`
sensitive_failure() {
token="$GITHUB_TOKEN"
${failure}
echo should-not-run
}
trap 'echo cleanup' EXIT
without_trace sensitive_failure
echo should-not-run
`
);
const prepared = await utils.addVerbose(run, platform);
const result = spawnSync('bash', [prepared], {
encoding: 'utf8',
env: process.env
});
expect(result.status).toBe(status);
expect(result.stdout).toBe('cleanup\n');
expect(result.stdout + result.stderr).not.toContain(
'example-github-token'
);
});
(process.platform === 'win32' ? it.skip : it).each(['true', 'vv', 'vvv'])(
'protects Relay credentials and preserves tracing and status for verbose=%s',
async verbose => {
process.env.verbose = verbose;
const ini = path.join(root, 'relay.ini');
fs.writeFileSync(
helper,
fs.readFileSync(path.join(scripts, 'extensions/relay.sh'), 'utf8') +
'\nsudo() { if [ "$1" = rm ]; then return "$RELAY_TEST_STATUS"; fi; "$@"; }\n' +
`init_relay_ini '${ini}'\nrelay_status=$?\necho after-relay\nexit "$relay_status"\n`
);
const prepared = await utils.addVerbose(run, platform);
for (const status of [0, 37]) {
fs.writeFileSync(ini, '; relay.key =\n');
const result = spawnSync('bash', [prepared], {
encoding: 'utf8',
env: {
...process.env,
RELAY_KEY: 'example-relay-key',
RELAY_TEST_STATUS: String(status)
}
});
expect(result.status).toBe(status);
expect(result.stdout + result.stderr).not.toContain(
'example-relay-key'
);
expect(result.stdout).toContain('after-relay');
expect(result.stderr.includes('+ echo after-relay')).toBe(
verbose !== 'true'
);
expect(fs.readFileSync(ini, 'utf8')).toBe(
'relay.key = example-relay-key\n'
);
}
}
);
}
(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
+1
View File
@@ -20,6 +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": "jest"
}, },
"repository": { "repository": {
+1 -1
View File
@@ -47,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 run_path; return await utils.addVerbose(run_path, os);
} }
/** /**
+28 -10
View File
@@ -90,7 +90,13 @@ add_brew_extension() {
safe_brew install --skip-link "${brew_opts[@]}" "$ext_tap/$formula@$version" >/dev/null 2>&1 && safe_brew install --skip-link "${brew_opts[@]}" "$ext_tap/$formula@$version" >/dev/null 2>&1 &&
brew link --overwrite --force "$formula@$version" >/dev/null 2>&1 && brew link --overwrite --force "$formula@$version" >/dev/null 2>&1 &&
copy_brew_extensions "$formula" copy_brew_extensions "$formula"
) || 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
} }
@@ -183,29 +189,35 @@ setup_cached_versions() {
# 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
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)" = "arm64" ] && [ "${runner:?}" != "self-hosted" ] && \ if [ "${runner:?}" != "self-hosted" ] && [ "${use_package_cache:-true}" != "false" ]; then
[ "${use_package_cache:-true}" != "false" ] && setup_cached_versions; then setup_cached_versions && return 0
return 0 [ "$(uname -m)" != "x86_64" ] || return 1
fi fi
update_dependencies update_dependencies
add_brew_tap "$php_tap" add_brew_tap "$php_tap"
fi 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" safe_brew install --only-dependencies "$php_formula" || return $?
safe_brew upgrade -f --overwrite "$php_formula" safe_brew upgrade -f --overwrite "$php_formula" || return $?
else else
brew unlink "$php_keg" brew unlink "$php_keg"
fi fi
else else
safe_brew install --only-dependencies "$php_formula" safe_brew install --only-dependencies "$php_formula" || return $?
safe_brew install --skip-link -f --overwrite "$php_formula" 2>/dev/null || safe_brew upgrade -f --overwrite "$php_formula" safe_brew install --skip-link -f --overwrite "$php_formula" 2>/dev/null || {
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")
} }
@@ -264,12 +276,18 @@ setup_php() {
run_script "php5-darwin" "${version/./}" >/dev/null 2>&1 run_script "php5-darwin" "${version/./}" >/dev/null 2>&1
status="Installed" status="Installed"
elif [[ "${existing_version:0:3}" != "$version" || -n "$(get_php_formula_suffix)" ]]; then elif [[ "${existing_version:0:3}" != "$version" || -n "$(get_php_formula_suffix)" ]]; then
add_php "install" "$existing_version" >/dev/null 2>&1 add_php "install" "$existing_version" >/dev/null 2>&1 || {
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" >/dev/null 2>&1 || {
add_log "${cross:?}" "PHP" "Could not upgrade PHP $version"
exit 1
}
status="Upgraded" status="Upgraded"
fi fi
fi fi
+55 -7
View File
@@ -104,16 +104,50 @@ Function Add-Extension {
[string] [string]
$extension_version = '' $extension_version = ''
) )
$extension_backup = ''
$restore_startup_errors = $false
try { try {
$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
if($extension_version -ne '' -and (Test-Path "$ext_dir\$extension-$extension_version")) { $cached = $extension_version -ne '' -and (Test-Path "$ext_dir\$extension-$extension_version")
Copy-Item "$ext_dir\$extension-$extension_version" "$ext_dir\php_$extension.dll" -Force $extension_info = $null
Enable-Extension $extension if(-not $cached) {
return $extension_info = Get-PhpExtension -Path $php_dir | Where-Object { $_.Name -eq $extension -or $_.Handle -eq $extension }
} }
$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 ($null -ne $extension_info -and ($extension_version -eq '' -or $extension_info.Version[0] -eq $extension_version)) { if($cached -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_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"
@@ -143,7 +177,10 @@ Function Add-Extension {
} }
# 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) {
Move-Item $ext_dir\php_$extension.dll $ext_dir\php_$extension.bak.dll -Force # Keep backups outside PhpManager's DLL scan and reuse known versions as cache entries.
$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
@@ -154,7 +191,18 @@ Function Add-Extension {
Copy-Item "$ext_dir\php_$extension.dll" "$ext_dir\$extension-$extension_version" -Force 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"
}
}
} }
} }
+3 -4
View File
@@ -222,16 +222,15 @@ add_pecl_extension() {
# Cache versioned extensions using suffixless copies in extension_dir. # Cache versioned extensions using suffixless copies in extension_dir.
if [ -n "$pecl_version" ] && [ -e "${ext_dir:?}/$extension-$pecl_version" ]; then if [ -n "$pecl_version" ] && [ -e "${ext_dir:?}/$extension-$pecl_version" ]; then
sudo cp "${ext_dir:?}/$extension-$pecl_version" "${ext_dir:?}/$extension.so" sudo cp "${ext_dir:?}/$extension-$pecl_version" "${ext_dir:?}/$extension.so"
enable_extension "$extension" "$prefix" sudo rm -f /tmp/php"${version:?}"_extensions
add_log "${tick:?}" "$extension" "Enabled"
return
fi fi
enable_extension "$extension" "$prefix" enable_extension "$extension" "$prefix"
ext_version=$(php -r "echo phpversion('$extension');") 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 [ -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")" >/dev/null 2>&1)
extension_version="$(php -r "echo phpversion('$extension');")" extension_version="$(php -r "echo phpversion('$extension');")"
+4
View File
@@ -63,6 +63,10 @@ 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
+28 -26
View File
@@ -87,35 +87,37 @@ Function Write-ComposerGhAuthNoOpWarning() {
# Function to setup authentication in composer. # Function to setup authentication in composer.
Function Set-ComposerAuth() { Function Set-ComposerAuth() {
$token = if ($env:COMPOSER_TOKEN) { $env:COMPOSER_TOKEN } else { $env:GITHUB_TOKEN } Invoke-WithoutTrace {
if(Test-Path env:COMPOSER_AUTH_JSON) { $token = if ($env:COMPOSER_TOKEN) { $env:COMPOSER_TOKEN } else { $env:GITHUB_TOKEN }
if(Test-Json -JSON $env:COMPOSER_AUTH_JSON) { if(Test-Path env:COMPOSER_AUTH_JSON) {
Set-Content -Path $composer_home\auth.json -Value $env:COMPOSER_AUTH_JSON if(Test-Json -JSON $env:COMPOSER_AUTH_JSON) {
} else { Set-Content -Path $composer_home\auth.json -Value $env:COMPOSER_AUTH_JSON
Add-Log "$cross" "composer" "Could not parse COMPOSER_AUTH_JSON as valid JSON" } else {
Add-Log "$cross" "composer" "Could not parse COMPOSER_AUTH_JSON as valid JSON"
}
} }
} if($skip_composer_github_auth) {
if($skip_composer_github_auth) { Write-ComposerGhAuthNoOpWarning
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
} }
if ($env:GITHUB_SERVER_URL -ne "https://github.com" -and -not(Test-GitHubPublicAccess $token)) { $composer_auth = @()
$write_token = $false if(Test-Path env:PACKAGIST_TOKEN) {
$composer_auth += '"http-basic": {"repo.packagist.com": { "username": "token", "password": "' + $env:PACKAGIST_TOKEN + '"}}'
} }
if($write_token) { $write_token = $true
$composer_auth += '"github-oauth": {"github.com": "' + $token + '"}' if ($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
} }
} }
@@ -222,7 +224,7 @@ Function Add-ToolsHelper() {
} 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") { } elseif($tool -eq "cloud-cli") {
$extensions += @('sockets') $extensions += @('fileinfo', 'sockets')
Copy-Item $env:cloud_cli_bin\cloud.bat -Destination $env:cloud_cli_bin\cloud-cli.bat 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')
+5 -1
View File
@@ -85,6 +85,10 @@ 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
@@ -186,7 +190,7 @@ add_tools_helper() {
sudo cp "$tool_path_dir"/phpunit "$composer_bin" sudo cp "$tool_path_dir"/phpunit "$composer_bin"
fi fi
elif [ "$tool" = "cloud-cli" ]; then elif [ "$tool" = "cloud-cli" ]; then
extensions+=(dom iconv sockets tokenizer) extensions+=(dom fileinfo iconv sockets tokenizer)
sudo ln -s "$scoped_dir"/vendor/bin/cloud "$scoped_dir"/vendor/bin/cloud-cli 2>/dev/null || true 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)
+7 -5
View File
@@ -9,11 +9,13 @@ Function Add-Blackfire() {
Get-File -Url $url -OutFile $bin_dir\blackfire.zip >$null 2>&1 Get-File -Url $url -OutFile $bin_dir\blackfire.zip >$null 2>&1
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 >$null 2>&1
Add-ToProfile $current_profile 'blackfire' "New-Alias blackfire $bin_dir\blackfire.exe" Add-ToProfile $current_profile 'blackfire' "New-Alias blackfire $bin_dir\blackfire.exe"
if ((Test-Path env:BLACKFIRE_SERVER_ID) -and (Test-Path env:BLACKFIRE_SERVER_TOKEN)) { Invoke-WithoutTrace {
blackfire agent:config --server-id=$env:BLACKFIRE_SERVER_ID --server-token=$env:BLACKFIRE_SERVER_TOKEN >$null 2>&1 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 >$null 2>&1
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 >$null 2>&1 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 >$null 2>&1
}
} }
Add-Log $tick "blackfire" "Added blackfire $cli_version" Add-Log $tick "blackfire" "Added blackfire $cli_version"
} }
+4
View File
@@ -12,6 +12,10 @@ 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
+51 -25
View File
@@ -55,25 +55,45 @@ get_file_mtime() {
fi fi
} }
# Function to terminate a process and its direct children. # Function to list descendants before their parents, including separate sessions.
terminate_process_tree() { get_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" >/dev/null 2>&1 || true
for child in $children; do for child in $children; do
terminate_process_tree "$child" get_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
kill -KILL "$pid" >/dev/null 2>&1 || true for pid in $pids; do
for child in $children; do kill -KILL "$pid" >/dev/null 2>&1 || true
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
@@ -93,36 +113,39 @@ 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" >/dev/null 2>&1; 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 "$timeout_secs" ]; then if [ $((now - last_activity)) -ge "$active_timeout_secs" ]; then
printf "\nsetup-php: brew produced no output for %ss; terminating and retrying...\n" "$timeout_secs" >&2 printf "\nsetup-php: brew produced no output for %ss; terminating...\n" "$active_timeout_secs" >&2
: >"$timeout_file" : >"$timeout_file"
terminate_process_tree "$command_pid" terminate_process_tree "$command_pid"
break break
@@ -131,12 +154,15 @@ run_with_inactivity_watchdog() {
) & ) &
monitor_pid=$! monitor_pid=$!
wait "$command_pid" exit_code=0
exit_code=$? wait "$command_pid" || 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" >/dev/null 2>&1 || 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"
+13
View File
@@ -48,8 +48,21 @@ set_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 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
+18
View File
@@ -28,6 +28,18 @@ 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(
@@ -333,6 +345,12 @@ $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'
+16 -4
View File
@@ -118,6 +118,12 @@ export function extractChecksum(release: string): {
error: `Invalid ${algo} checksum, expected ${hash_length} hexadecimal characters` 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}`}; return {release, checksum: `${algo}:${hash}`};
} }
@@ -308,9 +314,14 @@ 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(extractChecksum(tool).release) 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(extractChecksum(tool).release) tool => !regex_any.test(extractChecksum(tool).release)
@@ -480,7 +491,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-]+)?$/.test(data.version): case /^\d+\.\d+\.\d+(?:-[\w.-]+)?(?:\+[\w.-]+)?$/.test(data.version):
if (skipGitHubAuthForComposerVersion(data.version)) { if (skipGitHubAuthForComposerVersion(data.version)) {
cleanComposerAuthJson(); cleanComposerAuthJson();
skip_composer_github_auth = ' true'; skip_composer_github_auth = ' true';
@@ -721,6 +732,7 @@ export async function getData(
data.checksum = checksum_data.checksum; data.checksum = checksum_data.checksum;
data.error = checksum_data.error; 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);
+50 -9
View File
@@ -71,15 +71,13 @@ 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: string | undefined = JSON.parse(fetchResult['data'])[ const resolved: unknown = JSON.parse(fetchResult['data'])[version];
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 (!/^\d+\.\d+$/.test(resolved)) { if (typeof resolved !== 'string' || !/^\d+\.\d+$/.test(resolved)) {
throw new Error( throw new Error(
`Invalid PHP version in manifest: ${resolved.slice(0, 10)}` `Invalid PHP version in manifest: ${typeof resolved === 'string' ? resolved.slice(0, 10) : typeof resolved}`
); );
} }
return resolved; return resolved;
@@ -332,6 +330,47 @@ export async function suppressOutput(os: string): Promise<string> {
} }
} }
/**
* 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.
* *
@@ -473,10 +512,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: string, source: string): string { function validatePHPVersionInput(version: unknown, source: string): string {
if (!VERSION_INPUT_REGEX.test(version)) { if (typeof version !== 'string' || !VERSION_INPUT_REGEX.test(version)) {
throw new Error( throw new Error(
`Invalid PHP version in ${source}: ${version.slice(0, 20)}` `Invalid PHP version in ${source}: ${typeof version === 'string' ? version.slice(0, 20) : typeof version}`
); );
} }
return version; return version;
@@ -494,7 +533,9 @@ 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(/^(?:php\s)?(\d+\.\d+\.\d+)$/m); const match = contents.match(
/^[ \t]*(?:php[ \t]+)?([^\s#]+)[ \t]*(?:#.*)?$/m
);
return validatePHPVersionInput( return validatePHPVersionInput(
match ? match[1] : contents.trim(), match ? match[1] : contents.trim(),
versionFile versionFile