diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/SKILL.md b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/SKILL.md index db27299..975eb38 100644 --- a/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/SKILL.md +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/SKILL.md @@ -95,6 +95,10 @@ list, and keep the phase table in `$STATE/state.md`: it survives a compaction. `.ai-dev/feature-install//` in the project. Substitute each one inline as a literal path; never set a shell variable and never `cd`. Run every script from the project root. +**Tool output.** `run-tools.php` prints one line per tool and writes the full output to files in +`$STATE`; `compare-baselines.php` prints one line per check. Read these lines. Open a log file +only for the failing part and search it for that part; never read the whole file. + **Delegation.** Invoke skills by slash command (`/spryker-refresher`, or `/spryker-ai-dev-sdk:spryker-refresher` on a plugin install). Agent names carry the plugin prefix on a plugin install, and the separator differs by harness (see @@ -150,11 +154,14 @@ or a package name.** Record in `state.md` that the search ran through a fallback SPRYKER_UPGRADE_STATE_DIR=$STATE/baseline php $UP/check-config-constants.php || true SPRYKER_UPGRADE_STATE_DIR=$STATE/baseline php $UP/check-dead-overrides.php snapshot SPRYKER_UPGRADE_STATE_DIR=$STATE/baseline php $UP/twig-shadow-map.php snapshot - script -q /dev/null docker/sdk cli php -d memory_limit=2048M vendor/bin/phpstan analyze -c phpstan.neon src/ -l 6 2>&1 | tee $STATE/baseline/phpstan-baseline-run.txt - script -q /dev/null docker/sdk cli vendor/bin/console code:sniff:style 2>&1 | tee $STATE/baseline/sniff-baseline.txt - script -q /dev/null docker/sdk testing codecept run --no-exit 2>&1 | tee $STATE/baseline/codecept-baseline.txt + SPRYKER_UPGRADE_STATE_DIR=$STATE/baseline php $UP/run-tools.php baseline phpstan sniffer tests --tests-args=--no-exit SPRYKER_UPGRADE_STATE_DIR=$STATE/baseline SPRYKER_BACKOFFICE_USER= SPRYKER_BACKOFFICE_PASSWORD= php $UP/backoffice-smoke.php --url --baseline ``` + `run-tools.php` writes `phpstan-baseline-run.txt`, `sniff-baseline.txt` and + `codecept-baseline.txt`, and pins the invocation in `tool-invocation.json` for Phase 6. It detects + the sniffer entry point; pass `--sniffer ""` when it names the wrong one, + `--env NAME=VALUE` for each environment variable the developer sets for the tests, and + `--codecept-options ""` once for each test configuration the project runs. For the storage and search counts, copy `$UP/storage-search-counts.php` into `$STATE/baseline/` and run it in the container with `--snapshot before`. 4. Check the baselines: `php $FI/compare-baselines.php $STATE` — every line under "Baselines" is @@ -323,9 +330,12 @@ widgets; every vendor template the project overrides has lost the vendor's calls acceptance criterion, in the guide's words. Record `verdict` PASS, FAIL or BLOCKED with the evidence path. Weigh a FAIL as a hypothesis before acting: browser problems look like feature failures. -3. Run the baseline tools again, into `$STATE/after/` with the same commands as in Phase 0: - `phpstan-after.txt`, `sniff-after.txt`, `codecept-after.txt`; the Back Office crawl without - `--baseline` (same `SPRYKER_UPGRADE_STATE_DIR`: it marks each failure that is in the baseline); +3. Run the baseline tools again, into `$STATE/after/` with the invocation Phase 0 pinned: + `SPRYKER_UPGRADE_STATE_DIR=$STATE/after php $UP/run-tools.php after phpstan sniffer tests + --tests-args=--no-exit --pin-dir $STATE/baseline` (it writes `phpstan-after.txt`, + `sniff-after.txt`, `codecept-after.txt`); the Back Office crawl without + `--baseline` (`SPRYKER_UPGRADE_STATE_DIR=$STATE/baseline` as in Phase 0: it marks each failure + that is in the baseline); the storage and search counts with `--snapshot after`, then `--compare before after`. Run each frontend build the project has into `after/yves-build.txt`, `after/zed-build.txt`, `after/mp-build.txt`, each ending with its exit code diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts/compare-baselines.php b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts/compare-baselines.php index f610a14..f17efdd 100644 --- a/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts/compare-baselines.php +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts/compare-baselines.php @@ -47,47 +47,7 @@ function cb_text(string $file): ?string { - return is_file($file) ? bl_plain_text((string)file_get_contents($file)) : null; -} - -function cb_phpstan_errors(string $text): ?int -{ - if (preg_match('/Found (\d+) (?:\S+ )?errors?/', $text, $m)) { - return (int)$m[1]; - } - - return preg_match('/\[OK\] No errors/', $text) ? 0 : null; -} - -function cb_sniff_findings(string $text): ?int -{ - if (preg_match('/A TOTAL OF (\d+) ERRORS? AND (\d+) WARNINGS?/', $text, $m)) { - return (int)$m[1] + (int)$m[2]; - } - if (preg_match_all('/FOUND (\d+) ERRORS?(?: AND (\d+) WARNINGS?)?/', $text, $m, PREG_SET_ORDER)) { - return array_sum(array_map(static fn (array $hit): int => (int)$hit[1] + (int)($hit[2] ?? 0), $m)); - } - - return bl_content_problem('sniff-baseline.txt', $text) === null ? 0 : null; -} - -/** - * @return array{total: ?int, failing: list} - */ -function cb_codecept(string $text): array -{ - $failing = []; - if (preg_match_all('/^\s*\d+\) (\S.*?)\s*$/m', $text, $m)) { - $failing = array_values(array_unique(array_map('trim', $m[1]))); - } - $total = null; - if (preg_match_all('/Tests: \d+, Assertions: \d+(?:, Errors: (\d+))?(?:, Failures: (\d+))?/', $text, $m, PREG_SET_ORDER)) { - $total = array_sum(array_map(static fn (array $hit): int => (int)($hit[1] ?? 0) + (int)($hit[2] ?? 0), $m)); - } elseif (preg_match('/\bOK \(\d+ tests?/', $text)) { - $total = 0; - } - - return ['total' => $total, 'failing' => $failing]; + return is_file($file) ? to_plain_text((string)file_get_contents($file)) : null; } /** @@ -109,9 +69,9 @@ function cb_evaluate(string $stateDir): array $after = cb_text($afterDir . '/phpstan-after.txt'); $checks['phpstan'] = match (true) { $after === null => 'missing after/phpstan-after.txt', - cb_phpstan_errors($after) === null => 'after/phpstan-after.txt has no PHPStan result line', - $before === null || cb_phpstan_errors($before) === null => 'no valid baseline to compare with', - cb_phpstan_errors($after) > cb_phpstan_errors($before) => sprintf('errors grew from %d to %d', cb_phpstan_errors($before), cb_phpstan_errors($after)), + to_phpstan_count($after) === null => 'after/phpstan-after.txt has no PHPStan result line', + $before === null || to_phpstan_count($before) === null => 'no valid baseline to compare with', + to_phpstan_count($after) > to_phpstan_count($before) => sprintf('errors grew from %d to %d', to_phpstan_count($before), to_phpstan_count($after)), default => null, }; @@ -119,9 +79,9 @@ function cb_evaluate(string $stateDir): array $after = cb_text($afterDir . '/sniff-after.txt'); $checks['sniffer'] = match (true) { $after === null => 'missing after/sniff-after.txt', - cb_sniff_findings($after) === null => 'after/sniff-after.txt has no sniffer result', - $before === null || cb_sniff_findings($before) === null => 'no valid baseline to compare with', - cb_sniff_findings($after) > cb_sniff_findings($before) => sprintf('findings grew from %d to %d', cb_sniff_findings($before), cb_sniff_findings($after)), + to_sniff_count($after) === null => 'after/sniff-after.txt has no sniffer result', + $before === null || to_sniff_count($before) === null => 'no valid baseline to compare with', + to_sniff_count($after) > to_sniff_count($before) => sprintf('findings grew from %d to %d', to_sniff_count($before), to_sniff_count($after)), default => null, }; @@ -132,8 +92,8 @@ function cb_evaluate(string $stateDir): array } elseif ($before === null) { $checks['tests'] = 'no valid baseline to compare with'; } else { - $old = cb_codecept($before); - $new = cb_codecept($after); + $old = to_codecept_summary($before); + $new = to_codecept_summary($after); $newFailures = array_values(array_diff($new['failing'], $old['failing'])); $checks['tests'] = match (true) { $new['total'] === null => 'after/codecept-after.txt has no summary line', diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/README.md b/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/README.md index d7146c8..6c8609f 100644 --- a/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/README.md +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/README.md @@ -25,12 +25,14 @@ SPRYKER_PROJECT_ROOT=/path/to/project # skip discovery SPRYKER_UPGRADE_STATE_DIR=/path/to/state # move baselines/reports (e.g. a CI cache directory) ``` -## The twenty-one scripts +## The twenty-three scripts | Script | Phase | What it answers | |---|---|---| | `check-added-comments.php` | 0 (`--record-base`), every lane, 7 | were explanatory comments or suppressions added since the upgrade began? | | `check-baselines.php` | 0 (gate) | do all Phase 0 baselines exist, so Phase 1 may start? | +| `run-tools.php` | 0, 1.2, 3, 5, 5.5 | what did PHPStan, the sniffer, the evaluator and the test suite report, with the invocation Phase 0 pinned? | +| `compare-tool-runs.php` | 1.2, 3, 5, 5.5 | which PHPStan errors, sniffer violations, evaluator findings and failing tests are new against the baselines? | | `backoffice-smoke.php` | 0 (`--baseline`), 4.9, 6.5 | does every Back Office navigation page and table data endpoint still answer? | | `check-platform-alignment.php` | 0, 1.2 | will a lock resolved on this host install on the project's image? | | `check-test-coverage.php` | 0, 0.5 | which customised modules would not notice if the upgrade broke them? | @@ -53,7 +55,8 @@ SPRYKER_UPGRADE_STATE_DIR=/path/to/state # move baselines/reports (e.g. a CI Phase 0 (`snapshot`) and Phase 6.1 (`diff`) also run `yves-integration-scan.php` from the sibling `yves-twig-integration` skill: which widgets the upgrade added that no template the project renders calls. Its findings are suggestions for the developer, not upgrade damage. -`bootstrap.php` is the shared library the scripts load. `upgrade-scripts.test.php` is the +`bootstrap.php` is the shared library the scripts load; `tool-output.php` parses the tool output +for `check-baselines.php`, `run-tools.php`, `compare-tool-runs.php` and `spryker-feature-install`. `upgrade-scripts.test.php` is the maintainer test suite for the scripts (`php $UP/upgrade-scripts.test.php`); it is not part of an upgrade run. @@ -94,7 +97,8 @@ php $UP/check-plugin-usage.php || true # record pre-existing damage php $UP/check-config-constants.php || true php $UP/check-constant-overrides.php --snapshot cp composer.lock .spryker-upgrade/state/composer.lock.before -# ... PHPStan, sniffer, evaluator and codecept runs tee'd into the state dir (see SKILL.md Phase 0) +php $UP/run-tools.php baseline phpstan sniffer evaluator +php $UP/run-tools.php baseline codecept-build tests --tests-args=--no-exit php $UP/backoffice-smoke.php --url --baseline cp $UP/storage-search-counts.php .spryker-upgrade/state/ # queues drained first docker/sdk cli php .spryker-upgrade/state/storage-search-counts.php --snapshot before @@ -170,7 +174,7 @@ php $UP/check-baselines.php --no-data # only when the environment cannot Checks the state directory for `base-ref`, `codecept-baseline.txt`, `phpstan-baseline-run.txt`, `sniff-baseline.txt`, `evaluator-baseline.txt`, `backoffice-smoke-baseline.json`, `constant-overrides-baseline.json` and `storage-search-counts-before.json`, and that each holds a real -result of its tool: `2>&1 | tee` creates the file even when the command failed. The check is a +result of its tool: `run-tools.php` writes the file also when the tool did not run. The check is a codecept summary line (`OK (`, `Tests:`, `FAILURES!`), a PHPStan `[OK]` or `Found N errors` line, sniffer or evaluator output that is not only a tool error or usage message, a commit hash in `base-ref`, a `results` list in the Back Office baseline, an `overrides` list in the constant-overrides @@ -182,6 +186,44 @@ the same way when they exist. It names the command that produces each missing fi a result. Every "after" check of the upgrade is compared against a "before" run; without it a new failure cannot be told from a pre-existing one. Exit 0 all present with a result, 1 otherwise. +## run-tools.php — PHPStan, sniffer, evaluator and tests in one call + +```bash +php $UP/run-tools.php baseline phpstan sniffer evaluator codecept-build tests --tests-args=--no-exit +php $UP/run-tools.php verify evaluator phpstan sniffer +php $UP/run-tools.php verify codecept-build tests --tests-args="-x Acceptance" +``` + +Runs each named tool in the container with the commands of the phases (inside `script` for a +pseudo-terminal, in its macOS or Linux form), writes the full output to `-.txt` in the +state directory (`phpstan-baseline-run.txt` for the baseline) with `exit ` as the last line, +and prints one line per tool: exit code, result (error count, or tests passed/failed/skipped and the +failing suites) and log file. A tool whose output holds no result is reported as "did not run". +The baseline run pins the sniffer entry point (detected, or `--sniffer`), the `--env` variables and +the `--codecept-options` in `tool-invocation.json`; later runs use the pin (`--pin-dir` reads it from +another directory) and refuse values that differ from it. A project with several test configurations +gives `--codecept-options` once for each (`--codecept-options "-c codeception.api.yml"`): the tests +tool runs `codecept run` once per configuration into one log, and a configuration that did not start +makes it "did not run". `tool-runs-.json` holds the commands, exit codes, the tests per suite +and the names of the failing tests; it is written after each tool, so a stopped run keeps the tools +that finished. Exit 0 every tool ran, 1 a tool did not run, 2 usage or no pin. + +## compare-tool-runs.php — what is new against the baselines + +```bash +php $UP/compare-tool-runs.php verify # every tool with a log of the run +php $UP/compare-tool-runs.php final tests --limit 20 +php $UP/compare-tool-runs.php detect phpstan --baseline phase0 +``` + +Compares the logs of a run with each tool's baseline: `*-post-tooling.txt` when it exists, else the +Phase 0 file (`--baseline phase0` forces the Phase 0 file; the post-tooling run is always compared +with it). Prints one verdict line per tool and at most `--limit` (default 10) new entries: PHPStan +errors and sniffer violations by file and message, evaluator violations, and tests that fail now +and did not fail in the baseline, per suite. The full lists go to `tool-comparison-.json`. +Exit 0 no regression, 1 regression or a run without a result, 2 usage, a missing log or a missing +baseline. + ## backoffice-smoke.php — crawl the whole Back Office ```bash diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/SKILL.md b/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/SKILL.md index 57e8342..3490b07 100644 --- a/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/SKILL.md +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/SKILL.md @@ -39,7 +39,7 @@ detector re-run that reopens a lane reopens its task. `TaskList` survives compac `Base directory for this skill:` when this skill loaded — that line is correct for every install. `$UP` below stands for whichever resolves — substitute it inline as a literal path; never set a shell variable and never `cd`, both prompt on every call. Run them from the project root: they write every snapshot and report -into `/.spryker-upgrade/state/`, created self-gitignoring. The twenty-one scripts are listed in +into `/.spryker-upgrade/state/`, created self-gitignoring. The twenty-three scripts are listed in `README.md` next to this skill; your job is to run the phases in order, do the semantic resolution work, and stop at the gates that belong to the developer. @@ -93,6 +93,11 @@ scripts run on host PHP. Never modify `vendor/`. Read Before the first `composer` command, run the shared environment preflight in [../spryker-feature-install/references/environment-preflight.md](../spryker-feature-install/references/environment-preflight.md). +**Tool output.** `run-tools.php` and `compare-tool-runs.php` print a summary and write the full +output to files in the state directory. Read the summary. Open a log file only for the failing part +and search it for that part; never read the whole file. When a run is stopped before it ends, +`tool-runs-.json` holds the tools that finished: run the other tools again. + **Coverage matrix.** Every known failure mode, what detects it and which phase resolves it is in [references/coverage-matrix.md](references/coverage-matrix.md). Read it when something turns up that you cannot place, and before the Phase 7 report; a new failure mode gets a row and a check. @@ -125,22 +130,27 @@ you cannot place, and before the Phase 7 report; a new failure mode gets a row a ``` 5. MISSING plugins, config problems or unloadable classes in these baselines are pre-existing breaks, usually leftovers of a removed feature. Surface them, offer to fix first, at minimum record counts. -6. **Static baselines** (record, don't fix). Use the project's sniffer entry point — - `vendor/bin/console code:sniff:style`, or its phpcs setup — and note which, for Phase 5: +6. **Static baselines** (record, don't fix) — PHPStan, the sniffer and the evaluator, into + `phpstan-baseline-run.txt`, `sniff-baseline.txt` and `evaluator-baseline.txt`: ```bash - script -q /dev/null docker/sdk cli php -d memory_limit=2048M vendor/bin/phpstan analyze -c phpstan.neon src/ -l 6 2>&1 | tee .spryker-upgrade/state/phpstan-baseline-run.txt - script -q /dev/null docker/sdk cli vendor/bin/console code:sniff:style 2>&1 | tee .spryker-upgrade/state/sniff-baseline.txt - script -q /dev/null docker/sdk cli vendor/bin/evaluator evaluate 2>&1 | tee .spryker-upgrade/state/evaluator-baseline.txt + php $UP/run-tools.php baseline phpstan sniffer evaluator ``` + The runner detects the project's sniffer entry point (`vendor/bin/console code:sniff:style`, or + its phpcs setup) and records which, for Phase 5. When it names the wrong one, run it again with + `--sniffer ""`. 7. **Baseline test run** — projects routinely start with red tests, often because of their own customisation, so the post-upgrade result means nothing without it: ```bash - script -q /dev/null docker/sdk testing codecept build - script -q /dev/null docker/sdk testing codecept run --no-exit 2>&1 | tee .spryker-upgrade/state/codecept-baseline.txt + php $UP/run-tools.php baseline codecept-build tests --tests-args=--no-exit ``` - Record pass/fail/skip per suite and the exact invocation, environment variables included (matrix - #66). The red tests become the report's "Tests already red before the upgrade" list; a suite that - cannot run is named with the reason, never counted as passing. + Add `--env NAME=VALUE` for each environment variable the developer sets for the tests, and + `--codecept-options ""` once for each test configuration the project runs (for example + `--codecept-options "-c codeception.api.yml"`); the runner runs them in that order into one log. + The baseline run pins the exact invocation, environment variables included, in + `tool-invocation.json` (matrix #66); every later run uses it. It records pass/fail/skip per suite + and the names of the failing tests in `tool-runs-baseline.json`. The red tests + become the report's "Tests already red before the upgrade" list; a suite that cannot run is named + with the reason, never counted as passing. 8. **Back Office crawl baseline** — every navigation page and every table data endpoint; `--baseline` writes `backoffice-smoke-baseline.json`. Exit 1 lists pages already failing (record them); exit 2 is a failed login or an unreachable or wrong URL, and no baseline was written: @@ -150,8 +160,8 @@ you cannot place, and before the Phase 7 report; a new failure mode gets a row a The credentials come from the environment (exported by the developer, or the repository-seeded demo account `spryker-runtime` documents); never write them into a file. 9. **Gate the baselines:** `php $UP/check-baselines.php` exits 0 before Phase 1 starts. It names each - baseline file above that is missing or holds no result of its tool (`tee` writes the file even when - the command failed or ran nothing): re-run that command. `--no-backoffice` (`--no-data`) only when + baseline file above that is missing or holds no result of its tool (the runner writes the file + also when the tool did not run): re-run that command. `--no-backoffice` (`--no-data`) only when the environment cannot boot (with data); the report then says the crawl (publish check) never ran. 10. **Create the task list** (§ Non-negotiables) as the last action of Phase 0. @@ -245,10 +255,12 @@ the target release**, each as its own commit, following 3. **Tooling set** — `phpstan/phpstan` and the PHPStan extensions the project has, `spryker-sdk/evaluator`, `spryker/code-sniffer`, `codeception/*`, `phpunit/phpunit` — to the reference's constraints, updated alone, in the container, as its own commit. -4. **Re-take the PHPStan, sniffer and evaluator baselines** right after that commit (and the test - baseline when codeception or phpunit moved) into `phpstan-`, `sniff-`, `evaluator-` and - `codecept-post-tooling.txt`, keeping the Phase 0 files, then re-run `check-baselines.php`. From - here on a tool's baseline is its `*-post-tooling.txt` file, so new tool rules are not upgrade damage. +4. **Re-take the PHPStan, sniffer and evaluator baselines** right after that commit with + `php $UP/run-tools.php post-tooling phpstan sniffer evaluator` (add `codecept-build tests + --tests-args=--no-exit` when codeception or phpunit moved). It writes `phpstan-`, `sniff-`, + `evaluator-` and `codecept-post-tooling.txt` and keeps the Phase 0 files; then re-run + `check-baselines.php`. From here on a tool's baseline is its `*-post-tooling.txt` file, so new tool + rules are not upgrade damage. If the new tools cannot resolve against the pre-upgrade modules, the tooling step and the image tag defer until right after Phase 2 (the reference's § When the new tools cannot resolve against the old code). @@ -306,7 +318,8 @@ php $UP/check-plugin-usage.php # exit 1 = missing plugins php $UP/check-config-constants.php # exit 1 = broken config refs php $UP/check-constant-overrides.php # exit 1 = core value changed under a project constant php $UP/check-performance.php # exit 1 = ProductGroupWidget rendering lost (Lane 2) -script -q /dev/null docker/sdk cli php -d memory_limit=2048M vendor/bin/phpstan analyze -c phpstan.neon src/ -l 6 +php $UP/run-tools.php detect phpstan +php $UP/compare-tool-runs.php detect phpstan # exit 1 = new PHPStan errors against the baseline ``` Run `check-typed-members.php` first: typed-member fatals abort `vendor/bin/console` itself (with @@ -412,11 +425,9 @@ script -q /dev/null docker/sdk cli vendor/bin/console transfer:generate script -q /dev/null docker/sdk cli vendor/bin/console propel:migration:diff # inspect; NEVER auto-migrate script -q /dev/null docker/sdk cli vendor/bin/console search:setup:index-map script -q /dev/null docker/sdk cli vendor/bin/console navigation:build-cache -script -q /dev/null docker/sdk cli vendor/bin/evaluator evaluate -script -q /dev/null docker/sdk cli php -d memory_limit=2048M vendor/bin/phpstan analyze -c phpstan.neon src/ -l 6 -script -q /dev/null docker/sdk cli vendor/bin/console code:sniff:style # the entry point Phase 0 recorded -script -q /dev/null docker/sdk testing codecept build -script -q /dev/null docker/sdk testing codecept run -x Acceptance +php $UP/run-tools.php verify evaluator phpstan sniffer +php $UP/run-tools.php verify codecept-build tests --tests-args="-x Acceptance" +php $UP/compare-tool-runs.php verify # exit 1 = new findings or failing tests against the baselines script -q /dev/null docker/sdk cli npm run yves php $UP/check-tooling-alignment.php --reference .spryker-upgrade/state/reference ``` @@ -431,8 +442,10 @@ Read [references/verification.md](references/verification.md) before the first o - **Sniffer:** auto-fix the PHP files the upgrade changed first (`-f`), then compare with the sniffer baseline. A new violation blocks, like a PHPStan or evaluator regression. - Tests: compare per suite with the test baseline, with the pinned invocation. -- A tool's baseline is its Phase 1.2 re-take (`*-post-tooling.txt`), else its Phase 0 file; after a - deferred tooling step, the Phase 0 findings plus the findings from rules new in the tool version. +- A tool's baseline is its Phase 1.2 re-take (`*-post-tooling.txt`), else its Phase 0 file; + `compare-tool-runs.php` takes them in that order. After a deferred tooling step the baseline is the + Phase 0 findings plus the findings from rules new in the tool version: compare with + `--baseline phase0` and take those tool findings out of its list. ## Phase 5.5 — The full suite against the final code, in the real environment @@ -440,8 +453,8 @@ Until the suite has run in the booted environment against the final code, it has upgrade. Run it after Phase 5's regeneration, never before. ```bash -script -q /dev/null docker/sdk testing codecept build -script -q /dev/null docker/sdk testing codecept run 2>&1 | tee .spryker-upgrade/state/codecept-final.txt +php $UP/run-tools.php final codecept-build tests +php $UP/compare-tool-runs.php final tests ``` Compare per suite with the test baseline (as in Phase 5) and classify every failure before fixing as diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/references/tooling-and-docker-sdk.md b/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/references/tooling-and-docker-sdk.md index ea4d641..7c58a40 100644 --- a/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/references/tooling-and-docker-sdk.md +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/references/tooling-and-docker-sdk.md @@ -92,14 +92,14 @@ exactly these packages. upgrade damage. The re-takes go to `*-post-tooling.txt`; the Phase 0 files stay as they are: ```bash - script -q /dev/null docker/sdk cli php -d memory_limit=2048M vendor/bin/phpstan analyze -c phpstan.neon src/ -l 6 2>&1 | tee .spryker-upgrade/state/phpstan-post-tooling.txt - script -q /dev/null docker/sdk cli vendor/bin/console code:sniff:style 2>&1 | tee .spryker-upgrade/state/sniff-post-tooling.txt - script -q /dev/null docker/sdk cli vendor/bin/evaluator evaluate 2>&1 | tee .spryker-upgrade/state/evaluator-post-tooling.txt + php $UP/run-tools.php post-tooling phpstan sniffer evaluator ``` When `codeception/*` or `phpunit/phpunit` moved, re-take the tests as well, with the exact - invocation Phase 0 pinned, into `codecept-post-tooling.txt`. Use the project's own sniffer entry - point if it has one (Phase 0 recorded which). Then `php $UP/check-baselines.php` must exit 0 again: + invocation Phase 0 pinned, into `codecept-post-tooling.txt`: + `php $UP/run-tools.php post-tooling codecept-build tests --tests-args=--no-exit`. The runner uses + the sniffer entry point and the environment variables Phase 0 pinned. Then + `php $UP/check-baselines.php` must exit 0 again: it checks each `*-post-tooling.txt` that exists for a real result. From here on a tool's baseline is its `*-post-tooling.txt` file (after a deferred tooling step: see the next section). @@ -114,10 +114,11 @@ New tooling can require versions of shared dependencies (`symfony/*`, `nikic/php 3. Directly after Phase 2 — before Phase 3 and before any lane edits a file — do the tooling step above as its own commit, with the re-takes into the `*-post-tooling.txt` files. The Phase 0 files stay unchanged. -4. Those re-takes run on upgraded code, so they mix two causes. Compare each with its Phase 0 file: - a finding whose rule or error identifier is new in the tool version is a tool finding; every other - new finding is Phase 3 upgrade damage. The baseline for the rest of the upgrade is the Phase 0 - findings plus only the tool findings; list those tool findings in the report. +4. Those re-takes run on upgraded code, so they mix two causes. Compare each with its Phase 0 file + (`php $UP/compare-tool-runs.php post-tooling` lists what is new against it): a finding whose + rule or error identifier is new in the tool version is a tool finding; every other new finding + is Phase 3 upgrade damage. The baseline for the rest of the upgrade is the Phase 0 findings plus + only the tool findings; list those tool findings in the report. 5. Say in the report that the tooling moved after Phase 2 and why, and which image the re-takes ran on when the image tag was deferred too. diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/references/verification.md b/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/references/verification.md index dfad2bc..b5bec6e 100644 --- a/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/references/verification.md +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/references/verification.md @@ -42,7 +42,8 @@ script). Read `console code:sniff:style --help` for how it takes a path or modul `git diff --name-only --diff-filter=AM "$(cat .spryker-upgrade/state/base-ref)" -- '*.php'`. 2. Auto-fix those files first (`code:sniff:style -f `, or `phpcbf `), and review the fixer's diff — it is part of the upgrade diff. -3. Run the sniffer over the same scope Phase 0 used and compare with the sniffer baseline +3. Run the sniffer over the same scope Phase 0 used (`run-tools.php` runs the pinned entry point) + and compare with the sniffer baseline with `compare-tool-runs.php` (`sniff-post-tooling.txt` when Phase 1.2 re-took it, else `sniff-baseline.txt`; after a deferred tooling step, the Phase 0 findings plus the new-rule findings). A violation that is not in the baseline blocks, like a PHPStan regression; fix it by hand. Never add an ignore rule or exclude a @@ -51,7 +52,8 @@ script). Read `console code:sniff:style --help` for how it takes a path or modul ### Comparing the test run with the baseline Compare per suite against the test baseline — `codecept-post-tooling.txt` when Phase 1.2 re-took it, -else `codecept-baseline.txt` — with the exact invocation Phase 0 pinned. A test that was red in the +else `codecept-baseline.txt` — with the exact invocation Phase 0 pinned. `compare-tool-runs.php` +lists, per suite, the tests that fail now and did not fail in the baseline. A test that was red in the baseline and is still red is not upgrade damage — list it under "Tests already red before the upgrade". A test that was green and is now red is classified in Phase 5.5 (app damage, harness damage or environment noise). diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/check-baselines.php b/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/check-baselines.php index 2f67c8f..798f6b7 100644 --- a/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/check-baselines.php +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/check-baselines.php @@ -6,7 +6,7 @@ * * Every "after" check of the upgrade is compared against a "before" run. Without the baseline a new * failure cannot be told apart from a pre-existing one, so the upgrade does not start until all of - * them exist. `2>&1 | tee` creates the file even when the command failed, so each file is also + * them exist. run-tools.php writes the file also when the tool did not run, so each file is also * checked for its tool's result line. The Phase 1.2 re-takes (`*-post-tooling.txt`) are checked the * same way when they exist. * @@ -24,45 +24,32 @@ error_reporting(E_ALL & ~E_DEPRECATED); +require_once __DIR__ . '/tool-output.php'; + const BL_REQUIRED = [ 'base-ref' => 'php $UP/check-added-comments.php --record-base', - 'codecept-baseline.txt' => 'full codecept run output before the upgrade', - 'phpstan-baseline-run.txt' => 'phpstan analyse output before the upgrade', - 'sniff-baseline.txt' => 'code sniffer output before the upgrade', - 'evaluator-baseline.txt' => 'spryker-sdk/evaluator output before the upgrade', + 'codecept-baseline.txt' => 'php $UP/run-tools.php baseline codecept-build tests --tests-args=--no-exit', + 'phpstan-baseline-run.txt' => 'php $UP/run-tools.php baseline phpstan', + 'sniff-baseline.txt' => 'php $UP/run-tools.php baseline sniffer', + 'evaluator-baseline.txt' => 'php $UP/run-tools.php baseline evaluator', 'backoffice-smoke-baseline.json' => 'php $UP/backoffice-smoke.php --url --baseline', 'constant-overrides-baseline.json' => 'php $UP/check-constant-overrides.php --snapshot', 'storage-search-counts-before.json' => 'cp $UP/storage-search-counts.php .spryker-upgrade/state/ && docker/sdk cli php .spryker-upgrade/state/storage-search-counts.php --snapshot before', ]; const BL_POST_TOOLING = [ - 'codecept-post-tooling.txt' => 'codecept run output after the tooling step', - 'phpstan-post-tooling.txt' => 'phpstan analyse output after the tooling step', - 'sniff-post-tooling.txt' => 'code sniffer output after the tooling step', - 'evaluator-post-tooling.txt' => 'spryker-sdk/evaluator output after the tooling step', + 'codecept-post-tooling.txt' => 'php $UP/run-tools.php post-tooling codecept-build tests --tests-args=--no-exit', + 'phpstan-post-tooling.txt' => 'php $UP/run-tools.php post-tooling phpstan', + 'sniff-post-tooling.txt' => 'php $UP/run-tools.php post-tooling sniffer', + 'evaluator-post-tooling.txt' => 'php $UP/run-tools.php post-tooling evaluator', ]; -const BL_TOOL_FAILURE = '/is not defined|There are no commands defined|Could not open input file|command not found' - . '|No such file or directory|Error response from daemon|is not running|Fatal error|Uncaught|Usage:|Unknown option' - . '|option does not exist|Permission denied/i'; - -/** - * The file's text without ANSI escape sequences, carriage returns and other control characters. - */ -function bl_plain_text(string $contents): string -{ - $text = (string)preg_replace('/\e\[[0-9;?]*[ -\/]*[@-~]|\e[()][A-Z0-9]|\e[=>]/', '', $contents); - $text = str_replace("\r", "\n", $text); - - return (string)preg_replace('/[\x00-\x08\x0B-\x1F\x7F]/', '', $text); -} - /** * The reason a baseline file holds no real result of its tool, or null when it does. */ function bl_content_problem(string $file, string $contents): ?string { - $text = bl_plain_text($contents); + $text = to_plain_text($contents); if (trim($text) === '') { return 'empty'; } @@ -87,30 +74,8 @@ function bl_content_problem(string $file, string $contents): ?string return (int)($decoded['totalRows'] ?? 0) > 0 ? null : 'no rows: the environment held no published data (boot with --data, drain the queues)'; } - $tool = explode('-', $file)[0]; - if ($tool === 'codecept') { - return preg_match('/\bOK \(\d+ tests?|\bTests: \d+|FAILURES!|ERRORS!/', $text) === 1 - ? null - : 'no codecept summary line (`OK (`, `Tests:`, `FAILURES!`)'; - } - if ($tool === 'phpstan') { - return preg_match('/\[OK\]|Found \d+ (?:\S+ )?errors?/', $text) === 1 - ? null - : 'no PHPStan result line (`[OK] No errors` or `Found N errors`)'; - } - $resultPattern = $tool === 'sniff' - ? '/FOUND \d+ ERRORS?|^FILE: |Time: |\d+ \/ \d+ \(\d+%\)/m' - : '/Success!|Read more: |^={5,}\s*$|^\s*\{"/m'; - if (preg_match($resultPattern, $text) === 1) { - return null; - } - foreach (preg_split('/\n/', $text) ?: [] as $row) { - if (preg_match(BL_TOOL_FAILURE, $row) === 1) { - return 'tool error instead of a result: ' . trim($row); - } - } - return null; + return to_result_problem(explode('-', $file)[0], $contents); } /** diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/compare-tool-runs.php b/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/compare-tool-runs.php new file mode 100644 index 0000000..51991f3 --- /dev/null +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/compare-tool-runs.php @@ -0,0 +1,267 @@ +-post-tooling.txt`) when it exists, else + * its Phase 0 file (phpstan-baseline-run.txt, sniff-baseline.txt, evaluator-baseline.txt, + * codecept-baseline.txt). `--baseline phase0` always takes the Phase 0 file; the post-tooling run is + * always compared with the Phase 0 files. + * + * Usage (from the project root): + * php compare-tool-runs.php [...] [--baseline phase0] [--limit N] + * + * the run name given to run-tools.php (detect, verify, final, post-tooling, ...). + * phpstan, sniffer, evaluator, tests; default: every tool with a log of the run. + * + * New findings: PHPStan errors and sniffer violations by file and message (line numbers ignored), + * evaluator violations by checker, message and target, and tests that fail now and did not fail in + * the baseline, per suite. A suite of the baseline that has no result now counts as new too. + * Standard output: one verdict line per tool, then at most --limit (default 10) new findings per + * tool. The full lists go to tool-comparison-.json in the state directory. + * + * Exit codes: 0 no regression; 1 a regression, or a tool of the run without a result; 2 usage error, + * a missing log of the run, or a missing baseline or a baseline without a result. + */ + +declare(strict_types=1); + +require_once __DIR__ . '/bootstrap.php'; +require_once __DIR__ . '/tool-output.php'; +require_once __DIR__ . '/run-tools.php'; + +const CT_TOOLS = ['phpstan', 'sniffer', 'evaluator', 'tests']; +const CT_USAGE = "Usage: php compare-tool-runs.php [phpstan|sniffer|evaluator|tests]... [--baseline phase0] [--limit N]\n"; + +/** + * Entries of $after that are not in $before, counted: an error that occurs twice now and once in the + * baseline is new once. + * + * @param list $before + * @param list $after + * + * @return list + */ +function ct_new_entries(array $before, array $after): array +{ + $remaining = array_count_values($before); + $new = []; + foreach ($after as $entry) { + if (($remaining[$entry] ?? 0) > 0) { + $remaining[$entry]--; + continue; + } + $new[] = $entry; + } + + return $new; +} + +/** + * The baseline file of a tool, or null when neither the post-tooling nor the Phase 0 file exists. + */ +function ct_baseline_file(string $stateDir, string $tool, string $run, bool $phase0Only): ?string +{ + $phase0 = rt_log_name($tool, 'baseline'); + $postTooling = rt_log_name($tool, 'post-tooling'); + if (!$phase0Only && $run !== 'post-tooling' && is_file($stateDir . '/' . $postTooling)) { + return $postTooling; + } + + return is_file($stateDir . '/' . $phase0) ? $phase0 : null; +} + +/** + * Count and findings of one tool output; findings are null when the output gives a count only. + * + * @return array{count: ?int, findings: ?list} + */ +function ct_measure(string $tool, string $text): array +{ + return match ($tool) { + 'phpstan' => ['count' => to_phpstan_count($text), 'findings' => to_phpstan_errors($text)], + 'sniffer' => ['count' => to_sniff_count($text), 'findings' => to_sniff_violations($text)], + 'evaluator' => (static function (?array $findings): array { + return ['count' => $findings === null ? null : count($findings), 'findings' => $findings]; + })(to_evaluator_findings($text)), + default => ['count' => to_codecept_counts($text)['failed'], 'findings' => null], + }; +} + +/** + * The failing tests per suite, as ": "; the failure list when the output has no result + * lines. + * + * @return array{failing: list, suites: list} + */ +function ct_failing_tests(string $text): array +{ + $suites = to_codecept_suites($text); + if ($suites === []) { + return ['failing' => to_codecept_summary($text)['failing'], 'suites' => []]; + } + $failing = []; + foreach ($suites as $name => $suite) { + foreach ($suite['failed'] as $test) { + $failing[] = $name . ': ' . $test; + } + } + + return ['failing' => $failing, 'suites' => array_keys($suites)]; +} + +/** + * The comparison of one tool. + * + * @return array{verdict: string, line: string, new: list, baseline: string, log: string} + */ +function ct_compare_tool(string $tool, string $baselineFile, string $baselineContents, string $logFile, string $logContents): array +{ + $unit = ['phpstan' => 'error(s)', 'sniffer' => 'violation(s)', 'evaluator' => 'finding(s)', 'tests' => 'failed test(s)'][$tool]; + $before = to_plain_text($baselineContents); + $after = to_plain_text((string)preg_replace('/\nexit \d+\s*$/', "\n", $logContents)); + $resultTool = ['sniffer' => 'sniff', 'tests' => 'codecept'][$tool] ?? $tool; + $base = ['baseline' => $baselineFile, 'log' => $logFile, 'new' => []]; + $afterProblem = to_result_problem($resultTool, $after); + if ($afterProblem !== null) { + return $base + ['verdict' => 'NO RESULT', 'line' => "$logFile: $afterProblem"]; + } + + if ($tool === 'tests') { + $old = ct_failing_tests($before); + $now = ct_failing_tests($after); + $new = ct_new_entries($old['failing'], $now['failing']); + $missingSuites = $now['suites'] === [] ? [] : array_values(array_diff($old['suites'], $now['suites'])); + foreach ($missingSuites as $suite) { + $new[] = "$suite: suite has no result in this run"; + } + $oldSummary = to_codecept_summary($before); + $nowSummary = to_codecept_summary($after); + $grew = $new === [] && $now['failing'] === [] && $oldSummary['total'] !== null && (int)$nowSummary['total'] > $oldSummary['total']; + $counts = to_codecept_counts($after); + $line = sprintf('%s tests, %s failed; baseline %s failed (%s)', $counts['tests'] ?? '?', $counts['failed'] ?? '?', to_codecept_counts($before)['failed'] ?? '?', $baselineFile); + if ($grew) { + $new[] = sprintf('failures grew from %d to %d (no test names in the output)', $oldSummary['total'], $nowSummary['total']); + } + + return ['verdict' => $new === [] ? 'ok' : 'REGRESSION', 'line' => $line . ($new === [] ? '' : sprintf('; %d new', count($new))), 'new' => $new] + $base; + } + + $old = ct_measure($tool, $before); + $now = ct_measure($tool, $after); + $new = ct_new_entries($old['findings'] ?? [], $now['findings'] ?? []); + if ($new === [] && $old['count'] !== null && $now['count'] !== null && $now['count'] > $old['count']) { + $new[] = sprintf('%d %s more than the baseline (no readable list in the output)', $now['count'] - $old['count'], $unit); + } + $line = sprintf('%s %s; baseline %s (%s)', $now['count'] ?? '?', $unit, $old['count'] ?? '?', $baselineFile); + + return ['verdict' => $new === [] ? 'ok' : 'REGRESSION', 'line' => $line . ($new === [] ? '' : sprintf('; %d new', count($new))), 'new' => $new] + $base; +} + +function ct_main(array $argv): int +{ + $positional = []; + $phase0Only = false; + $limit = 10; + $args = array_slice($argv, 1); + for ($i = 0; $i < count($args); $i++) { + $arg = $args[$i]; + if ($arg === '--baseline' || str_starts_with($arg, '--baseline=')) { + $value = $arg === '--baseline' ? ($args[++$i] ?? '') : substr($arg, 11); + if ($value !== 'phase0') { + fwrite(STDERR, "--baseline takes phase0\n" . CT_USAGE); + + return 2; + } + $phase0Only = true; + } elseif ($arg === '--limit' || str_starts_with($arg, '--limit=')) { + $value = $arg === '--limit' ? ($args[++$i] ?? '') : substr($arg, 8); + if (!ctype_digit($value)) { + fwrite(STDERR, "--limit takes a number\n" . CT_USAGE); + + return 2; + } + $limit = (int)$value; + } elseif (str_starts_with($arg, '--')) { + fwrite(STDERR, "Unknown option: $arg\n" . CT_USAGE); + + return 2; + } else { + $positional[] = $arg; + } + } + $run = array_shift($positional); + if ($run === null || !preg_match('/^[a-z0-9][a-z0-9-]*$/', $run) || $run === 'baseline') { + fwrite(STDERR, "Name the run to compare (not the baseline).\n" . CT_USAGE); + + return 2; + } + foreach ($positional as $tool) { + if (!in_array($tool, CT_TOOLS, true)) { + fwrite(STDERR, "Unknown tool: $tool\n" . CT_USAGE); + + return 2; + } + } + + $root = spryker_upgrade_project_root(); + $stateDir = spryker_upgrade_state_dir($root); + $tools = $positional !== [] + ? array_values(array_unique($positional)) + : array_values(array_filter(CT_TOOLS, static fn (string $tool): bool => is_file($stateDir . '/' . rt_log_name($tool, $run)))); + if ($tools === []) { + fwrite(STDERR, "No log of the run \"$run\" in " . spryker_upgrade_rel($stateDir, $root) . ": run run-tools.php $run first.\n"); + + return 2; + } + + $results = []; + $usage = []; + foreach ($tools as $tool) { + $logName = rt_log_name($tool, $run); + if (!is_file($stateDir . '/' . $logName)) { + $usage[] = "$tool: no $logName (run run-tools.php $run $tool first)"; + continue; + } + $baselineName = ct_baseline_file($stateDir, $tool, $run, $phase0Only); + if ($baselineName === null) { + $usage[] = "$tool: no baseline (" . rt_log_name($tool, 'baseline') . ')'; + continue; + } + $baselineContents = (string)file_get_contents($stateDir . '/' . $baselineName); + $problem = to_result_problem(['sniffer' => 'sniff', 'tests' => 'codecept'][$tool] ?? $tool, (string)preg_replace('/\nexit \d+\s*$/', "\n", $baselineContents)); + if ($problem !== null) { + $usage[] = "$tool: the baseline $baselineName holds no result ($problem)"; + continue; + } + $results[$tool] = ct_compare_tool($tool, $baselineName, $baselineContents, $logName, (string)file_get_contents($stateDir . '/' . $logName)); + } + if ($usage !== []) { + fwrite(STDERR, implode("\n", $usage) . "\n"); + + return 2; + } + + $reportFile = $stateDir . '/tool-comparison-' . $run . '.json'; + file_put_contents($reportFile, json_encode(['run' => $run, 'createdAt' => date('c'), 'tools' => $results], JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) . "\n"); + + $failing = 0; + foreach ($results as $tool => $result) { + $failing += $result['verdict'] === 'ok' ? 0 : 1; + fwrite(STDOUT, sprintf("%-10s %-10s %s\n", $tool, $result['verdict'], $result['line'])); + foreach (array_slice($result['new'], 0, $limit) as $entry) { + fwrite(STDOUT, " + $entry\n"); + } + if (count($result['new']) > $limit) { + fwrite(STDOUT, sprintf(" (%d more in the report)\n", count($result['new']) - $limit)); + } + } + fwrite(STDOUT, 'Full report: ' . spryker_upgrade_rel($reportFile, $root) . "\n"); + + return $failing === 0 ? 0 : 1; +} + +if (realpath($argv[0] ?? '') === __FILE__) { + exit(ct_main($argv)); +} diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/run-tools.php b/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/run-tools.php new file mode 100644 index 0000000..6353fde --- /dev/null +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/run-tools.php @@ -0,0 +1,449 @@ + ... [--tests-args ""] + * [--sniffer ""] [--env NAME=VALUE]... [--codecept-options ""]... + * [--pin-dir ] + * + * baseline, post-tooling, detect, verify, final, after, or another lower-case name. + * phpstan, sniffer, evaluator, codecept-build, tests. + * + * Commands (each wrapped in `script` for a pseudo-terminal: `script -q /dev/null ` on macOS + * and BSD, `script -q -e -c "" /dev/null` on Linux): + * phpstan docker/sdk cli php -d memory_limit=2048M vendor/bin/phpstan analyze -c phpstan.neon src/ -l 6 + * sniffer docker/sdk cli + * evaluator docker/sdk cli vendor/bin/evaluator evaluate + * codecept-build docker/sdk testing codecept build + * tests docker/sdk testing codecept run + * + * A project that runs several test configurations names each with its own --codecept-options + * (`--codecept-options "-c codeception.functional.yml" --codecept-options "-c codeception.api.yml"`). + * The tests tool then runs `codecept run` once per configuration, in that order, with the same tests + * arguments, into one log. A configuration that did not start makes the tests tool "did not run". + * + * Output files in the state directory (SPRYKER_UPGRADE_STATE_DIR, default .spryker-upgrade/state): + * phpstan-.txt (phpstan-baseline-run.txt for the baseline), sniff-.txt, + * evaluator-.txt, codecept-build-.txt, codecept-.txt. Each file ends with + * `exit `. tool-runs-.json holds the commands, exit codes, results, the tests per suite + * and the names of the failing tests of the latest run of each tool; it is written after each tool. + * + * The pinned invocation: the baseline run writes tool-invocation.json (sniffer entry point and how it + * was chosen, environment variables from --env, codecept options per configuration); a repeated + * baseline run keeps each value it is not given. Every other run reads it from + * --pin-dir (default: the state directory) and uses it; --sniffer, --env or --codecept-options that + * differ from it are a usage error. Without --sniffer the baseline detects the entry point: + * `vendor/bin/console code:sniff:style` when spryker/development is installed, else `vendor/bin/phpcs` + * with a phpcs.xml(.dist), else `composer cs-check` when composer.json has that script. + * + * Standard output: one line per tool with its exit code, its result and its log file; a tool that did + * not start is reported as "did not run". Exit codes: 0 every tool ran, 1 a tool did not run, 2 usage + * error or no pinned invocation. + */ + +declare(strict_types=1); + +require_once __DIR__ . '/bootstrap.php'; +require_once __DIR__ . '/tool-output.php'; + +const RT_TOOLS = ['phpstan', 'sniffer', 'evaluator', 'codecept-build', 'tests']; +const RT_PIN_FILE = 'tool-invocation.json'; +const RT_USAGE = "Usage: php run-tools.php ... [--tests-args \"\"] [--sniffer \"\"] [--env NAME=VALUE]... [--codecept-options \"\"]... [--pin-dir ]\n" + . " : phpstan, sniffer, evaluator, codecept-build, tests\n"; + +/** + * The log file of a tool in a run. + */ +function rt_log_name(string $tool, string $run): string +{ + return match ($tool) { + 'phpstan' => $run === 'baseline' ? 'phpstan-baseline-run.txt' : "phpstan-$run.txt", + 'sniffer' => "sniff-$run.txt", + 'evaluator' => "evaluator-$run.txt", + 'codecept-build' => "codecept-build-$run.txt", + default => "codecept-$run.txt", + }; +} + +/** + * Split a command line into words: single and double quotes group, no shell expansion. + * + * @return list + */ +function rt_words(string $line): array +{ + preg_match_all('/"((?:[^"\\\\]|\\\\.)*)"|\'([^\']*)\'|(\S+)/', $line, $m, PREG_SET_ORDER); + + return array_map(static fn (array $hit): string => match (true) { + ($hit[3] ?? '') !== '' => $hit[3], + ($hit[2] ?? '') !== '' => $hit[2], + default => stripcslashes($hit[1]), + }, $m); +} + +/** + * The sniffer entry point and how it was chosen. + * + * @return array{0: string, 1: string} + */ +function rt_detect_sniffer(string $root): array +{ + if (is_dir($root . '/vendor/spryker/development')) { + return ['vendor/bin/console code:sniff:style', 'detected: spryker/development provides code:sniff:style']; + } + foreach (['phpcs.xml', 'phpcs.xml.dist'] as $config) { + if (is_file($root . '/' . $config)) { + return ['vendor/bin/phpcs', "detected: $config"]; + } + } + $composer = json_decode((string)@file_get_contents($root . '/composer.json'), true); + if (isset($composer['scripts']['cs-check'])) { + return ['composer cs-check', 'detected: composer.json script cs-check']; + } + + return ['vendor/bin/console code:sniff:style', 'default: no sniffer setup found']; +} + +/** + * The codecept options of each test configuration: one entry per `codecept run`. A project with one + * configuration has one entry, which is empty when it needs no options. + * + * @return list + */ +function rt_option_sets(mixed $value): array +{ + $sets = is_array($value) ? array_values(array_map('strval', $value)) : (is_string($value) ? [$value] : []); + + return $sets === [] ? [''] : $sets; +} + +/** + * The command of a tool, without the pseudo-terminal wrapper. $codeceptOptions are the options of + * one test configuration. + * + * @param array{sniffer: string} $pin + * + * @return list + */ +function rt_tool_command(string $tool, array $pin, string $testsArgs, string $codeceptOptions = ''): array +{ + return match ($tool) { + 'phpstan' => ['docker/sdk', 'cli', 'php', '-d', 'memory_limit=2048M', 'vendor/bin/phpstan', 'analyze', '-c', 'phpstan.neon', 'src/', '-l', '6'], + 'sniffer' => array_merge(['docker/sdk', 'cli'], rt_words($pin['sniffer'])), + 'evaluator' => ['docker/sdk', 'cli', 'vendor/bin/evaluator', 'evaluate'], + 'codecept-build' => ['docker/sdk', 'testing', 'codecept', 'build'], + default => array_merge(['docker/sdk', 'testing', 'codecept', 'run'], rt_words($codeceptOptions), rt_words($testsArgs)), + }; +} + +/** + * The command inside the pseudo-terminal wrapper of the operating system. + * + * @param list $command + * + * @return list + */ +function rt_wrap(array $command, string $osFamily): array +{ + if ($osFamily === 'Linux') { + return ['script', '-q', '-e', '-c', implode(' ', array_map('escapeshellarg', $command)), '/dev/null']; + } + + return array_merge(['script', '-q', '/dev/null'], $command); +} + +/** + * Run a command with its output into $logFile; append `exit `. + * + * @param list $command + * @param array $env + */ +function rt_execute(array $command, string $root, array $env, string $logFile): int +{ + $log = fopen($logFile, 'w'); + if ($log === false) { + return 127; + } + $process = @proc_open($command, [0 => ['file', '/dev/null', 'r'], 1 => $log, 2 => $log], $pipes, $root, array_merge(getenv(), $env)); + if (!is_resource($process)) { + fwrite($log, "could not start: " . $command[0] . "\n"); + $code = 127; + } else { + $code = proc_close($process); + } + fwrite($log, "exit $code\n"); + fclose($log); + + return $code; +} + +/** + * Run `codecept run` once per test configuration, all into $logFile. With more than one + * configuration each part starts with a `==> ` line and ends with `==> exit `; the + * file ends with `exit `. + * + * @param list> $commands one command per configuration, without the wrapper + * @param array $env + * + * @return array{0: int, 1: list} the highest exit code, and one ": " entry + * per configuration that did not start or gave no result + */ +function rt_execute_tests(array $commands, string $root, array $env, string $logFile): array +{ + $highest = 0; + $notRun = []; + $combined = ''; + foreach ($commands as $command) { + $partFile = $logFile . '.part'; + $code = rt_execute(rt_wrap($command, PHP_OS_FAMILY), $root, $env, $partFile); + $part = (string)preg_replace('/\nexit \d+\s*$/', "\n", (string)file_get_contents($partFile)); + @unlink($partFile); + $highest = max($highest, $code); + $problem = $code === 126 || $code === 127 ? "exit $code" : to_result_problem('codecept', $part); + if ($problem !== null) { + $notRun[] = implode(' ', array_slice($command, 2)) . ': ' . (to_start_failure(to_plain_text($part)) ?? $problem); + } + $combined .= count($commands) > 1 + ? '==> ' . implode(' ', $command) . "\n" . $part . "==> exit $code\n" + : $part; + } + file_put_contents($logFile, $combined . "exit $highest\n"); + + return [$highest, $notRun]; +} + +/** + * The result of a tool from its log: did it run, and what did it find. + * + * @return array{ran: bool, result: string, counts?: array, suites?: array, failedTests?: array>} + */ +function rt_result(string $tool, string $contents, int $exitCode): array +{ + $text = to_plain_text($contents); + $startFailure = to_start_failure($text); + if ($exitCode === 126 || $exitCode === 127) { + return ['ran' => false, 'result' => 'did not run: ' . ($startFailure ?? "exit $exitCode")]; + } + if ($tool === 'codecept-build') { + if ($exitCode === 0) { + return ['ran' => true, 'result' => 'built']; + } + + return $startFailure !== null + ? ['ran' => false, 'result' => 'did not run: ' . $startFailure] + : ['ran' => true, 'result' => 'failed']; + } + $problem = to_result_problem(match ($tool) { + 'sniffer' => 'sniff', + 'tests' => 'codecept', + default => $tool, + }, (string)preg_replace('/\nexit \d+\s*$/', "\n", $contents)); + if ($problem !== null) { + return ['ran' => false, 'result' => 'did not run: ' . ($startFailure ?? $problem)]; + } + if ($tool === 'phpstan') { + $count = to_phpstan_count($text); + + return ['ran' => true, 'result' => sprintf('%d error(s)', (int)$count), 'counts' => ['errors' => $count]]; + } + if ($tool === 'sniffer') { + $count = to_sniff_count($text); + + return ['ran' => true, 'result' => sprintf('%d violation(s)', (int)$count), 'counts' => ['violations' => $count]]; + } + if ($tool === 'evaluator') { + $findings = to_evaluator_findings($text) ?? []; + + return ['ran' => true, 'result' => sprintf('%d finding(s)', count($findings)), 'counts' => ['findings' => count($findings)]]; + } + $counts = to_codecept_counts($text); + $suites = []; + $failedTests = []; + foreach (to_codecept_suites($text) as $name => $suite) { + $suites[$name] = ['passed' => count($suite['passed']), 'failed' => count($suite['failed']), 'skipped' => count($suite['skipped'])]; + if ($suite['failed'] !== []) { + $failedTests[$name] = $suite['failed']; + } + } + $failingSuites = array_filter($suites, static fn (array $suite): bool => $suite['failed'] > 0); + $named = array_map(static fn (string $name, array $suite): string => sprintf('%s (%d)', $name, $suite['failed']), array_keys($failingSuites), $failingSuites); + $result = sprintf( + '%s tests in %d suite(s): %s passed, %s failed, %s skipped', + $counts['tests'] ?? '?', + count($suites), + $counts['passed'] ?? '?', + $counts['failed'] ?? '?', + $counts['skipped'] ?? '?' + ); + if ($named !== []) { + $result .= '; failing suites: ' . implode(', ', array_slice($named, 0, 5)) . (count($named) > 5 ? sprintf(', +%d more', count($named) - 5) : ''); + } + + return ['ran' => true, 'result' => $result, 'counts' => $counts, 'suites' => $suites, 'failedTests' => $failedTests]; +} + +/** + * @return array{run: string, tools: list, options: array}|string the parsed + * arguments, or the usage error + */ +function rt_parse_args(array $args): array|string +{ + $positional = []; + $options = ['env' => [], 'codecept-options' => []]; + for ($i = 0; $i < count($args); $i++) { + $arg = $args[$i]; + if (!str_starts_with($arg, '--')) { + $positional[] = $arg; + continue; + } + [$name, $value] = str_contains($arg, '=') ? explode('=', substr($arg, 2), 2) : [substr($arg, 2), null]; + if (!in_array($name, ['tests-args', 'sniffer', 'env', 'codecept-options', 'pin-dir'], true)) { + return "Unknown option: --$name"; + } + if ($value === null) { + if (!isset($args[$i + 1])) { + return "--$name needs a value"; + } + $value = $args[++$i]; + } + if ($name === 'env') { + if (!preg_match('/^([A-Za-z_][A-Za-z0-9_]*)=(.*)$/s', $value, $m)) { + return "--env takes NAME=VALUE: $value"; + } + $options['env'][$m[1]] = $m[2]; + continue; + } + if ($name === 'codecept-options') { + $options['codecept-options'][] = $value; + continue; + } + $options[$name] = $value; + } + $run = array_shift($positional); + if ($run === null || !preg_match('/^[a-z0-9][a-z0-9-]*$/', $run)) { + return 'The first argument is the run name (lower-case letters, digits and dashes).'; + } + if ($positional === []) { + return 'Name at least one tool.'; + } + foreach ($positional as $tool) { + if (!in_array($tool, RT_TOOLS, true)) { + return "Unknown tool: $tool"; + } + } + + return ['run' => $run, 'tools' => array_values(array_unique($positional)), 'options' => $options]; +} + +/** + * The pinned invocation: written by the baseline run, read by every other run. + * + * @param array $options + * + * @return array{sniffer: string, snifferSource: string, env: array, codeceptOptions: list}|string + */ +function rt_pin(string $run, array $options, string $root, string $pinFile): array|string +{ + $existing = json_decode((string)@file_get_contents($pinFile), true); + if ($run === 'baseline') { + $existing = is_array($existing) && isset($existing['sniffer']) ? $existing : null; + [$sniffer, $source] = match (true) { + isset($options['sniffer']) => [$options['sniffer'], 'argument --sniffer'], + $existing !== null => [$existing['sniffer'], (string)($existing['snifferSource'] ?? '')], + default => rt_detect_sniffer($root), + }; + $pin = [ + 'sniffer' => $sniffer, + 'snifferSource' => $source, + 'env' => $options['env'] !== [] ? $options['env'] : (array)($existing['env'] ?? []), + 'codeceptOptions' => $options['codecept-options'] !== [] ? $options['codecept-options'] : rt_option_sets($existing['codeceptOptions'] ?? null), + ]; + if (!is_dir(dirname($pinFile))) { + mkdir(dirname($pinFile), 0775, true); + } + file_put_contents($pinFile, json_encode(['env' => (object)$pin['env']] + $pin + ['recordedAt' => date('c')], JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES) . "\n"); + + return $pin; + } + $pin = $existing; + if (!is_array($pin) || !isset($pin['sniffer'])) { + return "No pinned invocation in $pinFile: run the baseline first, or name its directory with --pin-dir."; + } + $pin['env'] = (array)($pin['env'] ?? []); + $pin['codeceptOptions'] = rt_option_sets($pin['codeceptOptions'] ?? null); + if (isset($options['sniffer']) && $options['sniffer'] !== $pin['sniffer']) { + return "--sniffer differs from the pinned invocation in $pinFile ({$pin['sniffer']})."; + } + if ($options['codecept-options'] !== [] && $options['codecept-options'] !== $pin['codeceptOptions']) { + return "--codecept-options differs from the pinned invocation in $pinFile (" . implode(' | ', $pin['codeceptOptions']) . ').'; + } + if ($options['env'] !== [] && $options['env'] != $pin['env']) { + return "--env differs from the pinned invocation in $pinFile."; + } + + return $pin; +} + +function rt_main(array $argv): int +{ + $parsed = rt_parse_args(array_slice($argv, 1)); + if (is_string($parsed)) { + fwrite(STDERR, $parsed . "\n" . RT_USAGE); + + return 2; + } + $root = spryker_upgrade_project_root(); + $stateDir = spryker_upgrade_state_dir($root); + $pinDir = isset($parsed['options']['pin-dir']) ? rtrim((string)$parsed['options']['pin-dir'], '/') : $stateDir; + $pin = rt_pin($parsed['run'], $parsed['options'], $root, $pinDir . '/' . RT_PIN_FILE); + if (is_string($pin)) { + fwrite(STDERR, $pin . "\n"); + + return 2; + } + + $testsArgs = (string)($parsed['options']['tests-args'] ?? ''); + $runsFile = $stateDir . '/tool-runs-' . $parsed['run'] . '.json'; + $records = (array)(json_decode((string)@file_get_contents($runsFile), true)['tools'] ?? []); + $notRun = 0; + foreach ($parsed['tools'] as $tool) { + $logFile = $stateDir . '/' . rt_log_name($tool, $parsed['run']); + if ($tool === 'tests') { + $commands = array_map(static fn (string $set): array => rt_tool_command($tool, $pin, $testsArgs, $set), $pin['codeceptOptions']); + [$exitCode, $partsNotRun] = rt_execute_tests($commands, $root, $pin['env'], $logFile); + $result = rt_result($tool, (string)file_get_contents($logFile), $exitCode); + if ($partsNotRun !== [] && $result['ran']) { + $result['ran'] = false; + $result['result'] .= '; did not run: ' . implode('; ', $partsNotRun); + } + } else { + $commands = [rt_tool_command($tool, $pin, $testsArgs)]; + $exitCode = rt_execute(rt_wrap($commands[0], PHP_OS_FAMILY), $root, $pin['env'], $logFile); + $result = rt_result($tool, (string)file_get_contents($logFile), $exitCode); + } + $notRun += $result['ran'] ? 0 : 1; + $log = spryker_upgrade_rel($logFile, $root); + $records[$tool] = ['command' => implode(' && ', array_map(static fn (array $command): string => implode(' ', $command), $commands)), 'exitCode' => $exitCode, 'log' => $log] + $result; + fwrite(STDOUT, sprintf("%-15s exit %-3d %s %s\n", $tool, $exitCode, $result['result'], $log)); + // Written after each tool, so a run that is stopped keeps the tools that finished. + file_put_contents($runsFile, json_encode([ + 'run' => $parsed['run'], + 'createdAt' => date('c'), + 'invocation' => $pin, + 'tools' => $records, + ], JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) . "\n"); + } + + if ($parsed['run'] === 'baseline') { + fwrite(STDOUT, sprintf("Pinned invocation: %s (sniffer %s)\n", spryker_upgrade_rel($pinDir . '/' . RT_PIN_FILE, $root), $pin['snifferSource'])); + } + + return $notRun === 0 ? 0 : 1; +} + +if (realpath($argv[0] ?? '') === __FILE__) { + exit(rt_main($argv)); +} diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/tool-output.php b/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/tool-output.php new file mode 100644 index 0000000..2778c38 --- /dev/null +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/tool-output.php @@ -0,0 +1,386 @@ +]|\^D\x08\x08/', '', $contents); + $text = str_replace(["\r\n", "\r"], "\n", $text); + + return (string)preg_replace('/[\x00-\x08\x0B-\x1F\x7F]/', '', $text); +} + +/** + * The reason a tool output holds no real result of its tool, or null when it does. + * $tool: phpstan, sniff, codecept; any other name is checked as evaluator output. + */ +function to_result_problem(string $tool, string $contents): ?string +{ + $text = to_plain_text($contents); + if (trim($text) === '') { + return 'empty'; + } + if ($tool === 'codecept') { + return preg_match('/\bOK \(\d+ tests?|\bTests: \d+|FAILURES!|ERRORS!/', $text) === 1 + ? null + : 'no codecept summary line (`OK (`, `Tests:`, `FAILURES!`)'; + } + if ($tool === 'phpstan') { + return preg_match('/\[OK\]|Found \d+ (?:\S+ )?errors?/', $text) === 1 + ? null + : 'no PHPStan result line (`[OK] No errors` or `Found N errors`)'; + } + $resultPattern = $tool === 'sniff' + ? '/FOUND \d+ ERRORS?|^FILE: |Time: |\d+ \/ \d+ \(\d+%\)/m' + : '/Success!|Read more: |^={5,}\s*$|^\s*\{"/m'; + if (preg_match($resultPattern, $text) === 1) { + return null; + } + foreach (preg_split('/\n/', $text) ?: [] as $row) { + if (preg_match(TO_TOOL_FAILURE, $row) === 1) { + return 'tool error instead of a result: ' . trim($row); + } + } + + return null; +} + +/** + * The first line of the output that says the tool did not start, or null. + */ +function to_start_failure(string $text): ?string +{ + foreach (preg_split('/\n/', $text) ?: [] as $row) { + if (preg_match(TO_START_FAILURE, $row) === 1) { + return trim($row); + } + } + + return null; +} + +function to_squash(string $text): string +{ + return trim((string)preg_replace('/\s+/', ' ', $text)); +} + +function to_phpstan_count(string $text): ?int +{ + if (preg_match('/Found (\d+) (?:\S+ )?errors?/', $text, $m)) { + return (int)$m[1]; + } + + return preg_match('/\[OK\] No errors/', $text) ? 0 : null; +} + +/** + * The PHPStan errors of the table output, each as ": ", without line numbers (lines + * move between runs) and without the identifier, tip and link lines. Repeated errors stay repeated. + * + * @return list + */ +function to_phpstan_errors(string $text): array +{ + $errors = []; + $file = null; + $current = null; + $open = false; + $flush = static function () use (&$errors, &$current, &$file): void { + if ($current !== null) { + $errors[] = $file . ': ' . to_squash($current); + } + $current = null; + }; + foreach (explode("\n", $text) as $row) { + if (preg_match('/^\s*-{3,}[\s-]*$/', $row)) { + $flush(); + $open = false; + continue; + } + if (preg_match('/^\s*Line\s{2,}(\S.*?)\s*$/', $row, $m)) { + $flush(); + $file = $m[1]; + continue; + } + if (preg_match('/^\s*Error\s*$/', $row)) { + $flush(); + $file = '(no file)'; + continue; + } + if ($file === null) { + continue; + } + if (preg_match('/^\s*(?:[^\x00-\x7F]|See:|Tip:|https?:\/\/)/u', $row)) { + $open = false; + continue; + } + if ($file !== '(no file)' && preg_match('/^\s+:?\d+\s{2,}(\S.*?)\s*$/', $row, $m)) { + $flush(); + $current = $m[1]; + $open = true; + continue; + } + if ($file === '(no file)' && preg_match('/^\s+(\S.*?)\s*$/', $row, $m)) { + $flush(); + $current = $m[1]; + $open = true; + continue; + } + if ($open && $current !== null && preg_match('/^\s{4,}(\S.*?)\s*$/', $row, $m)) { + $current .= ' ' . $m[1]; + } + } + $flush(); + + return $errors; +} + +/** + * Errors plus warnings of the sniffer output: the TOTAL line, else the sum of the FOUND lines, else 0 + * when the output holds a sniffer result without findings; null when it holds no result. + */ +function to_sniff_count(string $text): ?int +{ + if (preg_match('/A TOTAL OF (\d+) ERRORS? AND (\d+) WARNINGS?/', $text, $m)) { + return (int)$m[1] + (int)$m[2]; + } + if (preg_match_all('/FOUND (\d+) ERRORS?(?: AND (\d+) WARNINGS?)?/', $text, $m, PREG_SET_ORDER)) { + return array_sum(array_map(static fn (array $hit): int => (int)$hit[1] + (int)($hit[2] ?? 0), $m)); + } + + return to_result_problem('sniff', $text) === null ? 0 : null; +} + +/** + * The sniffer violations of the full report, each as ": ", without + * line numbers. + * + * @return list + */ +function to_sniff_violations(string $text): array +{ + $violations = []; + $file = null; + $current = null; + $flush = static function () use (&$violations, &$current): void { + if ($current !== null) { + $violations[] = to_squash($current); + } + $current = null; + }; + foreach (explode("\n", $text) as $row) { + if (preg_match('/^FILE: (.+?)\s*$/', $row, $m)) { + $flush(); + $file = $m[1]; + continue; + } + if ($file !== null && preg_match('/^\s*\d+\s*\|\s*(ERROR|WARNING)\s*\|\s*(?:\[[ x]\]\s*)?(.*?)\s*$/', $row, $m)) { + $flush(); + $current = $file . ': ' . $m[1] . ' ' . $m[2]; + continue; + } + if ($current !== null && preg_match('/^\s*\|\s*\|\s*(.*?)\s*$/', $row, $m)) { + $current .= ' ' . $m[1]; + continue; + } + $flush(); + } + $flush(); + + return $violations; +} + +/** + * The evaluator findings: one entry per violation row, ": ()"; a checker + * with violations but no readable row counts as one finding "". Null when the output holds + * no evaluator result. + * + * @return list|null + */ +function to_evaluator_findings(string $text): ?array +{ + if (to_result_problem('evaluator', $text) !== null) { + return null; + } + $rows = explode("\n", $text); + $findings = []; + $checker = null; + $checkerRows = 0; + $checkerFailed = false; + $current = null; + $closeChecker = static function () use (&$findings, &$checker, &$checkerRows, &$checkerFailed, &$current): void { + if ($current !== null) { + $findings[] = $checker . ': ' . to_squash($current[0]) . ' (' . to_squash($current[1]) . ')'; + $current = null; + } + if ($checker !== null && $checkerFailed && $checkerRows === 0) { + $findings[] = $checker; + } + }; + foreach ($rows as $i => $row) { + if (preg_match('/^={3,}\s*$/', $row) && isset($rows[$i + 2]) && preg_match('/^={3,}\s*$/', $rows[$i + 2]) && trim($rows[$i + 1]) !== '') { + $closeChecker(); + $checker = trim($rows[$i + 1]); + $checkerRows = 0; + $checkerFailed = false; + continue; + } + if ($checker === null) { + continue; + } + if (str_starts_with(trim($row), 'Read more: ')) { + $checkerFailed = true; + } + if (preg_match('/^\|\s*(\d+)\s*\|\s*(.*?)\s*\|\s*(.*?)\s*\|\s*$/', $row, $m)) { + if ($current !== null) { + $findings[] = $checker . ': ' . to_squash($current[0]) . ' (' . to_squash($current[1]) . ')'; + } + $current = [$m[2], $m[3]]; + $checkerRows++; + $checkerFailed = true; + continue; + } + if ($current !== null && preg_match('/^\|\s*\|\s*(.*?)\s*\|\s*(.*?)\s*\|\s*$/', $row, $m)) { + $current[0] .= ' ' . $m[1]; + $current[1] .= ' ' . $m[2]; + continue; + } + if ($current !== null && preg_match('/^\+[-+]+\+\s*$/', $row)) { + $findings[] = $checker . ': ' . to_squash($current[0]) . ' (' . to_squash($current[1]) . ')'; + $current = null; + } + } + $closeChecker(); + + return $findings; +} + +/** + * The Codeception summary: the tests of the failure list ("1) FooTest: bar") and the error plus + * failure count of the `Tests:` line (0 for `OK (`, null without a summary line). + * + * @return array{total: ?int, failing: list} + */ +function to_codecept_summary(string $text): array +{ + $failing = []; + if (preg_match_all('/^\s*\d+\) (\S.*?)\s*$/m', $text, $m)) { + $failing = array_values(array_unique(array_map('trim', $m[1]))); + } + $total = null; + if (preg_match_all('/Tests: \d+, Assertions: \d+(?:, Errors: (\d+))?(?:, Failures: (\d+))?/', $text, $m, PREG_SET_ORDER)) { + $total = array_sum(array_map(static fn (array $hit): int => (int)($hit[1] ?? 0) + (int)($hit[2] ?? 0), $m)); + } elseif (preg_match('/\bOK \(\d+ tests?/', $text)) { + $total = 0; + } + + return ['total' => $total, 'failing' => $failing]; +} + +/** + * The tests of each suite by their result line: `✔`/`+` passed, `✖`/`x`/`E` failed, `S`/`I`/`U`/`W` + * skipped. A suite is " " when the run includes several configurations. + * + * @return array, failed: list, skipped: list}> + */ +function to_codecept_suites(string $text): array +{ + $suites = []; + $namespace = ''; + $suite = null; + foreach (explode("\n", $text) as $row) { + if (str_starts_with($row, 'Codeception PHP Testing Framework')) { + // A new `codecept run` starts: its suites do not belong to the last include namespace. + $namespace = ''; + $suite = null; + continue; + } + if (preg_match('/^\[(.+?)\]: tests from /', $row, $m)) { + $namespace = $m[1]; + continue; + } + if (preg_match('/^(\S.*?) Tests \(\d+\) -*\s*$/', $row, $m)) { + $suite = $namespace === '' ? $m[1] : $namespace . ' ' . $m[1]; + $suites[$suite] ??= ['passed' => [], 'failed' => [], 'skipped' => []]; + continue; + } + if ($suite === null) { + continue; + } + if (preg_match('/^(Time: |There (?:was|were) \d+ |FAILURES!|ERRORS!|OK \()/', $row)) { + $suite = null; + continue; + } + if (preg_match('/^(✔|✖|\+|x|E|S|I|U|W) (\S.*?)(?:\s+\(\d+(?:\.\d+)?m?s\))?\s*$/u', $row, $m)) { + $kind = match ($m[1]) { + '✔', '+' => 'passed', + '✖', 'x', 'E' => 'failed', + default => 'skipped', + }; + $suites[$suite][$kind][] = to_squash((string)preg_replace('/\s+(?:\d+x)?\[F\]\s*$/', '', $m[2])); + } + } + + return $suites; +} + +/** + * Counts of a test run: from the result lines per suite, or from the summary line when the output + * has no result lines. + * + * @return array{tests: ?int, passed: ?int, failed: ?int, skipped: ?int} + */ +function to_codecept_counts(string $text): array +{ + $suites = to_codecept_suites($text); + $counts = ['passed' => 0, 'failed' => 0, 'skipped' => 0]; + foreach ($suites as $suite) { + foreach ($counts as $kind => $count) { + $counts[$kind] = $count + count($suite[$kind]); + } + } + if (array_sum($counts) > 0) { + return ['tests' => array_sum($counts)] + $counts; + } + if (preg_match_all('/Tests: (\d+), Assertions: \d+(?:, Errors: (\d+))?(?:, Failures: (\d+))?(?:, Warnings: \d+)?(?:, Skipped: (\d+))?(?:, Incomplete: (\d+))?/', $text, $m, PREG_SET_ORDER)) { + $tests = $failed = $skipped = 0; + foreach ($m as $hit) { + $tests += (int)$hit[1]; + $failed += (int)($hit[2] ?? 0) + (int)($hit[3] ?? 0); + $skipped += (int)($hit[4] ?? 0) + (int)($hit[5] ?? 0); + } + + return ['tests' => $tests, 'passed' => $tests - $failed - $skipped, 'failed' => $failed, 'skipped' => $skipped]; + } + if (preg_match_all('/\bOK \((\d+) tests?/', $text, $m)) { + $tests = array_sum(array_map('intval', $m[1])); + + return ['tests' => $tests, 'passed' => $tests, 'failed' => 0, 'skipped' => 0]; + } + + return ['tests' => null, 'passed' => null, 'failed' => null, 'skipped' => null]; +} diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/upgrade-scripts.test.php b/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/upgrade-scripts.test.php index 6c50286..881f708 100644 --- a/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/upgrade-scripts.test.php +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/upgrade-scripts.test.php @@ -11,6 +11,7 @@ require __DIR__ . '/check-constant-overrides.php'; require __DIR__ . '/storage-search-counts.php'; require __DIR__ . '/check-performance.php'; +require __DIR__ . '/compare-tool-runs.php'; $failures = 0; $count = 0; @@ -946,6 +947,163 @@ interface BazLimitsInterface [$twoModes] = run_script('check-performance.php', ['--init', '--verify'], $perf, $perfState); check('performance: two modes in one run -> exit 2', $twoModes === 2); +// --- run-tools and compare-tool-runs --- +$phpstanTable = static fn (array $errors): string => " ------ ------------------------------------------\n Line src/Pyz/Zed/Foo/FooFacade.php\n ------ ------------------------------------------\n" + . implode('', array_map(static fn (array $e): string => sprintf(" %-6d %s\n 🪪 %s\n", $e[0], $e[1], $e[2]), $errors)) + . " ------ ------------------------------------------\n\n [ERROR] Found " . count($errors) . " error" . (count($errors) === 1 ? '' : 's') . "\n"; +$phpstanBase = $phpstanTable([[12, 'Call to an undefined method Foo::bar().', 'method.notFound']]); +$phpstanAfter = $phpstanTable([[14, 'Call to an undefined method Foo::bar().', 'method.notFound'], [30, 'Parameter #1 $x of method Foo::baz() expects int, string given.', 'argument.type']]); +$sniffReport = static fn (array $violations): string => implode('', array_map(static fn (array $v): string => "FILE: /data/{$v[0]}\n----------------------------------------------------------------------\nFOUND 1 ERROR AFFECTING 1 LINE\n----------------------------------------------------------------------\n {$v[1]} | ERROR | [x] {$v[2]}\n | | found\n----------------------------------------------------------------------\n", $violations)) . "Time: 1.2 secs; Memory: 20MB\n"; +$sniffBase = $sniffReport([['src/Pyz/Zed/Foo/FooFacade.php', 12, 'Expected 1 space after FUNCTION keyword; 0']]); +$sniffAfter = $sniffReport([['src/Pyz/Zed/Foo/FooFacade.php', 13, 'Expected 1 space after FUNCTION keyword; 0'], ['src/Pyz/Zed/Bar/BarFacade.php', 5, 'Missing doc comment']]); +$evaluatorReport = static fn (array $rows): string => "=====================\nPHP VERSION CHECKER\n=====================\n\n+---+---------------------------+---------------+\n| # | Message | Target |\n+---+---------------------------+---------------+\n" + . implode('', array_map(static fn (int $i, array $r): string => sprintf("| %d | %-25s | %-13s |\n", $i + 1, $r[0], $r[1]), array_keys($rows), $rows)) + . "+---+---------------------------+---------------+\n\nRead more: https://docs.spryker.com/evaluator\n\n=================\nDEAD CODE CHECKER\n=================\n\nNo violations found\n"; +$evaluatorBase = $evaluatorReport([['Composer PHP is 8.1', 'composer.json']]); +$evaluatorAfter = $evaluatorReport([['Composer PHP is 8.1', 'composer.json'], ['Deploy PHP is 8.0', 'deploy.yml']]); +$codeceptRun = static fn (string $barMark, int $failures): string => "Codeception PHP Testing Framework v5.1.2\n[PyzTest\\Zed\\Foo]: tests from /data/tests/PyzTest/Zed/Foo\n\n\e[1mBusiness Tests (3) ------------------------------\e[22m\n" + . "- FooFacadeTest: Calculates price\r\e[32m✔\e[39m FooFacadeTest: Calculates price (0.01s)\r\n\e[31m✖\e[39m FooFacadeTest: Rounds tax (0.02s)\r\nS FooFacadeTest: Needs search\r\n------------------------------\n" + . "[PyzTest\\Zed\\Bar]: tests from /data/tests/PyzTest/Zed/Bar\n\nBusiness Tests (1) ------\n$barMark BarFacadeTest: Reads bar (0.01s)\n------\nTime: 00:01.234, Memory: 40.00 MB\n\n" + . "There " . ($failures === 1 ? 'was 1 failure' : "were $failures failures") . ":\n1) FooFacadeTest: Rounds tax\n Test tests/PyzTest/Zed/Foo/Business/FooFacadeTest.php:testRoundsTax\n" . ($failures > 1 ? "2) BarFacadeTest: Reads bar\n" : '') + . "\nFAILURES!\nTests: 4, Assertions: 5, Failures: $failures, Skipped: 1.\n"; +$codeceptBase = $codeceptRun('✔', 1); +$codeceptAfter = $codeceptRun('✖', 2); + +check('tool output: PHPStan errors by file and message, line number and identifier left out', to_phpstan_errors($phpstanBase) === ['src/Pyz/Zed/Foo/FooFacade.php: Call to an undefined method Foo::bar().']); +check('tool output: sniffer violations with wrapped message, line number left out', to_sniff_violations($sniffBase) === ['/data/src/Pyz/Zed/Foo/FooFacade.php: ERROR Expected 1 space after FUNCTION keyword; 0 found']); +check('tool output: evaluator violation rows per checker; a checker without violations adds none', to_evaluator_findings($evaluatorBase) === ['PHP VERSION CHECKER: Composer PHP is 8.1 (composer.json)']); +$suites = to_codecept_suites(to_plain_text($codeceptBase)); +check('tool output: codecept tests per suite from the result lines, include namespace in the suite name', array_keys($suites) === ['PyzTest\\Zed\\Foo Business', 'PyzTest\\Zed\\Bar Business'] && $suites['PyzTest\\Zed\\Foo Business']['failed'] === ['FooFacadeTest: Rounds tax'] && count($suites['PyzTest\\Zed\\Foo Business']['skipped']) === 1 && $suites['PyzTest\\Zed\\Bar Business']['passed'] === ['BarFacadeTest: Reads bar']); +check('tool output: pseudo-terminal line ends (CR LF) keep the evaluator and sniffer tables readable', to_evaluator_findings(str_replace("\n", "\r\n", $evaluatorBase)) === to_evaluator_findings($evaluatorBase) && to_sniff_violations(to_plain_text(str_replace("\n", "\r\n", $sniffBase))) === to_sniff_violations($sniffBase)); +check('tool output: codecept counts from the summary line when there are no result lines', to_codecept_counts("Tests: 10, Assertions: 20, Errors: 1, Failures: 2, Skipped: 3.\n") === ['tests' => 10, 'passed' => 4, 'failed' => 3, 'skipped' => 3]); +check('run-tools: macOS and Linux pseudo-terminal wrappers', rt_wrap(['docker/sdk', 'cli', 'x y'], 'Darwin') === ['script', '-q', '/dev/null', 'docker/sdk', 'cli', 'x y'] && rt_wrap(['docker/sdk', 'cli', 'x y'], 'Linux') === ['script', '-q', '-e', '-c', "'docker/sdk' 'cli' 'x y'", '/dev/null']); +check('run-tools: log names keep the names the gates read', rt_log_name('phpstan', 'baseline') === 'phpstan-baseline-run.txt' && rt_log_name('sniffer', 'post-tooling') === 'sniff-post-tooling.txt' && rt_log_name('tests', 'final') === 'codecept-final.txt' && rt_log_name('tests', 'after') === 'codecept-after.txt'); +check('run-tools: phpstan command keeps the memory limit and the analysed paths', rt_tool_command('phpstan', ['sniffer' => 'x', 'codeceptOptions' => ''], '') === ['docker/sdk', 'cli', 'php', '-d', 'memory_limit=2048M', 'vendor/bin/phpstan', 'analyze', '-c', 'phpstan.neon', 'src/', '-l', '6']); + +$runner = $tmp . '/runner'; +$runnerState = $runner . '/.state'; +$stub = $tmp . '/stub'; +write_file($runner . '/composer.json', "{}\n"); +mkdir($runner . '/src/Pyz', 0777, true); +mkdir($runner . '/vendor/spryker/development', 0777, true); +write_file($runner . '/docker/sdk', "#!/bin/sh\necho \"\$* ENV=\${SPRYKER_TESTING_ENABLED:-}\" >> \"\$STUB_DIR/calls.log\"\ncase \"\$*\" in\n *phpstan*) key=phpstan;;\n *code:sniff:style*|*phpcs*) key=sniffer;;\n *evaluator*) key=evaluator;;\n *'codecept build'*) key=build;;\n *) key=tests;;\nesac\ncat \"\$STUB_DIR/\$key.out\" 2>/dev/null\nexit \$(cat \"\$STUB_DIR/\$key.exit\" 2>/dev/null || echo 0)\n"); +chmod($runner . '/docker/sdk', 0755); +$stubOutput = static function (string $key, string $output, int $exit) use ($stub): void { + write_file("$stub/$key.out", $output); + write_file("$stub/$key.exit", (string)$exit); +}; +$stubOutput('phpstan', " [OK] No errors\n", 0); +$stubOutput('sniffer', $sniffBase, 1); +$stubOutput('evaluator', "Error response from daemon: container cli is not running\n", 1); +$stubOutput('build', "Building Actor classes for suites: Business\n", 0); +$stubOutput('tests', $codeceptBase, 0); +$stubEnv = ['STUB_DIR' => $stub]; +[$rtCode, $rtOut] = run_script('run-tools.php', ['baseline', 'phpstan', 'sniffer', 'evaluator', 'codecept-build', 'tests', '--tests-args=--no-exit', '--env', 'SPRYKER_TESTING_ENABLED=1'], $runner, $runnerState, $stubEnv); +$rtLines = explode("\n", trim($rtOut)); +check('run-tools: exit 1 when a tool did not run', $rtCode === 1); +check('run-tools: a passing tool -> one line with exit code, result and log file', str_contains($rtLines[0] ?? '', 'phpstan') && str_contains($rtLines[0], 'exit 0') && str_contains($rtLines[0], '0 error(s)') && str_contains($rtLines[0], '.state/phpstan-baseline-run.txt')); +check('run-tools: a failing tool -> its finding count', str_contains($rtLines[1] ?? '', 'exit 1') && str_contains($rtLines[1], '1 violation(s)') && str_contains($rtLines[1], 'sniff-baseline.txt')); +check('run-tools: a tool that did not start -> "did not run" with the reason, no result', str_contains($rtLines[2] ?? '', 'did not run: Error response from daemon') && !str_contains($rtLines[2], 'finding')); +check('run-tools: red tests -> passed, failed and skipped, failing suite named', str_contains($rtLines[4] ?? '', '4 tests in 2 suite(s): 2 passed, 1 failed, 1 skipped') && str_contains($rtLines[4], 'PyzTest\\Zed\\Foo Business (1)')); +check('run-tools: no raw tool output on stdout', !str_contains($rtOut, 'Expected 1 space') && !str_contains($rtOut, 'Rounds tax')); +check('run-tools: full output in the log, ending with the exit code', str_contains((string)file_get_contents($runnerState . '/sniff-baseline.txt'), 'Expected 1 space') && preg_match('/exit 1\n$/', (string)file_get_contents($runnerState . '/sniff-baseline.txt')) === 1); +check('run-tools: check-baselines accepts the logs of tools that ran and rejects the one that did not', bl_content_problem('phpstan-baseline-run.txt', (string)file_get_contents($runnerState . '/phpstan-baseline-run.txt')) === null && bl_content_problem('codecept-baseline.txt', (string)file_get_contents($runnerState . '/codecept-baseline.txt')) === null && bl_content_problem('evaluator-baseline.txt', (string)file_get_contents($runnerState . '/evaluator-baseline.txt')) !== null); +$pinned = read_json($runnerState . '/tool-invocation.json'); +check('run-tools: the baseline pins the sniffer it detected and the environment', ($pinned['sniffer'] ?? '') === 'vendor/bin/console code:sniff:style' && str_starts_with((string)($pinned['snifferSource'] ?? ''), 'detected') && ($pinned['env'] ?? []) === ['SPRYKER_TESTING_ENABLED' => '1']); +check('run-tools: tests run with the environment and the tests arguments', str_contains((string)file_get_contents($stub . '/calls.log'), 'testing codecept run --no-exit ENV=1')); +check('run-tools: tool-runs JSON holds the tests per suite', (read_json($runnerState . '/tool-runs-baseline.json')['tools']['tests']['suites']['PyzTest\\Zed\\Bar Business']['passed'] ?? 0) === 1); +@unlink($stub . '/calls.log'); +[$rtFinal, $rtFinalOut] = run_script('run-tools.php', ['final', 'codecept-build', 'tests'], $runner, $runnerState, $stubEnv); +check('run-tools: a later run uses the pinned environment without --env', $rtFinal === 0 && str_contains((string)file_get_contents($stub . '/calls.log'), 'testing codecept run ENV=1') && is_file($runnerState . '/codecept-final.txt')); +[$rtOtherEnv] = run_script('run-tools.php', ['final', 'tests', '--env', 'SPRYKER_TESTING_ENABLED=0'], $runner, $runnerState, $stubEnv); +[$rtOtherSniffer] = run_script('run-tools.php', ['final', 'sniffer', '--sniffer', 'vendor/bin/phpcs'], $runner, $runnerState, $stubEnv); +check('run-tools: an environment or sniffer that differs from the pin -> exit 2', $rtOtherEnv === 2 && $rtOtherSniffer === 2); +[$rtNoPin, $rtNoPinOut] = run_script('run-tools.php', ['after', 'phpstan'], $runner, $tmp . '/runner-after', $stubEnv); +[$rtPinDir] = run_script('run-tools.php', ['after', 'phpstan', '--pin-dir', $runnerState], $runner, $tmp . '/runner-after', $stubEnv); +check('run-tools: no pinned invocation -> exit 2; --pin-dir reads the baseline pin', $rtNoPin === 2 && str_contains($rtNoPinOut, 'No pinned invocation') && $rtPinDir === 0 && is_file($tmp . '/runner-after/phpstan-after.txt')); +[$rtBadTool] = run_script('run-tools.php', ['baseline', 'psalm'], $runner, $runnerState, $stubEnv); +check('run-tools: unknown tool -> exit 2', $rtBadTool === 2); +rename($runner . '/docker/sdk', $runner . '/docker/sdk.off'); +[$rtNoSdk, $rtNoSdkOut] = run_script('run-tools.php', ['detect', 'phpstan'], $runner, $runnerState, $stubEnv); +rename($runner . '/docker/sdk.off', $runner . '/docker/sdk'); +check('run-tools: docker/sdk missing -> did not run, exit 1', $rtNoSdk === 1 && str_contains($rtNoSdkOut, 'did not run')); +check('run-tools: tool-runs JSON names the failing tests per suite', (read_json($runnerState . '/tool-runs-baseline.json')['tools']['tests']['failedTests'] ?? null) === ['PyzTest\\Zed\\Foo Business' => ['FooFacadeTest: Rounds tax']]); +check('run-tools: tool-runs JSON keeps the tools of an earlier call of the same run', array_keys(read_json($runnerState . '/tool-runs-final.json')['tools'] ?? []) === ['codecept-build', 'tests']); + +// Several test configurations: one `codecept run` per --codecept-options, one log. +$multi = $tmp . '/runner-multi'; +$multiState = $multi . '/.state'; +write_file($multi . '/composer.json', "{}\n"); +mkdir($multi . '/src/Pyz', 0777, true); +write_file($multi . '/docker/sdk', "#!/bin/sh\necho \"\$*\" >> \"\$STUB_DIR/multi-calls.log\"\ncase \"\$*\" in\n *codeception.api.yml*) key=tests-api;;\n *codeception.broken.yml*) key=tests-broken;;\n *) key=tests;;\nesac\ncat \"\$STUB_DIR/\$key.out\" 2>/dev/null\nexit \$(cat \"\$STUB_DIR/\$key.exit\" 2>/dev/null || echo 0)\n"); +chmod($multi . '/docker/sdk', 0755); +$stubOutput('tests-api', "Codeception PHP Testing Framework v5.1.2\n\nApi Tests (2) ------\n✔ OrdersCest: Reads orders (0.01s)\nE OrdersCest: Creates order (0.01s)\n------\nTime: 00:01.000, Memory: 40.00 MB\n\nERRORS!\nTests: 2, Assertions: 2, Errors: 1.\n", 1); +$stubOutput('tests-broken', "Error response from daemon: container testing is not running\n", 1); +[$rtMulti, $rtMultiOut] = run_script('run-tools.php', ['baseline', 'tests', '--tests-args=--no-exit', '--codecept-options', '-c codeception.functional.yml', '--codecept-options', '-c codeception.api.yml'], $multi, $multiState, $stubEnv); +$multiLog = (string)file_get_contents($multiState . '/codecept-baseline.txt'); +$multiCalls = (string)file_get_contents($stub . '/multi-calls.log'); +check('run-tools: one codecept run per configuration, in the order given, with the tests arguments', $rtMulti === 0 && strpos($multiCalls, 'codecept run -c codeception.functional.yml --no-exit') !== false && strpos($multiCalls, 'codecept run -c codeception.api.yml --no-exit') > strpos($multiCalls, 'codeception.functional.yml')); +check('run-tools: the configurations share one log that ends with the highest exit code', substr_count($multiLog, '==> docker/sdk testing codecept run') === 2 && str_contains($multiLog, 'Rounds tax') && str_contains($multiLog, 'Creates order') && preg_match('/\nexit 1\n$/', $multiLog) === 1); +check('run-tools: the result adds up the configurations', str_contains($rtMultiOut, '6 tests in 3 suite(s): 3 passed, 2 failed, 1 skipped')); +check('run-tools: a suite of a later configuration does not take the namespace of the one before', array_key_exists('Api', read_json($multiState . '/tool-runs-baseline.json')['tools']['tests']['suites'] ?? [])); +check('run-tools: check-baselines accepts the combined log', bl_content_problem('codecept-baseline.txt', $multiLog) === null); +check('run-tools: the pin holds the options of each configuration', (read_json($multiState . '/tool-invocation.json')['codeceptOptions'] ?? null) === ['-c codeception.functional.yml', '-c codeception.api.yml']); +@unlink($stub . '/multi-calls.log'); +[$rtMultiLater] = run_script('run-tools.php', ['final', 'tests'], $multi, $multiState, $stubEnv); +check('run-tools: a later run uses every pinned configuration', $rtMultiLater === 0 && substr_count((string)file_get_contents($stub . '/multi-calls.log'), 'codecept run -c ') === 2); +[$rtMultiOther] = run_script('run-tools.php', ['final', 'tests', '--codecept-options', '-c codeception.api.yml'], $multi, $multiState, $stubEnv); +check('run-tools: configurations that differ from the pin -> exit 2', $rtMultiOther === 2); +[$rtMultiBroken, $rtMultiBrokenOut] = run_script('run-tools.php', ['baseline', 'tests', '--codecept-options', '-c codeception.functional.yml', '--codecept-options', '-c codeception.broken.yml'], $multi, $multiState, $stubEnv); +check('run-tools: a configuration that did not start -> tests did not run, named with the reason', $rtMultiBroken === 1 && str_contains($rtMultiBrokenOut, 'did not run: codecept run -c codeception.broken.yml: Error response from daemon')); +$oneFileTwoRuns = to_codecept_suites(to_plain_text($codeceptBase . "Codeception PHP Testing Framework v5.1.2\n\nApi Tests (1) ------\n✔ OrdersCest: Reads orders (0.01s)\n------\nTime: 00:01.000, Memory: 40.00 MB\n\nOK (1 test, 1 assertion)\n")); +check('tool output: a second codecept run in one file starts without an include namespace', array_keys($oneFileTwoRuns) === ['PyzTest\\Zed\\Foo Business', 'PyzTest\\Zed\\Bar Business', 'Api']); + +$cmp = $tmp . '/compare'; +$cmpState = $cmp . '/.state'; +write_file($cmp . '/composer.json', "{}\n"); +mkdir($cmp . '/src/Pyz', 0777, true); +$baselines = ['phpstan-baseline-run.txt' => $phpstanBase, 'sniff-baseline.txt' => $sniffBase, 'evaluator-baseline.txt' => $evaluatorBase, 'codecept-baseline.txt' => $codeceptBase]; +foreach ($baselines as $name => $contents) { + write_file("$cmpState/$name", $contents . "exit 0\n"); +} +$writeRun = static function (string $run, array $logs) use ($cmpState): void { + foreach ($logs as $tool => $contents) { + write_file($cmpState . '/' . rt_log_name($tool, $run), $contents . "exit 1\n"); + } +}; +$writeRun('verify', ['phpstan' => $phpstanBase, 'sniffer' => $sniffBase, 'evaluator' => $evaluatorBase, 'tests' => $codeceptBase]); +[$ctSame, $ctSameOut] = run_script('compare-tool-runs.php', ['verify'], $cmp, $cmpState); +check('compare: a baseline with red tests and the same result -> exit 0, every tool ok', $ctSame === 0 && substr_count($ctSameOut, ' ok ') === 4 && !str_contains($ctSameOut, ' + ')); +$writeRun('final', ['phpstan' => $phpstanAfter, 'sniffer' => $sniffAfter, 'evaluator' => $evaluatorAfter, 'tests' => $codeceptAfter]); +[$ctReg, $ctRegOut] = run_script('compare-tool-runs.php', ['final'], $cmp, $cmpState); +check('compare: regressions -> exit 1', $ctReg === 1); +check('compare: new PHPStan error only, the moved line of the old one is not new', str_contains($ctRegOut, '+ src/Pyz/Zed/Foo/FooFacade.php: Parameter #1 $x') && !str_contains($ctRegOut, '+ src/Pyz/Zed/Foo/FooFacade.php: Call to an undefined')); +check('compare: new sniffer violation only', str_contains($ctRegOut, '+ /data/src/Pyz/Zed/Bar/BarFacade.php: ERROR Missing doc comment') && substr_count($ctRegOut, 'Expected 1 space') === 0); +check('compare: new evaluator finding only', str_contains($ctRegOut, '+ PHP VERSION CHECKER: Deploy PHP is 8.0 (deploy.yml)') && !str_contains($ctRegOut, 'Composer PHP is 8.1')); +check('compare: a test that passed before and fails now, with its suite; the test red in the baseline is not listed', str_contains($ctRegOut, '+ PyzTest\\Zed\\Bar Business: BarFacadeTest: Reads bar') && !str_contains($ctRegOut, 'Rounds tax')); +check('compare: one verdict line per tool and the report path', preg_match_all('/^(phpstan|sniffer|evaluator|tests)\s+REGRESSION/m', $ctRegOut) === 4 && str_contains($ctRegOut, 'Full report: .state/tool-comparison-final.json')); +check('compare: the report holds the full lists', count(read_json($cmpState . '/tool-comparison-final.json')['tools']['phpstan']['new'] ?? []) === 1); +[$ctLimit, $ctLimitOut] = run_script('compare-tool-runs.php', ['final', 'sniffer', '--limit', '0'], $cmp, $cmpState); +check('compare: --limit caps the listed findings and points to the report', $ctLimit === 1 && str_contains($ctLimitOut, '(1 more in the report)') && !str_contains($ctLimitOut, ' + ')); +write_file($cmpState . '/phpstan-post-tooling.txt', $phpstanAfter . "exit 1\n"); +[$ctPost, $ctPostOut] = run_script('compare-tool-runs.php', ['final', 'phpstan'], $cmp, $cmpState); +[$ctPhase0] = run_script('compare-tool-runs.php', ['final', 'phpstan', '--baseline', 'phase0'], $cmp, $cmpState); +check('compare: the post-tooling file is the baseline when it exists; --baseline phase0 overrides', $ctPost === 0 && str_contains($ctPostOut, 'phpstan-post-tooling.txt') && $ctPhase0 === 1); +[$ctPostRun, $ctPostRunOut] = run_script('compare-tool-runs.php', ['post-tooling', 'phpstan'], $cmp, $cmpState); +check('compare: the post-tooling run is compared with the Phase 0 file', $ctPostRun === 1 && str_contains($ctPostRunOut, 'phpstan-baseline-run.txt')); +unlink($cmpState . '/evaluator-baseline.txt'); +[$ctNoBase, $ctNoBaseOut] = run_script('compare-tool-runs.php', ['final'], $cmp, $cmpState); +check('compare: a missing baseline -> exit 2, named', $ctNoBase === 2 && str_contains($ctNoBaseOut, 'evaluator: no baseline')); +write_file($cmpState . '/evaluator-baseline.txt', "Could not open input file: vendor/bin/evaluator\nexit 1\n"); +[$ctBadBase] = run_script('compare-tool-runs.php', ['final', 'evaluator'], $cmp, $cmpState); +check('compare: a baseline without a result -> exit 2', $ctBadBase === 2); +$writeRun('detect', ['phpstan' => "Error response from daemon: container cli is not running\n"]); +[$ctNoResult, $ctNoResultOut] = run_script('compare-tool-runs.php', ['detect'], $cmp, $cmpState); +check('compare: a run without a result -> NO RESULT, exit 1', $ctNoResult === 1 && str_contains($ctNoResultOut, 'NO RESULT')); +[$ctNoRun] = run_script('compare-tool-runs.php', ['nothing'], $cmp, $cmpState); +[$ctMissingLog] = run_script('compare-tool-runs.php', ['detect', 'sniffer'], $cmp, $cmpState); +check('compare: no log of the run, or of a named tool -> exit 2', $ctNoRun === 2 && $ctMissingLog === 2); + $cleanup = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($tmp, FilesystemIterator::SKIP_DOTS), RecursiveIteratorIterator::CHILD_FIRST); foreach ($cleanup as $entry) { $entry->isDir() && !$entry->isLink() ? @rmdir($entry->getPathname()) : @unlink($entry->getPathname()); diff --git a/tests/scripts/feature-install/feature-install.test.php b/tests/scripts/feature-install/feature-install.test.php index 277fa7e..57f80b0 100644 --- a/tests/scripts/feature-install/feature-install.test.php +++ b/tests/scripts/feature-install/feature-install.test.php @@ -357,9 +357,9 @@ function decided_row(array $overrides): array check('accepted moves are not open', array_keys(cnm_open($moves, ['spryker/gui' => 'developer: needed for the new Back Office assets'])) === ['spryker/mail']); echo "compare-baselines\n"; -check('PHPStan error count', cb_phpstan_errors('[ERROR] Found 12 errors') === 12 && cb_phpstan_errors(' [OK] No errors') === 0); -check('sniffer total', cb_sniff_findings('A TOTAL OF 3 ERRORS AND 2 WARNINGS WERE FOUND') === 5 && cb_sniff_findings("FOUND 2 ERRORS AFFECTING 2 LINES\nFOUND 1 ERROR AND 1 WARNING AFFECTING 2 LINES") === 4); -check('codecept failing tests are named', cb_codecept("There were 2 failures:\n1) FooTest: bar\n2) BazTest: qux\nFAILURES!\nTests: 10, Assertions: 20, Failures: 2.")['failing'] === ['FooTest: bar', 'BazTest: qux']); +check('PHPStan error count', to_phpstan_count('[ERROR] Found 12 errors') === 12 && to_phpstan_count(' [OK] No errors') === 0); +check('sniffer total', to_sniff_count('A TOTAL OF 3 ERRORS AND 2 WARNINGS WERE FOUND') === 5 && to_sniff_count("FOUND 2 ERRORS AFFECTING 2 LINES\nFOUND 1 ERROR AND 1 WARNING AFFECTING 2 LINES") === 4); +check('codecept failing tests are named', to_codecept_summary("There were 2 failures:\n1) FooTest: bar\n2) BazTest: qux\nFAILURES!\nTests: 10, Assertions: 20, Failures: 2.")['failing'] === ['FooTest: bar', 'BazTest: qux']); echo "check-data-manifests\n"; $manifestProject = temp_dir('manifests');