diff --git a/.agents/skills/php-forge-diff/SKILL.md b/.agents/skills/php-forge-diff/SKILL.md new file mode 100644 index 0000000..00e790d --- /dev/null +++ b/.agents/skills/php-forge-diff/SKILL.md @@ -0,0 +1,45 @@ +--- +name: php-forge-diff +description: Integrate or troubleshoot php-forge/diff line edit scripts and unified diff rendering in PHP applications. Use for LineDiffer, DifferInterface, or UnifiedDiffRenderer; exclude applying patches and unrelated Git operations. +license: BSD-3-Clause +metadata: + source: https://github.com/php-forge/diff +--- + +# Use php-forge/diff + +Inspect the installed revision and its `composer.json`, source and guides before choosing an API. For a dependency, +resolve Composer's installed path and reference; a path checkout can contain uncommitted changes. Compare the lock file, +which may describe a different installation. Use documentation matching the installed files and report a gap if it +cannot be found. PHP 8.3 or later is required by the current package. + +## Choose the result + +Use `(new PHPForge\Diff\LineDiffer())->diff($old, $new)` for an ordered list of `DiffLine` objects with +`DiffOp::Context`, `Remove`, or `Add`. It splits both strings literally on `"\n"`: an empty string is one empty line and +a trailing newline produces an empty final line. Remove `Add` entries to reconstruct the old input, or `Remove` entries +for the new input, joining the remaining `line` values with `"\n"`. It does not normalize line endings. + +Use `(new PHPForge\Diff\UnifiedDiffRenderer())->render($old, $new, $fromLabel, $toLabel, $context)` for unified text; +`$context` is optional and defaults to `3`. It normalizes CRLF and CR to LF, returns an empty string for normalized +equal texts and otherwise returns a patch without a trailing newline or Git's `diff --git` and `index` headers. Negative +context is treated as zero. Missing final newlines are represented by `\ No newline at end of file`. Labels are supplied +by the caller; this renderer does not read files, apply patches, or escape labels for untrusted presentation. + +A custom `DifferInterface` can be injected into the renderer. Its script must reconstruct both inputs in order. The +renderer takes the rendered lines from the texts by operation position and does not validate `DiffLine::line`: a script +whose operations do not consume both inputs exactly throws `LogicException`, while a balanced script with wrong +operations renders an incorrect diff without any error. Test a non-empty change as well as empty inputs because the +renderer handles empty sides separately. Do not swallow `LogicException` as an empty diff. + +The default differ follows Git's default xdiff pipeline and indent heuristic, but lacks Git's cost limit. Its edit +script is not guaranteed shortest or identical to Git on expensive inputs. Do not promise binary diff support or exact +byte preservation after renderer line-ending normalization. + +## Verify + +Use the application's existing tests and the package's `docs/examples.md`, `docs/algorithms.md` and `docs/testing.md` at +the matching revision. Assert both reconstructed sides, unchanged inputs, empty sides, trailing-newline differences, +line-ending normalization, requested context and custom-differ failure as relevant. If comparing with Git, disable user +and system Git configuration and document the chosen options. Record installation, client discovery, native skill +loading, actual task behavior and test results separately; reading this file alone proves no activation. diff --git a/.gitattributes b/.gitattributes index 2360366..860edb0 100644 --- a/.gitattributes +++ b/.gitattributes @@ -4,38 +4,50 @@ # ...Unless the name matches the following overriding patterns # Definitively text files -*.php text -*.css text -*.js text -*.txt text -*.md text -*.xml text -*.json text -*.bat text -*.sql text -*.yml text +*.php text +*.css text +*.js text +*.txt text +*.md text +*.xml text +*.json text +*.json5 text +*.neon text +*.bat text +*.sql text +*.yml text +*.yaml text +*.svg text # Ensure those won't be messed up with -*.png binary -*.jpg binary -*.gif binary -*.ttf binary +*.png binary +*.jpg binary +*.gif binary +*.ttf binary # Exclude files from the archive +/.agents export-ignore +/.claude export-ignore /.editorconfig export-ignore /.gitattributes export-ignore /.github export-ignore /.gitignore export-ignore +/.prettierignore export-ignore +/.prettierrc.json export-ignore /.styleci.yml export-ignore +/.stylelintignore export-ignore +/AGENTS.md export-ignore /codeception.yml export-ignore +/codecov.yml export-ignore /composer-require-checker.json export-ignore /docs export-ignore /ecs.php export-ignore /infection.json* export-ignore +/internal export-ignore /phpstan*.neon* export-ignore -/phpunit.xml.dist export-ignore /rector.php export-ignore /runtime export-ignore +/testo.php export-ignore /tests export-ignore # Avoid merge conflicts in CHANGELOG diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 7d4279f..372339a 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -16,10 +16,7 @@ permissions: contents: read jobs: - phpunit: - uses: yii2-framework/actions/.github/workflows/phpunit.yml@a28eb7d4ab03abd53ccd7c79014b3b27d09932ff # v2.0.1 - with: - extensions: gd, intl - php-version: '["8.3","8.4","8.5"]' + testo: + uses: php-forge/actions/.github/workflows/testo.yml@72def618dcf8a77705c26faa53e9f8b1dc1f53bb # v3.0.1 secrets: CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }} diff --git a/.gitignore b/.gitignore index d8f1018..e2c4d38 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,5 @@ # AI agents (if present) +.agents/skills/testo-* .codex .claude diff --git a/CHANGELOG.md b/CHANGELOG.md index 73ee0f9..6bf2656 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## 0.3.0 Under development - feat!: rename package to `php-forge/scaffold` with namespace `PHPForge\Scaffold`; update `require`, `allow-plugins` and class references. +- feat!: overhaul sync, merge modes and CLI; enforce strict manifests and locks; support Console 8 and drop Composer runtime dependency. ## 0.2.0 July 04, 2026 diff --git a/README.md b/README.md index ab7a4e1..9585fcb 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@

- PHPUnit + Testo Mutation Testing @@ -39,90 +39,106 @@ ```bash composer config allow-plugins.php-forge/scaffold true -composer require php-forge/scaffold:^0.3 +composer require --dev php-forge/scaffold:^0.3 ``` -Install your scaffold providers, then declare which are permitted to write files into your project: +Require the providers and list, in order, the ones allowed to write files into the project: ```json { + "require-dev": { + "php-forge/baseline": "^0.2", + "php-forge/coding-standard": "^0.3", + "php-forge/scaffold": "^0.3" + }, + "config": { + "allow-plugins": { + "php-forge/scaffold": true + } + }, "extra": { "scaffold": { - "allowed-packages": [ - "php-forge/baseline", - "php-forge/coding-standard" - ] + "allowed-packages": ["php-forge/baseline", "php-forge/coding-standard"] } } } ``` -Run `composer install` to trigger the scaffold process. Commit `scaffold-lock.json` to version control. +Run `composer install`. The plugin copies the provider files, merges the shared ones, writes `scaffold-lock.json` and +prints one summary line: -To opt out of auto-trigger and manage updates manually via `vendor/bin/scaffold`, set `auto: false` (see -[Configuration Reference](docs/configuration.md#auto)): - -```json -{ - "extra": { - "scaffold": { - "auto": false, - "allowed-packages": ["php-forge/baseline", "php-forge/coding-standard"] - } - } -} +```text +[scaffold] 10 files written, 1 unchanged, 1 warning. ``` +Review the result with `git diff` and commit the files together with `scaffold-lock.json`. + ## Configuration -Scaffold configuration for a project with `php-forge/baseline` and `php-forge/coding-standard` already installed: +| Setting | Default | Effect | +| --------------------------------- | ------- | ------------------------------------------------------------------------------------------------- | +| `extra.scaffold.allowed-packages` | `[]` | Providers allowed to write files, in order; the later provider wins when two ship the same file. | +| `extra.scaffold.auto` | `true` | `false` disables the Composer hooks; apply the providers with `vendor/bin/scaffold sync` instead. | + +Providers choose a mode per file: `replace` (provider-owned, skipped once you edit it), `preserve` (seeded once, then +yours), `append` (format-aware merge for `.editorconfig`, `.gitignore` and similar files) or `prepend`. The lock records +the owner, the mode and two hashes per file: ```json { - "require": { - "php-forge/scaffold": "^0.3" - }, - "config": { - "allow-plugins": { - "php-forge/scaffold": true + "providers": { + "php-forge/baseline": { + "version": "0.2.0", + "path": "vendor/php-forge/baseline" } }, - "extra": { - "scaffold": { - "allowed-packages": [ - "php-forge/baseline", - "php-forge/coding-standard" - ] + "files": { + ".styleci.yml": { + "hash": "sha256:825f8c744ffbd2bc2369712e7192b8694129a8ecbc3fd91dc9300fccecf827bd", + "provider": "php-forge/baseline", + "source": "metadata/.styleci.yml", + "mode": "replace", + "stub-hash": "sha256:825f8c744ffbd2bc2369712e7192b8694129a8ecbc3fd91dc9300fccecf827bd" } } } ``` +`hash` is the file as scaffold last left it and `stub-hash` the provider source at that moment, so scaffold can tell +your edits apart from provider updates. + ## Console commands -After `composer install`, the plugin ships a standalone Symfony Console CLI at `vendor/bin/scaffold` that works in any -PHP project (Yii2, Yii3, Laravel, Symfony, plain PHP). +The plugin installs a standalone console application at `vendor/bin/scaffold`. Every command finds the project root by +walking up to the nearest `composer.json`; the global `--working-dir` (`-d`) option starts the search elsewhere. -| Command | What it does | -| ------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------ | -| `vendor/bin/scaffold status` | Prints a table comparing every tracked file's on-disk hash to the one recorded in `scaffold-lock.json` (`synced` / `modified` / `missing`). | -| `vendor/bin/scaffold providers` | Lists every provider recorded in `scaffold-lock.json` and how many files each one contributed. | -| `vendor/bin/scaffold diff ` | Shows a line-by-line diff between the provider stub and the current on-disk file. | -| `vendor/bin/scaffold reapply [file] [--force] [--provider=]` | Re-copies stubs from `vendor/` to the project, updating lock hashes on success. Without `--force`, user-modified files are reported and skipped. | -| `vendor/bin/scaffold eject [--yes]` | Removes a file entry from `scaffold-lock.json` without deleting the file from disk. Without `--yes` only previews the change. | +| Command | What it does | +| -------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------- | +| `status [--format=table\|json] [--exit-code]` | Shows each file as `synced`, `pending`, `outdated`, `modified`, `conflict`, `missing`, `orphan`, `ejected` or `error`. | +| `diff \|--all [--exit-code]` | Shows what applying the providers would change, as a unified diff from the current file. | +| `reapply [] [--provider=] [--force] [--dry-run] [--exit-code]` | Applies the stubs of tracked files again; `--force` also takes user-modified, `preserve` and ejected files. | +| `eject [--yes]` | Marks a file as yours; no run writes it again until `reapply --force`. | +| `prune [--force] [--delete-modified] [--exit-code]` | Lists files no allowed provider ships anymore; `--force` deletes the unmodified ones and drops the entries. | +| `sync [--dry-run] [--exit-code] [--force]` | Applies every allowed provider outside Composer, for `auto: false`, `--no-plugins` runs and bots. | +| `providers` | Lists the providers recorded in `scaffold-lock.json` with their file counts. | -Typical post-install workflow: +Typical workflow after `composer install` or `composer update`: ```bash -vendor/bin/scaffold status # what changed -vendor/bin/scaffold diff config/params.php # review one file -vendor/bin/scaffold reapply config/params.php --force # accept stub version +vendor/bin/scaffold status # what needs attention +vendor/bin/scaffold diff --all # what applying the providers would change +vendor/bin/scaffold reapply .styleci.yml --force # take the provider version of a file you edited +vendor/bin/scaffold eject .styleci.yml --yes # or keep yours for good +vendor/bin/scaffold prune # review files the providers no longer ship +``` -# or -vendor/bin/scaffold eject config/params.php --yes # keep yours, stop tracking +Gate CI on drift between the committed files and the providers: + +```bash +vendor/bin/scaffold status --exit-code ``` -See [`docs/console.md`](docs/console.md) for the full reference. +Upgrading from `yii2-extensions/scaffold` `0.2`? Read [UPGRADE.md](UPGRADE.md). ## Documentation @@ -132,6 +148,7 @@ See [`docs/console.md`](docs/console.md) for the full reference. - 🔀 [File Modes](docs/modes.md) - 🖥️ [Console Commands](docs/console.md) - 🧪 [Testing Guide](docs/testing.md) +- ⬆️ [Upgrade Guide](UPGRADE.md) ## Package information @@ -141,10 +158,17 @@ See [`docs/console.md`](docs/console.md) for the full reference. ## Project status +[![Codecov](https://img.shields.io/codecov/c/github/php-forge/scaffold.svg?style=for-the-badge&logo=codecov&logoColor=white&label=Coverage)](https://codecov.io/github/php-forge/scaffold) [![PHPStan Level Max](https://img.shields.io/badge/PHPStan-Level%20Max-4F5D95.svg?style=for-the-badge&logo=github&logoColor=white)](https://github.com/php-forge/scaffold/actions/workflows/static.yml) [![Quality](https://img.shields.io/github/actions/workflow/status/php-forge/scaffold/quality.yml?style=for-the-badge&label=Quality&logo=github)](https://github.com/php-forge/scaffold/actions/workflows/quality.yml) [![StyleCI](https://img.shields.io/badge/StyleCI-Passed-44CC11.svg?style=for-the-badge&logo=github&logoColor=white)](https://github.styleci.io/repos/1212894073?branch=main) +## Built with AI + +[![Built with Claude Code](https://img.shields.io/badge/Built%20with-Claude%20Code-D97757.svg?style=for-the-badge&logo=claude&logoColor=white)](https://claude.com/claude-code) +[![Reviewed by Codex](https://img.shields.io/badge/Reviewed%20by-Codex-10A37F.svg?style=for-the-badge&logo=openaigym&logoColor=white)](https://openai.com/codex) +[![Reviewed by CodeRabbit](https://img.shields.io/badge/Reviewed%20by-CodeRabbit-FF570A.svg?style=for-the-badge&logo=coderabbit&logoColor=white)](https://www.coderabbit.ai) + ## Our social networks [![Follow on X](https://img.shields.io/badge/-Follow%20on%20X-1DA1F2.svg?style=for-the-badge&logo=x&logoColor=white&labelColor=000000)](https://x.com/Terabytesoftw) diff --git a/UPGRADE.md b/UPGRADE.md new file mode 100644 index 0000000..820ca63 --- /dev/null +++ b/UPGRADE.md @@ -0,0 +1,108 @@ +# Upgrading Scaffold + +This file lists, for each release, the changes that need an action from you or that change what you see when scaffold +runs. Features that need neither are described in the [documentation](README.md#documentation) and the +[changelog](CHANGELOG.md). + +## Upgrading from yii2-extensions/scaffold 0.2.x to php-forge/scaffold 0.3.x + +### Rename the package + +The package moved from `yii2-extensions/scaffold` to `php-forge/scaffold`. Composer cannot rename a package, so change +both keys in the same commit; a project whose `allow-plugins` still names only the old package fails non-interactive +installs because the new plugin is not allowed. + +```json +{ + "require-dev": { + "php-forge/scaffold": "^0.3" + }, + "config": { + "allow-plugins": { + "php-forge/scaffold": true + } + } +} +``` + +Remove `yii2-extensions/scaffold` from `require-dev` and from `config.allow-plugins`, then run: + +```bash +composer update php-forge/scaffold --with-all-dependencies +vendor/bin/scaffold status --exit-code +git diff +``` + +`vendor/bin/scaffold`, `extra.scaffold`, provider manifests and `scaffold-lock.json` keep their names and formats. The +PHP namespace moved from `yii\scaffold` to `PHPForge\Scaffold`; only code that imports the plugin classes is affected. + +### Dependencies + +- `symfony/console` `^7.4 || ^8.0` (Symfony Console 8 requires PHP 8.4). +- [`php-forge/diff`](https://github.com/php-forge/diff) renders the unified diffs with Git's default algorithm (Myers + with the indent heuristic). +- `composer/composer` and `sebastian/diff` are no longer installed with the plugin. A project that relied on them + transitively must require them itself. +- Require the plugin in `require-dev`: with `require`, a fresh `composer install --no-dev` scaffolds production builds. + +### First run after the upgrade + +The first `composer update` or `composer install` with 0.3 can change files that 0.2 left alone. Review `git diff`: + +- `append` files are now merged on every run with a format-aware strategy (`ini` for `.editorconfig`, `list` for + `.gitignore` and other ignore files, `text` otherwise), so provider entries that 0.2 never delivered are added. + Existing keys and entries are never changed or duplicated. See [File Modes](docs/modes.md#append). +- `prepend` is idempotent: the block is added only when the file does not contain it. +- A `replace` file that exists but is not tracked yet is still overwritten on adoption, now with an + `Overwrote untracked existing file ""` warning that points to `git diff` and `eject`. +- Lock entries gain `stub-hash` when they are applied again. Until then `status` prints + `[scaffold] N entries lack stub-hash; run composer install to refresh.` + +### scaffold-lock.json + +The format is additive; a 0.2 lock is read as is. Entries gain `stub-hash` (hash of the provider source at the last +apply), and, when they apply, `merge`, `ejected: true` and `adopted: true`. The file is now written with sorted keys and +a trailing newline, so the first write produces a reordering diff. Unknown keys are kept. See +[Configuration Reference](docs/configuration.md#scaffold-lockjson). + +### Composer runs + +- A run that writes files or needs attention prints a summary line, such as + `[scaffold] 2 files written, 7 unchanged, 1 conflict, 1 orphan, 1 warning.`; 0.2 printed nothing on success. +- These failures now fail the Composer command with exit code `1` instead of a message and exit code `0`: an unreadable + or conflicted `scaffold-lock.json`, an invalid manifest of an allowed provider (nothing is applied), and a file that + cannot be applied. +- Provider manifests with unknown keys are rejected. Check the providers you maintain: a typo such as `mode` instead of + `modes` used to be ignored silently. +- An allowed provider that is not installed is reported as + `Provider "" is allowed but not installed; check extra.scaffold.allowed-packages or require it.` +- Files that no allowed provider ships anymore are listed as orphans on every run, with the `prune` hint; they are never + deleted by Composer. +- `post-create-project-cmd` no longer applies a second time after `post-update-cmd`, so templates without + `composer.lock` no longer get duplicated `prepend` blocks. + +### Console commands + +- `diff` reversed its direction: it shows what applying the provider would change, from the current file (`a/`) to the + result of the apply (`b/`). 0.2 diffed from the stub to the current file. It needs a `` or `--all`; without + either it exits with `2`. +- `status` has new states (`pending`, `outdated`, `conflict`, `orphan`, `ejected`), a summary line, provider version + drift on stderr, `--format=json`, and exits with `1` when an entry is in the `error` state. Add + `vendor/bin/scaffold status --exit-code` to CI to fail on drift. +- `reapply` merges `append` and `prepend` files instead of refusing them, rewrites them from the stub with `--force`, + skips orphans, ends with a summary line, and exits with `1` when an entry is skipped for an error (provider not + allowed, unsafe entry, missing stub, unknown mode, read or write failure). It never reads providers that are not in + `allowed-packages`. +- `eject` is durable: the entry stays in the lock with `ejected: true`, and no Composer run writes the file again. In + 0.2 the entry was removed and the next `composer install` overwrote the file. `reapply --force` takes it back. +- `providers` sizes its columns to their content, like the `status` and `prune` tables. +- New commands: `sync` (apply the providers outside Composer, the bootstrap for `auto: false`) and `prune` (review and + remove orphans). +- Every command finds the project root by walking up to the nearest `composer.json`, and accepts the global + `--working-dir` (`-d`) option. + +### Providers + +- New manifest key `merge` selects the `append` strategy per destination. +- Brace alternatives `{a,b}` now work in `exclude`, `modes` and `merge` patterns. +- Default excludes gained `.git` as a file, `node_modules/**`, `.idea/**` and `.DS_Store`. diff --git a/bin/scaffold b/bin/scaffold index 0d92aa7..0ccc09a 100755 --- a/bin/scaffold +++ b/bin/scaffold @@ -4,21 +4,24 @@ declare(strict_types=1); /** - * Standalone entry point for the `php-forge/scaffold` Symfony Console application. - * - * Resolves its Composer autoloader whether invoked from the plugin's own `bin/scaffold` (development) or from a - * consumer's `vendor/bin/scaffold` (production). Any PHP project that requires `php-forge/scaffold` can run - * this binary without needing a framework. + * Runs the `php-forge/scaffold` console application with the autoloader published by Composer's `vendor/bin` proxy, + * falling back to the autoloader of the plugin checkout or of the consumer project. */ use PHPForge\Scaffold\Console\Application; -foreach ( - [ - __DIR__ . '/../vendor/autoload.php', - __DIR__ . '/../../../autoload.php', - ] as $autoloadPath -) { +// Composer's 'vendor/bin' proxies (2.2+) expose the consumer autoloader path; the relative candidates cover direct +// invocation of the plugin checkout and of an installed copy without a proxy. +$autoloadCandidates = []; + +if (isset($GLOBALS['_composer_autoload_path']) && is_string($GLOBALS['_composer_autoload_path'])) { + $autoloadCandidates[] = $GLOBALS['_composer_autoload_path']; +} + +$autoloadCandidates[] = __DIR__ . '/../vendor/autoload.php'; +$autoloadCandidates[] = __DIR__ . '/../../../autoload.php'; + +foreach ($autoloadCandidates as $autoloadPath) { if (is_file($autoloadPath)) { require $autoloadPath; diff --git a/composer-require-checker.json b/composer-require-checker.json index af5da6d..576706e 100644 --- a/composer-require-checker.json +++ b/composer-require-checker.json @@ -1,5 +1,14 @@ { - "symbol-whitelist": [], + "symbol-whitelist": [ + "Composer\\Composer", + "Composer\\EventDispatcher\\EventSubscriberInterface", + "Composer\\InstalledVersions", + "Composer\\IO\\IOInterface", + "Composer\\Package\\PackageInterface", + "Composer\\Plugin\\PluginInterface", + "Composer\\Script\\Event", + "Composer\\Script\\ScriptEvents" + ], "php-core-extensions": [ "Core", "date", diff --git a/composer.json b/composer.json index 26bc14a..0252802 100644 --- a/composer.json +++ b/composer.json @@ -22,9 +22,8 @@ "require": { "php": ">=8.3", "composer-plugin-api": "^2.3", - "composer/composer": "^2.10", - "sebastian/diff": "^7.0", - "symfony/console": "^7.4" + "php-forge/diff": "^0.1", + "symfony/console": "^7.4 || ^8.0" }, "bin": [ "bin/scaffold" @@ -32,13 +31,14 @@ "require-dev": { "composer/composer": "^2.10", "infection/infection": "^0.35", + "llm/skills": "^1.15", "maglnet/composer-require-checker": "^4.1", "php-forge/coding-standard": "^0.3", "phpstan/extension-installer": "^1.4", "phpstan/phpstan": "^2.2", "phpstan/phpstan-strict-rules": "^2.0", - "phpunit/phpunit": "^12.5", - "xepozz/internal-mocker": "^1.4" + "testo/bridge-infection": "^0.1.9", + "testo/testo": "^0.10.56" }, "autoload": { "psr-4": { @@ -60,16 +60,21 @@ "sort-packages": true, "allow-plugins": { "infection/extension-installer": true, + "llm/skills": true, "phpstan/extension-installer": true } }, "scripts": { "check-dependencies": "./vendor/bin/composer-require-checker check", "ecs": "./vendor/bin/ecs --fix", - "mutation": "./vendor/bin/infection --threads=4 --ignore-msi-with-no-mutations --min-msi=85 --min-covered-msi=85", - "mutation-static": "php -d memory_limit=-1 ./vendor/bin/infection --initial-tests-php-options='-d memory_limit=-1' --test-framework-extra-args='-d memory_limit=-1' --threads=4 --ignore-msi-with-no-mutations --min-msi=100 --min-covered-msi=100 --static-analysis-tool=phpstan --static-analysis-tool-options='--memory-limit=-1'", + "mutation": [ + "Composer\\Config::disableProcessTimeout", + "@php -d memory_limit=-1 ./vendor/bin/infection" + ], + "mutation-static": "@mutation --static-analysis-tool=phpstan", "rector": "./vendor/bin/rector process", "static": "./vendor/bin/phpstan --memory-limit=-1", - "tests": "./vendor/bin/phpunit" + "tests": "./vendor/bin/testo", + "tests-unit": "./vendor/bin/testo --suite=Unit" } } diff --git a/docs/configuration.md b/docs/configuration.md index 33f7401..8897da0 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -1,68 +1,70 @@ # Configuration reference -All scaffold configuration lives under the `extra.scaffold` key in the root project's `composer.json`. Provider packages -are never trusted unless they appear in `allowed-packages`. +The consumer configuration lives under `extra.scaffold` in the root `composer.json` of the project. Only the root +package is read: the `extra.scaffold` block of a provider describes what it ships (see +[Creating Providers](providers.md)), and its own `allowed-packages` has no effect on the projects that install it. ## allowed-packages -**Required.** An ordered list of Composer package names that are permitted to contribute scaffold files. +An ordered list of the Composer packages allowed to write files into the project. Packages that are not listed are never +read, even when they ship a manifest. ```json { "extra": { "scaffold": { - "allowed-packages": [ - "php-forge/baseline", - "php-forge/coding-standard" - ] + "allowed-packages": ["php-forge/baseline", "php-forge/coding-standard"] } } } ``` -**Ordering matters.** When two providers declare the same destination file, the provider listed **later** wins. This -allows specialised layers to override base-layer defaults without forking them. - -If the list is empty or absent the plugin writes a notice and exits without modifying any files. +- **Order matters.** When two providers ship the same destination, the provider listed later wins, and the run prints + `[scaffold] "" from "" overrides "" (last provider in allowed-packages wins).` +- A listed package that is not installed produces a warning that names the fix: + `[scaffold] Provider "" is allowed but not installed; check extra.scaffold.allowed-packages or require it.` +- Entries that are not strings are ignored with `[scaffold] Non-string entry in allowed-packages ignored.` +- Without `extra.scaffold`, or with an empty or missing list, Composer runs print + `[scaffold] No extra.scaffold configuration found. Skipping scaffold.` or + `[scaffold] No allowed-packages configured. Skipping scaffold.` and write nothing. ## auto -**Optional, defaults to `true`.** Controls whether the plugin auto-triggers on Composer script events -(`post-install-cmd`, `post-update-cmd`, `post-create-project-cmd`). +Optional, defaults to `true`. Controls whether the plugin scaffolds on Composer events. ```json { "extra": { "scaffold": { "auto": false, - "allowed-packages": ["php-forge/baseline"] + "allowed-packages": ["php-forge/baseline", "php-forge/coding-standard"] } } } ``` -When `auto: false`, the plugin remains installed and authorised but does not hook into Composer events. The CLI commands -at `vendor/bin/scaffold` continue to work, so the consumer can sync provider templates on demand: +With `auto: false`, Composer runs print +`[scaffold] Auto-scaffold disabled via "extra.scaffold.auto"; run "vendor/bin/scaffold" manually.` and write nothing. +The console commands keep working, and `sync` applies the providers on demand, creating `scaffold-lock.json` when it +does not exist yet: ```bash -vendor/bin/scaffold reapply --provider=php-forge/baseline -vendor/bin/scaffold diff -vendor/bin/scaffold status +vendor/bin/scaffold status # every provider file is listed as pending +vendor/bin/scaffold sync --dry-run --exit-code # review what applying the providers would change +vendor/bin/scaffold sync # apply them, as composer install would ``` -Use this when **explicit, opt-in updates** matter more than continuous synchronisation, for example on repositories -where every change to project standards should be reviewed before being applied. - -Only an explicit `false` disables the auto-trigger; missing, `null`, non-boolean, or any other value defaults to enabled -to avoid silent disable on typo. - -## Full annotated example +Use it when every change to the shared files must be reviewed before it lands. Only an explicit `false` disables the +Composer hooks; any other value, including a missing key or `null`, keeps them enabled, so a typo never disables +scaffolding silently. -Scaffold configuration for a project with `php-forge/baseline` and `php-forge/coding-standard` already installed: +## Full example ```json { - "require": { + "require-dev": { + "php-forge/baseline": "^0.2", + "php-forge/coding-standard": "^0.3", "php-forge/scaffold": "^0.3" }, "config": { @@ -80,43 +82,117 @@ Scaffold configuration for a project with `php-forge/baseline` and `php-forge/co ## scaffold-lock.json -The plugin writes `scaffold-lock.json` at the project root after every successful run. It records the SHA-256 hash, -provider name, source path, and mode for every file it has written. +Every run that applies files writes `scaffold-lock.json` at the project root. It records which provider owns each file, +how it was written, and the hashes that scaffold compares against on the next run. Commit it: `status`, `diff`, `prune` +and the user-modified detection of every clone and CI job read it. -**Commit this file.** It serves the same role as `composer.lock`: it lets collaborators and CI reproduce the exact -scaffold state and detect files that have been modified after scaffolding. - -Example lock entry: +Excerpt from a project that installed `php-forge/baseline` and `php-forge/coding-standard` with an existing `ecs.php`: ```json { "providers": { "php-forge/baseline": { - "version": "0.1.0", + "version": "0.2.0", "path": "vendor/php-forge/baseline" + }, + "php-forge/coding-standard": { + "version": "0.3.4", + "path": "vendor/php-forge/coding-standard" } }, "files": { - "config/params.php": { - "hash": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + ".gitignore": { + "hash": "sha256:4d07dd19f50ed675620f5a2f2d3abc9d2d3df9fe4ffbf70efc7a7efabfdbdc7c", + "provider": "php-forge/baseline", + "source": "metadata/.gitignore", + "mode": "append", + "stub-hash": "sha256:7d7753b2cc6184d74fb22f78c6b351b6c9c9dc04bcabe5481a0ed64b06858597" + }, + ".styleci.yml": { + "hash": "sha256:825f8c744ffbd2bc2369712e7192b8694129a8ecbc3fd91dc9300fccecf827bd", "provider": "php-forge/baseline", - "source": "stubs/config/params.php", - "mode": "replace" + "source": "metadata/.styleci.yml", + "mode": "replace", + "stub-hash": "sha256:825f8c744ffbd2bc2369712e7192b8694129a8ecbc3fd91dc9300fccecf827bd" + }, + "ecs.php": { + "hash": "sha256:50b842500050094116202088109abfac734d2fd9341eb14b25dd870fc63936f3", + "provider": "php-forge/coding-standard", + "source": "src/config/ecs.php", + "mode": "preserve", + "stub-hash": "sha256:7c054b397506c1a4d4ab2d1197e9536b44f114e2721a0e9f8c46f362efcc7bae", + "adopted": true } } } ``` -Provider paths are recorded **relative to the project root** so the lockfile stays stable across developer machines. -Versions come from Composer's `getPrettyVersion()`. +`providers.`: + +| Key | Meaning | +| --------- | --------------------------------------------------------------------------------------------------------- | +| `version` | Pretty version of the provider at the last run, as Composer reports it. | +| `path` | Install path of the provider, relative to the project root, or absolute when it lies outside the project. | + +`files.`: + +| Key | Meaning | +| ----------- | ---------------------------------------------------------------------------------------------------------------- | +| `hash` | `sha256:` of the destination as scaffold last left it (see [Hash tracking](modes.md#hash-tracking)). | +| `provider` | Package that owns the destination. | +| `source` | Path of the stub inside the provider. | +| `mode` | `replace`, `preserve`, `append` or `prepend`. | +| `stub-hash` | `sha256:` of the stub at the last apply. Entries written by `0.2.x` lack it until a run applies them again. | +| `merge` | Merge strategy (`ini`, `list` or `text`) selected by the manifest `merge` map; absent when the name decides it. | +| `ejected` | `true` after `vendor/bin/scaffold eject --yes`: no run writes the file until `reapply --force`. | +| `adopted` | `true` for a `preserve` file that existed before scaffold tracked it. | + +The file is written atomically with `providers` and `files` sorted by key and a trailing newline, so diffs stay small. +Keys that scaffold does not know are kept. A lock with Git conflict markers is rejected with a message that names them; +resolve the conflict and run Composer again. + +## Composer events + +| Composer event | Behavior | +| ------------------------- | ----------------------------------------------------------------------------------------------------------------------------- | +| `post-install-cmd` | Applies every allowed and installed provider: every mode on every destination, ejected files skipped. | +| `post-update-cmd` | Same as `post-install-cmd`. | +| `post-create-project-cmd` | Same, unless `post-install-cmd` or `post-update-cmd` already ran in the same Composer process, so a template is applied once. | + +There is no partial run: `append` and `prepend` files are re-evaluated on every event, so new provider entries reach +existing projects on the next `composer install` or `composer update`. + +The plugin subscribes to these events as a Composer plugin, not as a script: + +- `composer install --no-scripts` still scaffolds. +- `composer install --no-plugins` does not load the plugin + (`The "php-forge/scaffold" plugin was not loaded as plugins are disabled.`); run `vendor/bin/scaffold sync` + afterwards, or a later plain `composer install` catches up. +- With the plugin in `require-dev`, a fresh `composer install --no-dev`, such as a production build, does not install it + and writes no scaffold file. + +## Output and failure policy + +A Composer run that writes a file or needs attention ends with one summary line on stdout, such as +`[scaffold] 2 files written, 7 unchanged, 1 conflict, 1 orphan, 1 warning.`; a run that changes nothing prints nothing. +Warnings and errors go to stderr, prefixed with `[scaffold]`. + +The run fails (Composer exits with `1`) when: + +- `scaffold-lock.json` cannot be read: invalid JSON or Git conflict markers. Nothing is applied. +- The manifest of an allowed and installed provider is invalid: unknown key, invalid mode or merge strategy, unsafe + path, missing `copy` path. The message names the provider; nothing is applied. +- A file cannot be applied (unsafe path, unreadable stub, write failure). The other files are applied and recorded + first, then the run fails with `[scaffold] 1 file failed while scaffolding; see the messages above.` -## Event differentiation +Warnings keep the run successful: -| Composer event | Behaviour | -| ------------------------- | ---------------------------------------------------------------------------------------------------------------------------------- | -| `post-create-project-cmd` | Full scaffold: all modes applied, all files written, lock created. | -| `post-install-cmd` | Partial scaffold: `append` and `prepend` files already in the lock are skipped. `replace` files whose hashes match are re-applied. | -| `post-update-cmd` | Same as `post-install-cmd`. | +- An allowed provider that is not installed, or that produced no file mapping. +- A `replace` file that overwrote an untracked file with different content. +- A user-modified `replace` file that was skipped, with the `conflict` line when its stub changed (see + [File Modes](modes.md#provider-updates-after-a-version-bump)). +- Orphaned files that no allowed provider ships anymore, listed with the `vendor/bin/scaffold prune` hint. Composer runs + never delete them. ## Next steps diff --git a/docs/console.md b/docs/console.md index c62c02a..8e7ebb3 100644 --- a/docs/console.md +++ b/docs/console.md @@ -1,140 +1,336 @@ # Console commands -The scaffold plugin ships a standalone [Symfony Console](https://symfony.com/doc/current/components/console.html) CLI at -`vendor/bin/scaffold`. It works in any PHP project (Yii2, Yii3, Laravel, Symfony, plain PHP) with no framework bootstrap -required; the binary starts directly from Composer's autoloader. +The plugin ships a standalone [Symfony Console](https://symfony.com/doc/current/components/console.html) application at +`vendor/bin/scaffold`. It needs no framework bootstrap and works in any Composer project. Run `vendor/bin/scaffold list` +for the command list and `vendor/bin/scaffold --help` for the options of one command. + +| Command | Purpose | +| ----------- | ----------------------------------------------------------------------------------- | +| `status` | Shows the state of every tracked and pending file; `--exit-code` gates CI. | +| `diff` | Shows what applying the provider would change, as a Git-style unified diff. | +| `reapply` | Applies the stubs of tracked files again; `--force` takes user-modified files back. | +| `eject` | Marks a file as owned by the project, so scaffold never writes it again. | +| `prune` | Lists the files no allowed provider ships anymore; `--force` removes them. | +| `sync` | Applies every allowed provider outside Composer, as `composer install` would. | +| `providers` | Lists the providers recorded in `scaffold-lock.json` with their file counts. | + +## Project root and global options + +Every command looks for the project root by walking up from the current directory to the nearest `composer.json` (or the +file named by the `COMPOSER` environment variable), so `cd src && ../vendor/bin/scaffold status` works. The global +option `--working-dir=` (`-d `) starts the search from another directory: -Run `vendor/bin/scaffold list` to discover every available command; each entry below also responds to `--help` for -detailed option documentation. +```bash +vendor/bin/scaffold --working-dir=../app status +``` -## vendor/bin/scaffold status +The vendor directory follows `COMPOSER_VENDOR_DIR`, then `config.vendor-dir`, then `vendor`. Provider roots come from +the project's `vendor/composer/installed.php`, so custom installers and symlinked path repositories resolve correctly; +the path recorded in the lock is the fallback. -Reads `scaffold-lock.json` and compares the recorded hash of every tracked file to its current on-disk hash. Outputs a -status table. +Every command except `eject` and `providers` reads only the providers listed in `extra.scaffold.allowed-packages`. +`status`, `diff` and `reapply` report a lock entry whose provider is no longer allowed on stderr +(`[scaffold] "": provider "" is not in extra.scaffold.allowed-packages; skipped.`); `diff` and `reapply` +then exit with `1` without touching the file. `prune` lists such entries as orphans. -```bash -vendor/bin/scaffold status +Tables, diffs and summary lines go to stdout; notices, warnings and errors go to stderr, prefixed with `[scaffold]`. On +an ANSI-capable terminal, diffs are colorized; pass `--no-ansi` for plain output. + +## status + +```text +vendor/bin/scaffold status [--format=table|json] [--exit-code] ``` -Example output: +Compares every tracked file with the disk and with the current provider stubs, and lists the provider files that are not +tracked yet. Output after a provider release that changed `.styleci.yml` (edited in the project) and dropped +`.github/linters/.gitleaks.toml`: ```text -File Provider Mode Status --------------------------------------------------------------------------------------------- -config/params.php php-forge/baseline replace synced -config/web.php php-forge/baseline preserve synced -.env.example php-forge/baseline append modified -docker/nginx/nginx.conf php-forge/coding-standard replace missing +File Provider Mode Status +----------------------------------------------------------------------------------------- +.editorconfig php-forge/baseline append synced +.gitattributes php-forge/baseline replace synced +.github/linters/.codespellrc php-forge/baseline replace synced +.github/linters/.editorconfig-checker.json php-forge/baseline replace synced +.github/linters/.gitleaks.toml php-forge/baseline replace orphan +.github/linters/.markdown-lint.yml php-forge/baseline replace synced +.gitignore php-forge/baseline append synced +.styleci.yml php-forge/baseline replace conflict +composer-require-checker.json php-forge/baseline preserve synced +ecs.php php-forge/coding-standard preserve synced +rector.php php-forge/coding-standard preserve synced +[scaffold] 11 files: 9 synced, 1 conflict, 1 orphan. ``` -| Status | Meaning | -| ---------- | -------------------------------------------------------------- | -| `synced` | On-disk hash matches the hash recorded at scaffold time. | -| `modified` | The file has been changed since the last scaffold run. | -| `missing` | The file was written by scaffold but no longer exists on disk. | +The generated +[`FileStatus` API reference](https://yii2-framework.github.io/docs/extensions/scaffold/reference/services/filestatus/) +defines every state. A tracked file gets the first applicable state in this evaluation order: `ejected`, `error` for an +unsafe lock destination, `orphan`, `missing`, `error` for a read, manifest or stub failure, `conflict`, `modified`, +`outdated`, then `synced`. After tracked entries, provider mappings without a lock entry are reported as `pending`. + +Notices on stderr: + +- Provider version drift between the lock and the installed package: + `[scaffold] php-forge/baseline: lock 0.2.0, installed 0.2.1 (run composer install).` +- Entries written before stub hashes were recorded: + `[scaffold] 3 entries lack stub-hash; run composer install to refresh.` +- Lock entries of providers that are no longer allowed, and manifests that cannot be loaded. + +`--format=json` prints one JSON document on stdout and nothing else: + +```json +{ + "files": { + ".styleci.yml": { + "provider": "php-forge/baseline", + "mode": "replace", + "status": "conflict" + } + }, + "providers": { + "php-forge/baseline": { + "lock": "0.2.1", + "installed": "0.2.1" + } + }, + "summary": { + "total": 11, + "synced": 9, + "pending": 0, + "outdated": 0, + "modified": 0, + "conflict": 1, + "missing": 0, + "orphan": 1, + "ejected": 0, + "error": 0 + } +} +``` -## vendor/bin/scaffold diff `` +| Key | Type | +| ----------- | --------------------------------------------------------------------------------------------------------- | +| `files` | Object keyed by destination; each value has `provider`, `mode` and `status` (one of the states above). | +| `providers` | Object keyed by the providers recorded in the lock; `lock` and `installed` are version strings or `null`. | +| `summary` | `total` and one count per state, always all ten keys, in the order shown. | -Shows a git-style unified diff between the provider stub and the current on-disk file. +`status` exits with `1` when any file is in the `error` state. With `--exit-code`, it also exits with `1` when any file +is neither `synced` nor `ejected`, `pending` included; this is the CI gate: ```bash -vendor/bin/scaffold diff config/params.php +vendor/bin/scaffold status --exit-code ``` -The output starts with `--- a/` / `+++ b/` headers followed by `@@` hunk headers with three lines of -context. Lines present only in the stub are prefixed with `-`, and lines present only in the current file with `+`. On -ANSI-capable terminals the diff is colorized (bold headers, cyan hunks, green additions, red removals); pass `--no-ansi` -to force plain output. +## diff -```diff ---- a/config/params.php -+++ b/config/params.php -@@ -1 +1 @@ --return []; -+return ['adminEmail' => 'admin@example.com']; +```text +vendor/bin/scaffold diff | --all [--exit-code] ``` -## vendor/bin/scaffold reapply `[file]` `[--force]` `[--provider=]` +Shows what applying the provider would change right now, as a Git-style unified diff from the current file (`a/`) +to the result of the apply (`b/`), rendered by [php-forge/diff](https://github.com/php-forge/diff) with Git's +default algorithm. `--all` covers every tracked, non-ejected file in lock order and reports orphans without diffing +them. Pass exactly one of `` and `--all`. -Re-copies stubs from `vendor/` to the project, updating `scaffold-lock.json` hashes on success. +```text +[scaffold] .github/linters/.gitleaks.toml: orphan; no allowed provider ships it anymore. +[scaffold] .gitignore: no changes. +[scaffold] .styleci.yml (replace, php-forge/baseline): changes applying the provider would make (user-modified: scaffold skips it; use reapply --force) +--- a/.styleci.yml ++++ b/.styleci.yml +@@ -1,5 +1,5 @@ +-preset: psr12 +-risky: false ++preset: per ++risky: true + + version: 8.3 -```bash -# reapply a single file -vendor/bin/scaffold reapply config/params.php +``` + +- `replace` diffs to the stub. A user-modified file gets the suffix + `(user-modified: scaffold skips it; use reapply --force)`. +- `preserve` diffs to the stub with the suffix `(preserve: applied only with reapply --force)`. +- `append` and `prepend` diff to the merge result, so a file that already holds every provider entry prints + `[scaffold] : no changes.` +- A missing file diffs from empty. A file that differs only in line endings prints `differs only in line endings.` +- An ejected file prints `[scaffold] : ejected; scaffold does not manage it (see reapply --force).` + +`diff` exits with `1` when the file is not tracked, an entry is unsafe, its provider is not allowed or its manifest +cannot be loaded, or a file cannot be read. With `--exit-code`, it also exits with `1` when applying would change any +file. + +## reapply -# reapply all files from one provider -vendor/bin/scaffold reapply --provider=php-forge/baseline +```text +vendor/bin/scaffold reapply [] [--provider=] [--force] [--dry-run] [--exit-code] +``` -# reapply all tracked files -vendor/bin/scaffold reapply +Applies the stubs of the tracked files again and records the new hashes. `` and `--provider` restrict the run to +one destination or one provider. -# overwrite even user-modified files -vendor/bin/scaffold reapply config/params.php --force +```text +[scaffold] ".editorconfig" is already up to date. +[scaffold] Reapplied ".gitattributes". +[scaffold] Reapplied ".github/linters/.codespellrc". +[scaffold] Reapplied ".github/linters/.editorconfig-checker.json". +[scaffold] Reapplied ".github/linters/.markdown-lint.yml". +[scaffold] ".gitignore" is already up to date. +[scaffold] reapply: 4 written, 2 unchanged, 5 skipped (1 orphaned, 1 user-modified, 3 preserve), 0 errors. ``` -Without `--force`, files whose on-disk hash differs from the lock hash are reported and skipped. With `--force`, -user-modified files are overwritten and the lock hash is updated. +with the skip reasons on stderr: -## vendor/bin/scaffold eject `` `[--yes]` +```text +[scaffold] ".github/linters/.gitleaks.toml" is orphaned; run "vendor/bin/scaffold prune" to review. +[scaffold] ".styleci.yml" is user-modified. Use --force to overwrite. +[scaffold] "composer-require-checker.json" uses mode "preserve". Use --force to overwrite. +[scaffold] "ecs.php" uses mode "preserve". Use --force to overwrite. +[scaffold] "rector.php" uses mode "preserve". Use --force to overwrite. +``` -Removes a file entry from `scaffold-lock.json` without deleting the file from disk. After ejection the file is no longer -managed by scaffold. +- Without `--force`: `replace` files are rewritten unless they are user-modified or adopted; `append` and `prepend` + files are merged as on a Composer run; existing `preserve` files and ejected files are skipped. +- With `--force`: every matching file is rewritten from its stub, user-modified, adopted, `preserve`, `append`, + `prepend` and ejected files included; the `ejected` and `adopted` flags are cleared. Consumer additions to `append` + and `prepend` files are lost. +- Orphans are always skipped, even with `--force`. +- `--dry-run` prints the diff of every file that would change, as `diff` does, and writes nothing. With `--exit-code`, a + dry run exits with `1` when any file would change. -```bash -# preview what would happen -vendor/bin/scaffold eject config/params.php +`reapply` exits with `1` when `` or `--provider` matches no tracked file, or when an entry is skipped for an error +(unsafe entry, provider not allowed, missing stub, unknown mode, read, hash or write failure). Skips for user-modified, +`preserve`, ejected and orphaned files are not errors. + +## eject -# perform the ejection -vendor/bin/scaffold eject config/params.php --yes +```text +vendor/bin/scaffold eject [--yes] ``` -Without `--yes`, the command only describes what would happen and exits without modifying the lock. +Marks a tracked file as `ejected` in `scaffold-lock.json`. The file stays on disk and in the lock, and no Composer run, +`sync` or `reapply` without `--force` writes it again. `vendor/bin/scaffold reapply --force` takes it back. -## vendor/bin/scaffold providers +```text +$ vendor/bin/scaffold eject .styleci.yml +[scaffold] Would eject ".styleci.yml": it will not be managed until reapplied with --force. Run with --yes to confirm. +$ vendor/bin/scaffold eject .styleci.yml --yes +[scaffold] Ejected ".styleci.yml": it will not be managed until reapplied with --force. The file was not deleted from disk. +``` -Lists all providers recorded in `scaffold-lock.json` with their file counts. +`eject` exits with `1` when the file is not tracked. Ejecting an ejected file prints `is already ejected.` and exits +with `0`. -```bash -vendor/bin/scaffold providers +## prune + +```text +vendor/bin/scaffold prune [--force] [--delete-modified] [--exit-code] ``` -Example output: +Lists the orphans: tracked files that no allowed and installed provider ships anymore, because the provider dropped the +file, or the provider was removed from `allowed-packages` or uninstalled. Ejected files are never orphans. Without +`--force`, `prune` only prints a table: ```text -Provider Files ----------------------------------------------------- -php-forge/baseline 4 -php-forge/coding-standard 2 +File Provider Disk With --force +---------------------------------------------------------------------------- +.github/linters/.gitleaks.toml php-forge/baseline unmodified delete +[scaffold] prune --dry-run: 1 would be removed, 0 would be kept (modified), 0 errors; run with --force to apply. ``` -## Typical post-install workflow +| Disk | Meaning | With `--force` | +| ------------ | ------------------------------------------------------------------------------ | ------------------------------------ | +| `unmodified` | The file holds only the provider content of the last apply. | `delete` | +| `modified` | The file changed since the last apply. | `keep` (`--delete-modified` deletes) | +| `merged` | An `append` or `prepend` file that also holds consumer content. | `keep` (`--delete-modified` deletes) | +| `adopted` | The file existed before scaffold tracked it. | `keep` (`--delete-modified` deletes) | +| `missing` | The file is already gone. | `drop entry` | +| `unsafe` | The destination in the lock fails path validation; nothing is touched on disk. | `drop entry` | +| `error` | The destination cannot be read, for example a directory; nothing is touched. | `keep` (never deleted) | -```bash -# 1. Check what changed after composer update -vendor/bin/scaffold status +```text +$ vendor/bin/scaffold prune --force +[scaffold] Deleted ".github/linters/.gitleaks.toml". +[scaffold] prune: 1 removed, 0 kept (modified), 0 errors. +``` + +- `--force` removes every orphan entry from the lock, deletes the `unmodified` files and the empty directories they + leave (never the project root), keeps every other file on disk as yours, and removes the providers that have no entry + left and are no longer allowed or installed. +- `--delete-modified` (destructive, only with `--force`) also deletes `modified`, `merged` and `adopted` orphans and + prints each path. +- `--exit-code` (without `--force`) exits with `1` when orphans exist. -# 2. Review a modified file -vendor/bin/scaffold diff config/params.php +`prune` exits with `1` when a provider manifest cannot be loaded (the orphans of that provider are never pruned), an +orphan is in the `error` state, or a file cannot be deleted. An empty parent directory that cannot be removed is only +reported. -# 3a. Accept the stub version (overwrite) -vendor/bin/scaffold reapply config/params.php --force +## sync -# 3b. Keep your version and stop tracking it -vendor/bin/scaffold eject config/params.php --yes +```text +vendor/bin/scaffold sync [--dry-run] [--exit-code] [--force] ``` -## Exit codes +Applies every allowed and installed provider exactly as a Composer run does, without Composer: for projects with +`auto: false`, installs run with `--no-plugins`, bots and CI. It creates `scaffold-lock.json` when it is missing. + +```text +$ vendor/bin/scaffold sync --dry-run --exit-code +... +[scaffold] sync --dry-run: 10 files would change, 0 unchanged, 0 orphan, 0 errors. +$ vendor/bin/scaffold sync +[scaffold] sync: 10 files written, 0 unchanged. +``` + +- `--dry-run` prints, for every file the providers ship, the diff that applying it would make (as `diff`), then the + orphans on stderr, and writes nothing. A file that is not tracked yet counts as a change. +- `--exit-code` (with `--dry-run`) exits with `1` when applying would write a file or add an entry to the lock. +- `--force` overwrites user-modified and adopted `replace` files, as `reapply --force` does. + +`sync` exits with `1` when a provider manifest is invalid (nothing is applied), a file fails to apply, or the lock +cannot be read or written. With no `allowed-packages`, it prints `No allowed-packages configured. Nothing to sync.` and +exits with `0`. + +## providers + +```text +vendor/bin/scaffold providers +``` + +Lists the providers recorded in `scaffold-lock.json` with the number of tracked files of each: + +```text +Provider Files +-------------------------------- +php-forge/baseline 9 +php-forge/coding-standard 2 +``` + +## Typical workflow -All commands follow standard Symfony Console conventions: +```bash +composer update # install a provider release +vendor/bin/scaffold status # what needs attention +vendor/bin/scaffold diff --all # what applying the providers would change +vendor/bin/scaffold reapply .styleci.yml --force # take the provider version of a file +vendor/bin/scaffold eject .styleci.yml --yes # or keep yours for good +vendor/bin/scaffold prune # review files no provider ships anymore +``` -| Code | Meaning | -| ---- | ---------------------------------------------------------------------------------------------------------------------------- | -| `0` | Success (including preview / no-op runs). | -| `1` | Recoverable error (for example, untracked file passed to `diff` / `eject`, or filter in `reapply` matched no tracked files). | -| `2` | Input validation error raised by Symfony Console (for example, missing required argument). | +In CI, fail the build when the committed files drift from the providers: + +```bash +vendor/bin/scaffold status --exit-code +``` + +## Exit codes -Use the exit code in CI scripts to halt on failures (for example, `vendor/bin/scaffold status` always returns `0` -regardless of `modified` / `missing` entries; inspect the text output yourself if you want CI to gate on drift). +| Code | Meaning | +| ---- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `0` | Success, including previews, skips and runs that change nothing. | +| `1` | Error: no project root, unreadable lock or `composer.json`, untracked file, unsafe entry, provider not allowed, invalid manifest, missing stub, write failure, `status` entry in the `error` state, unknown option or missing argument. With `--exit-code`, also drift or pending changes. | +| `2` | Invalid input detected by the command: `diff` without a file and without `--all`, or with both; `status --format` other than `table` or `json`. | ## Next steps diff --git a/docs/installation.md b/docs/installation.md index 2c818df..87586cd 100644 --- a/docs/installation.md +++ b/docs/installation.md @@ -3,24 +3,30 @@ ## System requirements - [PHP](https://www.php.net/downloads) `8.3` or higher. -- [Composer](https://getcomposer.org/download/) `2.9` or higher. +- [Composer](https://getcomposer.org/download/) `2.3` or higher (the plugin requires `composer-plugin-api` `^2.3`). +- [Symfony Console](https://symfony.com/doc/current/components/console.html) `^7.4` or `^8.0`, installed as a + dependency. Symfony Console 8 requires PHP 8.4, so a project on PHP 8.3 resolves 7.4. +- [php-forge/diff](https://github.com/php-forge/diff), installed as a dependency, which renders the unified diffs with + Git's default algorithm (Myers with the indent heuristic). -The plugin is framework-agnostic. It works in Yii2, Yii3, Laravel, Symfony, Slim, Mezzio, or plain PHP projects as long -as they use Composer. +The plugin is framework-agnostic: it works in any project managed by Composer. -## Installation +## Install the plugin -Allow the Composer plugin, then install it: +Scaffolding is a development-time task, so require the plugin in `require-dev` and allow it to run: ```bash composer config allow-plugins.php-forge/scaffold true -composer require php-forge/scaffold:^0.3 +composer require --dev php-forge/scaffold:^0.3 ``` -Alternatively, add the permission to your `composer.json` before running `composer require`: +The equivalent `composer.json` configuration is: ```json { + "require-dev": { + "php-forge/scaffold": "^0.3" + }, "config": { "allow-plugins": { "php-forge/scaffold": true @@ -29,10 +35,16 @@ Alternatively, add the permission to your `composer.json` before running `compos } ``` -## Authorize scaffold providers +Without the `allow-plugins` entry, Composer asks whether to trust the plugin, and non-interactive runs such as CI fail. -Install the scaffold provider packages required by your project, then declare which are permitted to write files under -`extra.scaffold.allowed-packages`. The plugin ignores all providers that are not listed here. +## Authorize providers + +Require the provider packages and list, in order, the ones allowed to write files into the project. Packages that are +not listed are ignored. + +```bash +composer require --dev php-forge/baseline php-forge/coding-standard +``` ```json { @@ -44,34 +56,82 @@ Install the scaffold provider packages required by your project, then declare wh } ``` -Run `composer install` or `composer update` to trigger the scaffold process. The plugin applies all file mappings -declared by the listed providers and writes `scaffold-lock.json`. +Run `composer install` or `composer update`. The plugin applies the files of every listed provider, writes +`scaffold-lock.json`, and ends with a summary line on stdout: + +```text +[scaffold] 10 files written, 1 unchanged, 1 warning. +``` + +Warnings, such as an existing file that the first install overwrote, are printed on stderr above it; see +[File Modes](modes.md#replace). Review the result with `git diff`. -## Commit the lockfile +## Commit the lock file -`scaffold-lock.json` records the hash of every file written by the scaffold process. Commit it to version control -alongside `composer.lock` so that collaborators and CI can detect user-modified files and reproduce the exact scaffold -state. +`scaffold-lock.json` records which provider owns each file, how it was written and the hashes of the last apply. Commit +it with the scaffolded files, so every clone and CI job detects user-modified files and provider updates the same way: ```bash git add scaffold-lock.json -git commit -m "chore: add scaffold-lock.json" ``` -## Invoke the console CLI +## Composer flags + +The plugin listens to Composer events as a plugin, not as a script: + +| Command | Scaffolds? | +| -------------------------------- | ------------------------------------------------------------------------ | +| `composer install` | Yes. | +| `composer install --no-scripts` | Yes: `--no-scripts` disables scripts, not plugin event subscribers. | +| `composer install --no-plugins` | No: the plugin is not loaded. Run `vendor/bin/scaffold sync` afterwards. | +| `composer install --no-dev` | No, on a fresh install: the plugin in `require-dev` is not installed. | +| Any command with `"auto": false` | No: run `vendor/bin/scaffold sync` when you want to apply the providers. | + +## Manual mode with auto: false + +To review every change to the shared files before it lands, disable the Composer hooks and apply the providers with the +console: + +```json +{ + "extra": { + "scaffold": { + "auto": false, + "allowed-packages": ["php-forge/baseline", "php-forge/coding-standard"] + } + } +} +``` + +Composer runs then print +`[scaffold] Auto-scaffold disabled via "extra.scaffold.auto"; run "vendor/bin/scaffold" manually.` Bootstrap the project +with `sync`, which also creates `scaffold-lock.json`: + +```text +$ vendor/bin/scaffold status +... +[scaffold] 10 files: 10 pending. +$ vendor/bin/scaffold sync --dry-run --exit-code +... +[scaffold] sync --dry-run: 10 files would change, 0 unchanged, 0 orphan, 0 errors. +$ vendor/bin/scaffold sync +[scaffold] sync: 10 files written, 0 unchanged. +``` + +Run `vendor/bin/scaffold sync` again after each provider update. + +## Invoke the console -After `composer install`, the Symfony Console CLI is available at `vendor/bin/scaffold`: +The plugin installs a standalone console application at `vendor/bin/scaffold`; it starts from Composer's autoloader and +needs no framework bootstrap: ```bash -vendor/bin/scaffold list # discover available commands -vendor/bin/scaffold status # what changed since last scaffold? -vendor/bin/scaffold providers # list providers + file counts -vendor/bin/scaffold diff config/params.php # review changes on a single file -vendor/bin/scaffold reapply --force # replay stubs, overwriting user edits -vendor/bin/scaffold eject config/params.php --yes # detach a file from the lock +vendor/bin/scaffold list # available commands +vendor/bin/scaffold status # state of every scaffolded file +vendor/bin/scaffold diff --all # what applying the providers would change ``` -No framework bootstrap is required; the binary starts directly from Composer's autoloader. +See [Console Commands](console.md) for every command and option. ## Next steps diff --git a/docs/modes.md b/docs/modes.md index 94d003c..cdd2138 100644 --- a/docs/modes.md +++ b/docs/modes.md @@ -1,109 +1,215 @@ # File modes -Provider manifests list source paths in `copy` and select write modes by destination path or glob in `modes`. The -default mode is `replace`. The mode also determines how the hash-tracking mechanism reacts when a file has been modified -by the developer after scaffolding. +A provider manifest assigns a write mode to each destination through its `modes` map; a destination without a matching +pattern uses `replace`. Every mode runs on every `composer install`, `composer update` and `composer create-project`, +and on `vendor/bin/scaffold sync`. All modes are idempotent: a second run with the same provider and the same project +files writes nothing. ## Mode reference -| Mode | File absent | File present (unmodified) | File present (user-modified) | -| ---------- | -------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------- | -| `replace` | Writes stub, records hash. | Overwrites with stub, updates hash. | **Skips** emits warning to stderr. | -| `preserve` | Writes stub, records hash. | **Skips**; never overwrites. | **Skips**; never overwrites. | -| `append` | Writes stub, records hash. | Inserts missing stub lines at their contextual position (idempotent LCS line merge); updates hash. Returns `Skipped` when every stub line is already in the file. | Inserts missing stub lines at their contextual position (idempotent LCS line merge); user lines are kept. | -| `prepend` | Writes stub, records hash. | Prepends stub content before existing content, updates hash (full scaffold only; skipped on `post-install-cmd`/`post-update-cmd` if already in lock). | Prepends stub content, updates hash (full scaffold only). | +| Mode | Destination missing | Destination exists, not tracked yet | Destination tracked and unchanged since the last apply | Destination changed since the last apply | +| ---------- | ------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------- | +| `replace` | Copies the stub. | Overwrites it with the stub. When the content differed, prints `Overwrote untracked existing file ""; review it with git diff or run "scaffold eject --yes" to keep your version.` | Copies the current stub, so provider updates arrive. | Skips it with `User-modified file skipped: "".`; a changed provider stub makes it a `conflict`. | +| `preserve` | Copies the stub. | Keeps it and records it with `adopted: true`. | Keeps it. | Keeps it. | +| `append` | Copies the stub. | Adds the provider entries the file lacks, with the [merge strategy](#append) of the destination. | Adds the provider entries the file lacks. | Adds the provider entries the file lacks; consumer lines are never removed, reordered or overridden. | +| `prepend` | Copies the stub. | Inserts the stub block at the top unless the file already contains it. | Inserts the stub block unless the file contains it. | Inserts the stub block unless the file contains it; a block moved elsewhere in the file still counts as present. | + +Files ejected with `vendor/bin/scaffold eject --yes` are never written by any mode until +`vendor/bin/scaffold reapply --force` takes them back. `replace` and `preserve` copy the file permissions of the +stub; `append` and `prepend` keep the permissions of the existing file. ## Hash tracking -After writing a file the plugin computes `sha256:` and records it in `scaffold-lock.json`. -On subsequent runs the plugin compares the current on-disk hash to the recorded hash: +`scaffold-lock.json` records two hashes per file, both `sha256:` of the file bytes: + +- `hash`: the destination as scaffold last left it. When the destination exists and scaffold did not write it (an + adopted `preserve` file, an `append` file that already held every entry), it is the hash of the file at that moment. +- `stub-hash`: the provider source at the last apply. Comparing it with the current stub tells a provider change apart + from a local edit. + +How each mode uses them: -- **Hashes match**; the file has not been changed since the last scaffold run. The plugin re-applies the stub (for - `replace`) or skips (for `preserve`). -- **Hashes differ**; the developer has modified the file. For `replace`, the plugin skips the file and writes a warning - to stderr. For `preserve`, the file is always skipped regardless of hash. +| Mode | `hash` decides | `stub-hash` decides | +| ---------- | ------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------- | +| `replace` | Whether the file is user-modified (the disk hash differs), so the next run skips it. | Whether a skipped file is a `conflict`, and whether `status` says `outdated`. | +| `preserve` | Whether `status` reports `modified`. | Whether `status` and the run summary report `outdated`. | +| `append` | Nothing during a run; the merge itself decides what to write. | Whether `prune` treats an orphan as provider-only content. | +| `prepend` | Nothing during a run; the block search decides what to write. | Whether `prune` treats an orphan as provider-only content. | -`append` does not compare hashes; instead it diffs the stub lines against the destination and inserts only the missing -ones at their contextual position. The operation is therefore idempotent: repeated runs over a file that already -contains every stub line are a no-op. On partial scaffold runs (`post-install-cmd`, `post-update-cmd`), `append` and -`prepend` are also skipped at the scaffolder level for files already recorded in the lockfile as a performance -optimisation; the line-diff guarantees correctness even without that skip. +A `replace` or `preserve` file recorded with `adopted: true` existed before scaffold tracked it, so scaffold never +treats it as pristine: if the provider later switches it to `replace`, it is skipped as user-modified until +`reapply --force` or `sync --force`. ## replace -Intended for configuration files that the scaffold system owns. The developer is expected to leave these files as-is or -accept that custom changes may be warned about on re-scaffold. +For files that the provider owns, such as linter configuration. Leave them unchanged to keep receiving updates; editing +one stops the updates for that file until you take the provider version back. ```json { - "copy": [{"from": "stubs/config/params.php", "to": "config/params.php"}], - "modes": {"config/params.php": "replace"} + "copy": [{ "from": "metadata/.styleci.yml", "to": ".styleci.yml" }] } ``` +The first install overwrites an existing file that scaffold does not track yet, so the provider version wins on +adoption. Review the result with `git diff`; to keep your version, run `vendor/bin/scaffold eject --yes`, restore +the file from Git, and commit both. + ## preserve -Intended for files that provide sensible defaults but are designed to be customised by the developer. Once written, the -file is never touched again by the scaffold process. +For files that the provider seeds once and the project then owns, such as `ecs.php` and `rector.php` of +`php-forge/coding-standard`. Composer runs and `sync` never overwrite an existing `preserve` file; only +`vendor/bin/scaffold reapply --force` does. ```json { - "copy": [{"from": "stubs/config/db.php", "to": "config/db.php"}], - "modes": {"config/db.php": "preserve"} + "copy": [ + { "from": "src/config/ecs.php", "to": "ecs.php" }, + { "from": "src/config/rector.php", "to": "rector.php" } + ], + "modes": { + "ecs.php": "preserve", + "rector.php": "preserve" + } } ``` -## append - -Idempotent contextual line merge. The plugin reads both the stub and the destination, splits each on `\n` (after -trimming the trailing newline), and inserts the stub lines missing from the destination at their contextual position, -aligned against shared anchor lines (LCS). Presence is order-independent: a destination that contains every stub line in -a different order is left untouched. Existing lines keep their original terminators (mixed EOLs included); inserted -lines use the destination's dominant EOL. Repeated runs over a destination that already contains every stub line are a -no-op (`ApplyOutcome::Skipped`); developer-added lines are never removed or reordered. +When a provider release changes a `preserve` stub, the run that installs it counts the file as `outdated` in its summary +line and records the new `stub-hash`; the file itself is not touched. `vendor/bin/scaffold diff ` shows the +provider version labelled `(preserve: applied only with reapply --force)`. -Use it for line-based, comment-tolerant files where the destination may already contain the stub content (because the -project follows the same baseline) or where the developer routinely adds project-specific entries: +## append -- `.gitignore`, `.gitattributes`, `.editorconfig` -- `.prettierignore`, `.stylelintignore` -- Environment variable lists, plain-text allowlists +A format-aware, idempotent merge for files that the provider and the project both extend, such as `.editorconfig` and +`.gitignore` of `php-forge/baseline`. The merge adds the provider entries missing from the destination and never +removes, reorders or overrides consumer content. Inserted lines use the line endings of the destination (CRLF when the +file contains any). ```json { - "copy": [{"from": "stubs/gitignore-additions.txt", "to": ".gitignore"}], - "modes": {".gitignore": "append"} + "copy": [ + { "from": "metadata/.editorconfig", "to": ".editorconfig" }, + { "from": "metadata/.gitignore", "to": ".gitignore" } + ], + "modes": { + ".editorconfig": "append", + ".gitignore": "append" + } } ``` -> **Note:** `append` operates at the line level. It is not safe for structured documents (JSON, YAML, TOML, XML); use -> `replace` or `preserve` for those. +The manifest `merge` map selects the strategy per destination (see [Creating Providers](providers.md#manifest-keys)); +without a match, the basename of the destination decides: + +| Strategy | Default for | +| -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `ini` | `.editorconfig` and every `*.ini` file. | +| `list` | `.codespellignore`, `.dockerignore`, `.eslintignore`, `.gitattributes`, `.gitignore`, `.markdownlintignore`, `.npmignore`, `.prettierignore`, `.stylelintignore`. | +| `text` | Every other file. | + +### ini + +- Keys before the first section (such as `root = true`) are added after the last such key of the destination, or at the + top. +- A section is identified by its header text: `[*.js]` and `[*.{cjs,js,mjs}]` are different sections. +- A key missing from a section that the destination has is added after the last key of the first occurrence of that + section. Key names are compared case-insensitively. +- An existing key is never duplicated or changed: the consumer value wins, `unset` included. +- A missing section is appended at the end as a whole block, with the comment lines directly above its header. +- `#` and `;` start comments. + +Provider `.editorconfig` merged into a destination that sets `indent_size = 2` for `[*]`: + +```ini +root = true + +[*] +indent_size = 2 +charset = utf-8 +end_of_line = lf +insert_final_newline = true +indent_style = space +trim_trailing_whitespace = true + +[*.js] +indent_size = 2 +``` + +### list + +- Entries are the non-blank lines that do not start with `#`, compared after trimming and byte for byte: `vendor` and + `/vendor` are different entries. Comments and blank lines never count as entries. +- The provider file is read as blocks: comment lines followed by entries, separated by a blank line or by a comment that + follows an entry. +- When the destination contains the first comment line of a block, the missing entries of that block are added after the + last entry under that comment. Otherwise the block is appended at the end with its comments. + +> **Note:** ignore files are order-sensitive: the last matching rule wins. An entry appended at the end lands after +> every consumer line, so it overrides a consumer negation that targets it. For example, a provider block `*.log` +> appended after a consumer `!keep.log` ignores `keep.log` again. Move the negation below the appended block, or ask the +> provider to ship the negation. + +### text + +- Every non-blank provider line missing from the destination (compared after trimming trailing whitespace) is appended + at the end, after a blank line, in provider order. +- Lines are compared whole, so `text` does not understand keys: a provider `APP_ENV=dev` is added below a consumer + `APP_ENV=prod`. + +Do not use `append` for structured documents (JSON, YAML, TOML, XML); use `replace` or `preserve` for those. ## prepend -Prepends the stub content before the existing destination content. Useful for inserting PHP `declare(strict_types=1)` -headers, autoload includes, or licence headers. +Inserts the stub at the top of the destination, for example a license or "generated file" notice in a text file. The +block is terminated with the end-of-line sequence of the destination. Before writing, the mode searches the destination +for the stub lines as one contiguous run (line endings normalised); when it finds them anywhere in the file, it writes +nothing, so repeated runs never duplicate the block. ```json { - "copy": [{"from": "stubs/bootstrap-header.php", "to": "bootstrap/web.php"}], - "modes": {"bootstrap/web.php": "prepend"} + "copy": [{ "from": "stubs/NOTICE.txt", "to": "NOTICE" }], + "modes": { "NOTICE": "prepend" } } ``` -## --force reapply workflow +Do not prepend to files whose first line is significant, such as PHP files that start with ``, then either take the provider version with +`vendor/bin/scaffold reapply --force` and re-apply your edits, or keep your version for good with +`vendor/bin/scaffold eject --yes`. ## Next steps - 📖 [Readme](../README.md) - 🖥️ [Console Commands](console.md) - ⚙️ [Configuration Reference](configuration.md) +- 📦 [Creating Providers](providers.md) diff --git a/docs/providers.md b/docs/providers.md index 0a81dd7..e8f3df3 100644 --- a/docs/providers.md +++ b/docs/providers.md @@ -1,25 +1,35 @@ # Creating providers -A scaffold provider is a Composer package that declares which of its files scaffold should copy into consumer projects -on `composer install`. +A scaffold provider is a Composer package that declares which of its files scaffold copies into the projects that +install it and allow it in `extra.scaffold.allowed-packages`. No special package type is needed: `php-forge/baseline` +and `php-forge/coding-standard` are plain `library` packages. + +## Manifest keys + +| Key | Required | Value | +| --------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `copy` | Yes | Non-empty list of entries. A string copies the path to the same place in the project; `{"from": ..., "to": ...}` maps a provider path to a project path. A directory is walked recursively. | +| `exclude` | No | List of glob patterns matched against provider-relative source paths found while walking a `copy` directory. | +| `modes` | No | Object of destination path or glob pattern to [file mode](modes.md): `replace` (default), `preserve`, `append` or `prepend`. | +| `merge` | No | Object of destination path or glob pattern to [append strategy](modes.md#append): `ini`, `list` or `text`. | + +Rules: + +- Any other key is rejected, so a typo such as `mode` fails the Composer run instead of silently changing a mode: + `Manifest contains unknown key "mode". Allowed keys: copy, exclude, merge, modes.` +- Every path and pattern must be relative and must not contain `..` segments; absolute paths, `\` prefixes and Windows + drive letters are rejected. A path listed in `copy` must exist in the provider. +- In `modes` and `merge`, an exact destination wins over patterns; patterns are tried in declaration order and the first + match wins. +- `exclude` applies only to the files found while walking a `copy` directory; a file listed explicitly in `copy` is + always copied. `exclude` matches source paths, while `modes` and `merge` match destination paths; the two differ when + `from` and `to` differ. +- Within one provider, a later `copy` entry that produces the same destination replaces the earlier one. Across + providers, the provider listed later in the consumer's `allowed-packages` wins. -Providers do not need a special package type; any installed package can contribute scaffold files once it appears in the -root project's `allowed-packages` list. - -## Manifest shape - -Every provider declares a `scaffold` manifest with three keys: - -- `copy` (required, array of paths) directories or files relative to the provider root. Directories are walked - recursively. -- `exclude` (optional, array of glob patterns) patterns omitted from the walk. Only applies to directory entries in - `copy`; explicit file entries bypass this filter. -- `modes` (optional, map of glob pattern → [file mode](modes.md)) overrides the default write mode per destination. - Exact path matches win over glob matches; the default when no pattern matches is `replace`. - -## Inline manifest +## External manifest -Declare under `extra.scaffold` in the provider's `composer.json`: +Point `extra.scaffold.manifest` at a JSON file inside the provider. `php-forge/baseline` declares: ```json { @@ -27,47 +37,67 @@ Declare under `extra.scaffold` in the provider's `composer.json`: "type": "library", "extra": { "scaffold": { - "copy": [ - {"from": "metadata/.editorconfig", "to": ".editorconfig"}, - {"from": "metadata/gitattributes", "to": ".gitattributes"}, - {"from": "metadata/.gitignore", "to": ".gitignore"}, - {"from": "metadata/.styleci.yml", "to": ".styleci.yml"}, - {"from": "metadata/composer-require-checker.json", "to": "composer-require-checker.json"}, - {"from": "metadata/.github/linters", "to": ".github/linters"} - ], - "modes": { - ".editorconfig": "append", - ".gitignore": "append", - "composer-require-checker.json": "preserve" - } + "manifest": "scaffold.json" } } } ``` -## External manifest +and ships this `scaffold.json`: -For larger providers, point to a `scaffold.json` file next to `composer.json`: +```json +{ + "copy": [ + { "from": "metadata/.editorconfig", "to": ".editorconfig" }, + { "from": "metadata/gitattributes", "to": ".gitattributes" }, + { "from": "metadata/.gitignore", "to": ".gitignore" }, + { "from": "metadata/.styleci.yml", "to": ".styleci.yml" }, + { + "from": "metadata/composer-require-checker.json", + "to": "composer-require-checker.json" + }, + { "from": "metadata/.github/linters", "to": ".github/linters" } + ], + "modes": { + ".editorconfig": "append", + ".gitignore": "append", + "composer-require-checker.json": "preserve" + } +} +``` + +The provider keeps its templates under `metadata/`, so its own `.gitignore` and `.editorconfig` never leak into +consumers. The `.github/linters` directory entry copies every file below it with the default `replace` mode. + +The manifest path is resolved inside the provider's install directory; it must be relative and must not contain `..`. An +external manifest may contain only the four manifest keys. + +## Inline manifest + +The manifest keys can also sit directly under `extra.scaffold` of the provider's `composer.json`. A package that is both +a provider and a consumer keeps its consumer keys (`allowed-packages`, `auto`) in the same block; they apply only when +the package is the root project. `php-forge/coding-standard` combines an external manifest with its own consumer +configuration: ```json { "name": "php-forge/coding-standard", - "type": "library", "extra": { "scaffold": { - "manifest": "scaffold.json" + "manifest": "scaffold.json", + "allowed-packages": ["php-forge/baseline"] } } } ``` -`scaffold.json` at the provider root uses the same `copy` / `exclude` / `modes` shape: +Its `scaffold.json` seeds two files that the consumer owns afterwards: ```json { "copy": [ - {"from": "src/config/ecs.php", "to": "ecs.php"}, - {"from": "src/config/rector.php", "to": "rector.php"} + { "from": "src/config/ecs.php", "to": "ecs.php" }, + { "from": "src/config/rector.php", "to": "rector.php" } ], "modes": { "ecs.php": "preserve", @@ -76,88 +106,81 @@ For larger providers, point to a `scaffold.json` file next to `composer.json`: } ``` -The plugin resolves the path relative to the provider's installation directory inside `vendor/`. +An inline manifest with a `merge` override: `.env.dist` would default to `text`, which compares whole lines; `ini` +compares keys, so a consumer `APP_ENV=prod` is kept and no second `APP_ENV` line is added. -## Glob syntax +```json +{ + "extra": { + "scaffold": { + "copy": [{ "from": "stubs/env.dist", "to": ".env.dist" }], + "modes": { ".env.dist": "append" }, + "merge": { ".env.dist": "ini" } + } + } +} +``` -Patterns in `exclude` and the keys of `modes` support: +## Glob syntax -| Token | Matches | -| ------- | ---------------------------------------------------------------------------------- | -| `*` | Any sequence of characters that does NOT include `/`. | -| `**` | Any sequence of characters including `/` (crosses directories). | -| `**/` | Zero or more directory levels (so `**/.gitignore` also matches root `.gitignore`). | -| `?` | A single character that is not `/`. | -| literal | Any other character matches byte-exact. | +Patterns in `exclude`, `modes` and `merge` match the whole forward-slash path: -## File modes +| Token | Matches | +| ------- | ---------------------------------------------------------------------------------------- | +| `*` | Any sequence of characters except `/`. | +| `**` | Any sequence of characters, `/` included. | +| `**/` | Zero or more directory levels, so `**/.gitignore` also matches the root `.gitignore`. | +| `?` | One character except `/`. | +| `{a,b}` | One of the comma-separated alternatives (one level; braces without a comma are literal). | +| other | The character itself, byte for byte. | -| Mode | Behaviour | -| ---------- | ------------------------------------------------------------------------------------------------------------------- | -| `replace` | Writes the stub. Skips if the destination has been modified by the user since the last scaffold run. | -| `preserve` | Writes the stub only if the destination does not already exist on disk. Never overwrites. | -| `append` | Appends only stub lines not already present in the destination (idempotent line merge). Creates the file if absent. | -| `prepend` | Prepends the stub content before existing destination content. Creates the file if absent. | +## Default excludes -See [File Modes](modes.md) for a detailed description of each mode and the hash-tracking mechanism. +These patterns are always skipped while walking a `copy` directory, so a provider never ships its own development files. +They are matched against the provider-relative source path. The generated API reference lists the exact current +[`DefaultExcludes::PATTERNS`](https://yii2-framework.github.io/docs/extensions/scaffold/reference/manifest/defaultexcludes/#const-PATTERNS); +the guide does not duplicate that implementation-owned list. -## Default excludes +Patterns match the whole path from the provider root: `.gitignore` excludes the root `.gitignore`, not +`metadata/.gitignore`. To ship a file that matches a default exclude, such as `runtime/.gitignore`, list it explicitly +in `copy`. -The following patterns are hardcoded and always skipped when walking a directory listed in `copy`, so providers never -accidentally ship their own development metadata: - -```text -composer.json, composer.lock, vendor/** -.git/**, .github/**, .gitattributes, .gitignore -tests/**, phpunit.xml, phpunit.xml.dist, .phpunit.cache/**, phpunit.cache/** -phpstan.neon, phpstan.neon.dist, phpstan.cache/** -infection.json5, infection.json, infection.log, .infection/** -.editorconfig, .php-cs-fixer.php, .php-cs-fixer.dist.php, ecs.php -psalm.xml, psalm.xml.dist -README.md, CHANGELOG.md, LICENSE, docs/** -scaffold.json, scaffold-lock.json -runtime/** -``` +## Security model -A provider that needs to distribute a file matching one of these patterns (for example, a `runtime/.gitignore` template) -can list the exact path as an explicit file entry in `copy`; explicit file entries bypass the default excludes. - -## Provider layout - -Because `copy` walks the provider tree directly, providers look like real Yii2 apps. There is no `stubs/` wrapper and no -per-file declaration: - -```text -acme/app-backend/ -├── composer.json # declares extra.scaffold or extra.scaffold.manifest -├── scaffold.json # optional external manifest -├── src/ # copied verbatim into the consumer's src/ -├── config/ -├── migrations/ -├── public/ -├── resources/ -├── yii -├── tests/ # default-excluded, lives in the provider for its own CI -├── phpunit.xml # default-excluded -├── phpstan.neon # default-excluded -└── infection.json5 # default-excluded -``` +- **Allowlist**: only packages listed in the consumer's `allowed-packages` are read; any other installed package is + ignored. The console commands report lock entries of providers that are no longer allowed and never read from or write + to them. +- **Paths**: manifest paths and patterns must be relative without `..`. Before each write, the source must resolve + inside the provider root and the destination inside the project root, also through symbolic links, a dangling symbolic + link included. `scaffold-lock.json` is never a valid destination. +- **Failures are loud**: an invalid manifest of an allowed provider fails the Composer run before any file is written; + see [Output and failure policy](configuration.md#output-and-failure-policy). -This layout lets the provider be a standalone Yii2 application: you can run `composer install` inside it, then -`./vendor/bin/phpunit`, `./vendor/bin/phpstan`, and `composer mutation-static` to prove the distributed code works -before any consumer depends on it. +## Test a provider locally -## Security model +Install the provider into a scratch project through a path repository and run the inspection commands: -The plugin validates every entry before writing: +```json +{ + "repositories": [{ "type": "path", "url": "../baseline", "options": { "symlink": false } }], + "require-dev": { + "php-forge/baseline": "@dev", + "php-forge/scaffold": "^0.3" + }, + "config": { + "allow-plugins": { "php-forge/scaffold": true } + }, + "extra": { + "scaffold": { "allowed-packages": ["php-forge/baseline"] } + } +} +``` -- **Package allowlist**: the provider must appear in `allowed-packages`. Unknown providers cause an error and no file is - written. -- **Path traversal rejection**: entries in `copy` and `exclude` must be relative and must not contain `..` segments. - Absolute paths and Windows drive letters are rejected. -- **File existence**: every path listed in `copy` must exist on disk at expansion time; missing entries fail the run - loudly instead of silently skipping. -- **Walk boundary**: the filesystem walk is constrained to the provider's installation directory inside `vendor/`. +```bash +composer install +vendor/bin/scaffold status +vendor/bin/scaffold diff --all +``` ## Next steps diff --git a/docs/svgs/features-mobile.svg b/docs/svgs/features-mobile.svg index 1b3ca7a..f3b9e19 100644 --- a/docs/svgs/features-mobile.svg +++ b/docs/svgs/features-mobile.svg @@ -11,14 +11,14 @@ Agnostic Framework - Console binary at vendor/bin/scaffold • 5 commands • Runs in any PHP project + Console binary at vendor/bin/scaffold • 7 commands • Runs in any PHP project Manifest-driven - Inline + external JSON manifest • 4 file modes • SHA-256 hash per tracked file + Inline + external JSON manifest • 4 file modes • SHA-256 hashes per tracked file diff --git a/docs/svgs/features.svg b/docs/svgs/features.svg index 217265d..b65a962 100644 --- a/docs/svgs/features.svg +++ b/docs/svgs/features.svg @@ -10,14 +10,14 @@ Agnostic Framework - Console binary at vendor/bin/scaffold • 5 commands • Runs in any PHP project + Console binary at vendor/bin/scaffold • 7 commands • Runs in any PHP project Manifest-driven - Inline + external JSON manifest • 4 file modes • SHA-256 hash per tracked file + Inline + external JSON manifest • 4 file modes • SHA-256 hashes per tracked file diff --git a/docs/testing.md b/docs/testing.md index 5c7b212..8944172 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -1,27 +1,64 @@ # Testing -This package provides a consistent set of [Composer](https://getcomposer.org/) scripts for local validation. +This package provides a consistent set of [Composer](https://getcomposer.org/) scripts for local validation. Install the +development dependencies first: + +```bash +composer install +``` Tool references: +- [Actionlint](https://github.com/rhysd/actionlint) for GitHub Actions workflow linting. +- [Codespell](https://github.com/codespell-project/codespell) for spelling checks. - [Composer Require Checker](https://github.com/maglnet/ComposerRequireChecker) for dependency definition checks. - [Easy Coding Standard (ECS)](https://github.com/easy-coding-standard/easy-coding-standard) for coding standards. +- [EditorConfig Checker](https://github.com/editorconfig-checker/editorconfig-checker) for EditorConfig compliance. +- [Gitleaks](https://github.com/gitleaks/gitleaks) for secret scanning. - [Infection](https://infection.github.io/) for mutation testing. +- [Markdownlint-cli2](https://github.com/DavidAnson/markdownlint-cli2) for Markdown linting. - [PHPStan](https://phpstan.org/) for static analysis. -- [PHPUnit](https://phpunit.de/) for unit tests. +- [Prettier](https://prettier.io/) for Markdown and YAML formatting checks. - [Rector](https://github.com/rectorphp/rector) for automated refactoring. +- [Testo](https://github.com/php-testo/testo) for unit, functional and real-Composer tests. +- [Yamllint](https://github.com/adrienverge/yamllint) for YAML linting. +- [Zizmor](https://github.com/zizmorcore/zizmor) for GitHub Actions security audits. + +The Testo configuration lives in `testo.php` and defines two suites: + +- `Unit` reads `tests/` without `tests/Composer`, `tests/Fixtures`, `tests/Provider` and `tests/Support`. It holds the + unit, command and functional tests, which run in the current process. +- `Composer` reads `tests/Composer`. It runs a real Composer binary in subprocesses against temporary projects (see + [Real Composer tests](#real-composer-tests)). + +Both suites fail a test on any PHP warning, notice or deprecation, and on a test without assertions +(`tests/Support/StrictTestPlugin.php`). Filesystem failures are exercised against the real filesystem (a directory where +a file is expected, a regular file as a parent directory, a missing source, `chmod 0000`), without function mocks; the +`chmod` cases are skipped on Windows and when running as root. ## Automated refactoring (Rector) -Run Rector to apply automated code refactoring. +Run Rector to apply automated code refactoring. This command modifies files. ```bash composer rector ``` +Preview the refactoring without modifying files. + +```bash +composer rector -- --dry-run +``` + ## Coding standards (ECS) -Run Easy Coding Standard (ECS) and apply fixes. +Check coding standards without modifying files. + +```bash +vendor/bin/ecs check +``` + +Apply coding standard fixes. Review the changes before keeping them. ```bash composer ecs @@ -37,48 +74,102 @@ composer check-dependencies ## Mutation testing (Infection) -Run mutation testing. +Run mutation testing with PHPStan static analysis enabled. Infection runs the `Unit` suite through +`testo/bridge-infection`. This is the command CI runs. ```bash -composer mutation +composer mutation-static ``` -Run mutation testing with static analysis enabled. +Run mutation testing without static analysis. ```bash -composer mutation-static +composer mutation ``` +Both runs reach the required score without ignored mutants. Thresholds, thread count and memory options live in +`infection.json5`; the package requires a 100 % mutation score indicator (MSI) and covered MSI. The `Composer` suite is +left out because its subprocesses install a snapshot of the working tree instead of running the mutated code. + +## Repository quality and security checks + +The `quality` workflow runs Actionlint and uses the repository configurations for Codespell, EditorConfig Checker, +Markdownlint-cli2, Prettier and Yamllint. The `security` workflow runs Zizmor with its pedantic persona and Gitleaks +with the repository configuration. These checks are not exposed as Composer scripts in this package; run the individual +tools directly with the checked-in configuration when reproducing a hosted check locally. + +Report hosted workflow execution separately from local commands. Keep generated reports in ignored `internal/` or +`runtime/` paths. + ## Static analysis (PHPStan) -Run static analysis. +Run static analysis at level max with the strict checks from `phpstan.neon`. The Composer script removes the PHP memory +limit. ```bash composer static ``` -## Unit tests (PHPUnit) +## Tests (Testo) -Run the full test suite. +Run both suites. ```bash composer tests ``` -## Passing extra arguments +Run only the `Unit` suite. -Composer scripts support forwarding additional arguments using `--`. +```bash +composer tests-unit +``` + +CI runs the suites on PHP 8.3, 8.4 and 8.5, on Ubuntu and Windows, and uploads the coverage to Codecov. + +### Real Composer tests + +The `Composer` suite covers the plugin lifecycle and the provider integration that an in-process test cannot reproduce: +`composer install`, `update` and `create-project` against a snapshot of this working tree and a provider fixture, +offline. The harness uses the `COMPOSER_BINARY` environment variable when set; otherwise it looks for `composer.phar` +and then `composer` on `PATH`. When none is available, every test of the suite is skipped. + +Run only this suite: + +```bash +composer tests -- --suite=Composer +``` + +Run it with a specific Composer PHAR: + +```bash +COMPOSER_BINARY=/path/to/composer.phar composer tests -- --suite=Composer +``` + +### Running one test -Run PHPUnit with code coverage report generation. +Filter the tests by class or method name (the match is case-sensitive), and print a single JSON summary with the failed +tests instead of the terminal report. ```bash -composer tests -- --coverage-html code_coverage +vendor/bin/testo --json --filter=ScaffolderTest ``` -Run PHPStan with a different memory limit. +### Code coverage + +Collect coverage with PCOV or Xdebug enabled and write a Clover XML report. + +```bash +composer tests-unit -- --coverage-clover=runtime/clover.xml +``` + +## Passing extra arguments + +Composer scripts forward additional arguments after `--`. + +Run PHPStan with debug output. ```bash -composer static -- --memory-limit=512M +composer static -- --debug ``` ## Next steps diff --git a/infection.json5 b/infection.json5 index adf049c..9151988 100644 --- a/infection.json5 +++ b/infection.json5 @@ -1,15 +1,23 @@ { $schema: "./vendor/infection/infection/resources/schema.json", + ignoreMsiWithNoMutations: true, + initialTestsPhpOptions: "-d memory_limit=-1", logs: { text: "php://stderr", stryker: { report: "main", }, }, - source: { - directories: ["src"], - }, + minCoveredMsi: 100, + minMsi: 100, mutators: { "@default": true, }, + source: { + directories: ["src"], + }, + staticAnalysisToolOptions: "--memory-limit=-1", + testFramework: "testo", + testFrameworkExtraArgs: "--suite=Unit", + threads: "max", } diff --git a/phpunit.xml.dist b/phpunit.xml.dist deleted file mode 100644 index 52fd2fd..0000000 --- a/phpunit.xml.dist +++ /dev/null @@ -1,28 +0,0 @@ - - - - - tests - - - - - - ./src - - - - - - - diff --git a/src/Config/InstalledPackages.php b/src/Config/InstalledPackages.php new file mode 100644 index 0000000..17e5474 --- /dev/null +++ b/src/Config/InstalledPackages.php @@ -0,0 +1,137 @@ +|null $packages Installed packages keyed by + * name, with their pretty version and absolute install path, or `null` when the installed packages are unknown. + */ + public function __construct(private array|null $packages) {} + + /** + * Reads the installed packages of the project from `/composer/installed.php`, then from the + * `Composer\InstalledVersions` runtime data when its root package is `$projectRoot`. + * + * @param string $vendorDir Absolute path to the Composer vendor directory of the project. + * @param string $projectRoot Absolute path to the project root. + * + * @return self Installed packages, or an unknown list when neither source describes the project. + */ + public static function detect(string $vendorDir, string $projectRoot): self + { + $file = PathResolver::destination($vendorDir, 'composer/installed.php'); + + if (is_file($file)) { + return self::fromRawData(require $file); + } + + $rootPath = InstalledVersions::getRootPackage()['install_path']; + + if (PathResolver::realpathOrFallback($rootPath) !== PathResolver::realpathOrFallback($projectRoot)) { + return new self(null); + } + + $packages = []; + + foreach (InstalledVersions::getInstalledPackages() as $name) { + $packages[$name] = [ + 'version' => InstalledVersions::getPrettyVersion($name), + 'path' => InstalledVersions::getInstallPath($name), + ]; + } + + return new self($packages); + } + + /** + * Builds the list from the array returned by a `vendor/composer/installed.php` file. + * + * @param mixed $data Decoded installed data with a `versions` map; any other value yields an unknown list. + * + * @return self Installed packages that declare an install path, or an unknown list when `$data` is malformed. + */ + public static function fromRawData(mixed $data): self + { + if (!is_array($data) || !is_array($data['versions'] ?? null)) { + return new self(null); + } + + $packages = []; + + foreach ($data['versions'] as $name => $info) { + if (!is_string($name) || !is_array($info) || !is_string($info['install_path'] ?? null)) { + continue; + } + + $version = $info['pretty_version'] ?? null; + + $packages[$name] = [ + 'version' => is_string($version) ? $version : null, + 'path' => PathResolver::realpathOrFallback($info['install_path']), + ]; + } + + return new self($packages); + } + + /** + * Returns whether `$name` is installed; `false` when the installed packages are unknown. + * + * @param string $name Package name to look up. + * + * @return bool `true` when the package is installed, `false` when it is not installed or the list is unknown. + */ + public function has(string $name): bool + { + return $this->packages !== null && array_key_exists($name, $this->packages); + } + + /** + * Returns the absolute install path of `$name`, or `null` when it is not installed or unknown. + * + * @param string $name Package name to look up. + * + * @return string|null Absolute install path, or `null` when the package is not installed or the list is unknown. + */ + public function installPath(string $name): string|null + { + return $this->packages[$name]['path'] ?? null; + } + + /** + * Returns whether the installed packages are known. + * + * @return bool `true` when an installed package source describes the project, `false` otherwise. + */ + public function isKnown(): bool + { + return $this->packages !== null; + } + + /** + * Returns the installed pretty version of `$name`, or `null` when it is not installed or unknown. + * + * @param string $name Package name to look up. + * + * @return string|null Pretty version, or `null` when it is missing, not installed, or the list is unknown. + */ + public function version(string $name): string|null + { + return $this->packages[$name]['version'] ?? null; + } +} diff --git a/src/Config/ProjectConfig.php b/src/Config/ProjectConfig.php new file mode 100644 index 0000000..a9cea7b --- /dev/null +++ b/src/Config/ProjectConfig.php @@ -0,0 +1,133 @@ + $allowedPackages Package names allowed to write scaffold files, in declaration order. + * @param bool $auto Whether the Composer hooks scaffold automatically. + * @param int $ignoredEntries Number of non-string `allowed-packages` entries that were ignored. + * @param bool $declared Whether `extra.scaffold` is an object. + * @param string|null $vendorDir Non-empty `config.vendor-dir` as written in `composer.json`, or `null` when unset. + */ + public function __construct( + public array $allowedPackages = [], + public bool $auto = true, + public int $ignoredEntries = 0, + public bool $declared = false, + public string|null $vendorDir = null, + ) {} + + /** + * Reads the configuration from a `composer.json` file. + * + * @param string $path Absolute path to the project `composer.json`. + * + * @throws RuntimeException when the file is missing, unreadable, or not a JSON object. + * + * @return self Configuration from `extra.scaffold` and `config.vendor-dir`, or the defaults when they are absent. + */ + public static function fromComposerJson(string $path): self + { + if (!is_file($path)) { + throw new RuntimeException( + Message::CONFIG_MANIFEST_NOT_FOUND->getMessage($path), + ); + } + + $content = Filesystem::read($path, Message::CONFIG_MANIFEST_UNREADABLE->getMessage($path)); + + try { + $decoded = json_decode($content, associative: true, flags: JSON_THROW_ON_ERROR); + } catch (JsonException $e) { + throw new RuntimeException( + Message::CONFIG_MANIFEST_INVALID_JSON->getMessage($path, $e->getMessage()), + 0, + $e, + ); + } + + if (!is_array($decoded)) { + throw new RuntimeException( + Message::CONFIG_MANIFEST_NOT_OBJECT->getMessage($path), + ); + } + + $extra = $decoded['extra'] ?? []; + + $vendorDir = is_array($decoded['config'] ?? null) ? $decoded['config']['vendor-dir'] ?? null : null; + + $config = self::fromExtra(is_array($extra) ? $extra : []); + + return new self( + $config->allowedPackages, + $config->auto, + $config->ignoredEntries, + $config->declared, + is_string($vendorDir) && $vendorDir !== '' ? $vendorDir : null, + ); + } + + /** + * Reads the configuration from the `extra` section of the root package; only an explicit `false` in `auto` + * disables the Composer hooks. + * + * @param array $extra `extra` section of the root package. + * + * @return self Configuration from `extra.scaffold`, or the defaults when it is absent or not an object. + */ + public static function fromExtra(array $extra): self + { + $scaffold = $extra['scaffold'] ?? null; + + if (!is_array($scaffold)) { + return new self(); + } + + $rawAllowed = $scaffold['allowed-packages'] ?? null; + + $allowed = []; + $ignored = 0; + + if (is_array($rawAllowed)) { + foreach ($rawAllowed as $item) { + if (is_string($item)) { + $allowed[] = $item; + } else { + $ignored++; + } + } + } + + return new self($allowed, ($scaffold['auto'] ?? null) !== false, $ignored, true); + } + + /** + * Returns whether `$packageName` is listed in `allowed-packages`. + * + * @param string $packageName Package name to check. + * + * @return bool `true` when the package is allowed to write scaffold files, `false` otherwise. + */ + public function isAllowed(string $packageName): bool + { + return in_array($packageName, $this->allowedPackages, true); + } +} diff --git a/src/Config/ProjectContext.php b/src/Config/ProjectContext.php new file mode 100644 index 0000000..e698028 --- /dev/null +++ b/src/Config/ProjectContext.php @@ -0,0 +1,134 @@ +vendorDir); + + return new self($projectRoot, $vendorDir, $config, InstalledPackages::detect($vendorDir, $projectRoot)); + } + + /** + * Returns whether the provider is installed: from the installed packages when known, otherwise from the + * existence of its resolved root directory. + * + * @param string $providerName Provider package name. + * @param mixed $providerLock Decoded `providers.` entry of `scaffold-lock.json`, or `null` when absent. + * + * @return bool `true` when the provider is installed in the project, `false` otherwise. + */ + public function isInstalled(string $providerName, mixed $providerLock = null): bool + { + if ($this->installed->isKnown()) { + return $this->installed->has($providerName); + } + + return is_dir($this->providerRoot($providerName, $providerLock)['root']); + } + + /** + * Resolves the root of a provider from its Composer install path, then its lock-recorded path inside the vendor + * directory, then `/`. + * + * @param string $providerName Provider package name. + * @param mixed $providerLock Decoded `providers.` entry of `scaffold-lock.json`, or `null` when absent. + * + * @return array{root: string, warning: string|null} Provider root, and a warning when the lock-recorded path + * resolves outside the vendor directory. + */ + public function providerRoot(string $providerName, mixed $providerLock = null): array + { + $installPath = $this->installed->installPath($providerName); + + if ($installPath !== null) { + return [ + 'root' => $installPath, + 'warning' => null, + ]; + } + + return PathResolver::resolveProviderRoot($this->vendorDir, $providerName, $providerLock, $this->projectRoot); + } + + /** + * Returns the allowed providers that are installed, as descriptors whose `extra` the scaffold core reads from + * their `composer.json`. + * + * @param array $lockProviders `providers` map of `scaffold-lock.json`, used for recorded paths and, + * when the installed packages are unknown, recorded versions. + * + * @return array{providers: array, warnings: array} Providers keyed by name + * in `allowed-packages` order, and warnings about provider roots keyed by provider name. + */ + public function providers(array $lockProviders): array + { + $providers = []; + $warnings = []; + + foreach ($this->config->allowedPackages as $name) { + $providerLock = $lockProviders[$name] ?? null; + + if (!$this->isInstalled($name, $providerLock)) { + continue; + } + + $resolved = $this->providerRoot($name, $providerLock); + + if ($resolved['warning'] !== null) { + $warnings[$name] = $resolved['warning']; + } + + $lockVersion = is_array($providerLock) ? $providerLock['version'] ?? null : null; + + $providers[$name] = new ProviderPackage( + $name, + $this->installed->version($name) ?? (is_string($lockVersion) ? $lockVersion : 'unknown'), + $resolved['root'], + ); + } + + return [ + 'providers' => $providers, + 'warnings' => $warnings, + ]; + } +} diff --git a/src/Config/ProjectRootFinder.php b/src/Config/ProjectRootFinder.php new file mode 100644 index 0000000..1021f15 --- /dev/null +++ b/src/Config/ProjectRootFinder.php @@ -0,0 +1,57 @@ +|null $extra `extra` section of the package, or `null` to read it from the `composer.json` at + * `$installPath`. + */ + public function __construct( + public string $name, + public string $prettyVersion, + public string|null $installPath, + public array|null $extra = null, + ) {} +} diff --git a/src/Config/VendorDirResolver.php b/src/Config/VendorDirResolver.php new file mode 100644 index 0000000..0cc1a8f --- /dev/null +++ b/src/Config/VendorDirResolver.php @@ -0,0 +1,93 @@ +/vendor`. + */ +final class VendorDirResolver +{ + /** + * Returns the file name of the project manifest: the `COMPOSER` environment variable when set, otherwise + * `composer.json`. + * + * @return string Manifest file name, relative to the project root unless the `COMPOSER` value is absolute. + */ + public static function manifestName(): string + { + $env = getenv('COMPOSER'); + + return is_string($env) && $env !== '' ? $env : 'composer.json'; + } + + /** + * Returns the absolute path of the project manifest named by {@see self::manifestName()}. + * + * @param string $projectRoot Absolute path to the project root directory. + * + * @return string Absolute path of the project manifest. + */ + public static function manifestPath(string $projectRoot): string + { + return self::absolutize(self::manifestName(), $projectRoot); + } + + /** + * Returns the absolute path to the vendor directory for the project rooted at `$projectRoot`. + * + * @param string $projectRoot Absolute path to the project root directory. + * @param string|null $configured `config.vendor-dir` of the project manifest, or `null` when unset. + * + * @return string Absolute path to the resolved vendor directory. + */ + public static function resolve(string $projectRoot, string|null $configured = null): string + { + $env = getenv('COMPOSER_VENDOR_DIR'); + + if (is_string($env) && $env !== '') { + return self::absolutize($env, $projectRoot); + } + + if ($configured !== null) { + return self::absolutize($configured, $projectRoot); + } + + return rtrim($projectRoot, '/\\') . '/vendor'; + } + + /** + * Returns `$path` as an absolute path without trailing separators, joining relative and drive-relative paths (such + * as `C:vendor`) to `$projectRoot` and keeping the separator of a drive root (such as `C:\`). + * + * @param string $path Absolute or relative filesystem path. + * @param string $projectRoot Absolute path used as the base for relative `$path` values. + * + * @return string Absolute path; a drive root keeps its trailing separator, every other path has it stripped. + */ + private static function absolutize(string $path, string $projectRoot): string + { + $isAbsolute = str_starts_with($path, '/') + || str_starts_with($path, '\\') + || preg_match('#^[A-Za-z]:[/\\\\]#', $path) === 1; + + if ($isAbsolute) { + // Preserve drive-root separator: "C:\" and "C:/" must remain 3 characters. + if (preg_match('#^([A-Za-z]:)([/\\\\])$#', $path, $matches) === 1) { + return "{$matches[1]}{$matches[2]}"; + } + + return rtrim($path, '/\\'); + } + + return rtrim($projectRoot, '/\\') . '/' . rtrim($path, '/\\'); + } +} diff --git a/src/Console/Application.php b/src/Console/Application.php index 3665fd6..f38d068 100644 --- a/src/Console/Application.php +++ b/src/Console/Application.php @@ -6,28 +6,37 @@ use Composer\InstalledVersions; use OutOfBoundsException; -use PHPForge\Scaffold\Console\Command\{DiffCommand, EjectCommand, ProvidersCommand, ReapplyCommand, StatusCommand}; +use Override; +use PHPForge\Scaffold\Console\Command\{ + DiffCommand, + EjectCommand, + ProvidersCommand, + PruneCommand, + ReapplyCommand, + StatusCommand, + SyncCommand, +}; use Symfony\Component\Console\Application as SymfonyApplication; +use Symfony\Component\Console\Input\{InputDefinition, InputOption}; /** - * Symfony Console application that exposes the scaffold plugin's five commands as a standalone CLI, available via - * `vendor/bin/scaffold` after `composer install`. - * - * Works in any PHP project with Composer, regardless of framework (Yii2, Yii3, Laravel, Symfony, Slim, pure PHP). + * Runs the `status`, `providers`, `diff`, `eject`, `reapply`, `prune` and `sync` commands as the + * `vendor/bin/scaffold` console application. */ final class Application extends SymfonyApplication { /** - * Fallback version returned by {@see resolveVersion()} when the package is not installed via Composer (for example, - * when the source tree is loaded directly without running `composer install` first). + * Version reported when Composer's runtime metadata does not list the package. */ public const string FALLBACK_VERSION = '0.3.x-dev'; - /** * Application / Composer package name. */ public const string NAME = 'php-forge/scaffold'; + /** + * Creates the application and registers the scaffold commands. + */ public function __construct() { parent::__construct(self::NAME, self::resolveVersion()); @@ -39,19 +48,19 @@ public function __construct() new DiffCommand(), new EjectCommand(), new ReapplyCommand(), + new PruneCommand(), + new SyncCommand(), ], ); } /** - * Returns the installed version of `$package` via Composer's runtime metadata, falling back to - * {@see FALLBACK_VERSION} when the package is not present in `vendor/composer/installed.php` (missing autoload, - * dev checkout run outside Composer, etc.). + * Returns the installed version of `$package` from Composer's runtime metadata, or {@see self::FALLBACK_VERSION} + * when the metadata does not list it. * - * @param string $package Composer package name to query. Defaults to this application's own package name so - * `vendor/bin/scaffold --version` reports the actual installed version on every tagged release. + * @param string $package Composer package name to query; defaults to this application's package. * - * @return string Semver-compatible version string or the fallback. + * @return string Installed pretty version (for example, `1.2.0` or `dev-main`), or the fallback version. */ public static function resolveVersion(string $package = self::NAME): string { @@ -61,4 +70,26 @@ public static function resolveVersion(string $package = self::NAME): string return self::FALLBACK_VERSION; } } + + /** + * Returns the default input definition with the global `--working-dir` (`-d`) option added. + * + * @return InputDefinition Symfony's default definition extended with `--working-dir`. + */ + #[Override] + protected function getDefaultInputDefinition(): InputDefinition + { + $definition = parent::getDefaultInputDefinition(); + + $definition->addOption( + new InputOption( + 'working-dir', + 'd', + InputOption::VALUE_REQUIRED, + 'Use the given directory as the starting point of the project root search.', + ), + ); + + return $definition; + } } diff --git a/src/Console/Command/AbstractScaffoldCommand.php b/src/Console/Command/AbstractScaffoldCommand.php index f3368d7..30209aa 100644 --- a/src/Console/Command/AbstractScaffoldCommand.php +++ b/src/Console/Command/AbstractScaffoldCommand.php @@ -4,39 +4,129 @@ namespace PHPForge\Scaffold\Console\Command; +use PHPForge\Scaffold\Config\{ProjectRootFinder, VendorDirResolver}; +use PHPForge\Scaffold\Console\{Message, SymfonyOutputWriter}; +use PHPForge\Scaffold\Scaffold\PathResolver; +use RuntimeException; use Symfony\Component\Console\Command\Command; +use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; +use function getcwd; +use function is_dir; +use function is_string; + /** - * Base class for scaffold Symfony Console commands that need to resolve the project root from the current working - * directory. - * - * Centralizes the `getcwd()` fail-fast check so every command reports a single, consistent diagnostic when the CWD - * becomes unreadable (for example, after the parent directory is removed) instead of silently propagating an - * empty project root into {@see \PHPForge\Scaffold\Scaffold\Lock\LockFile} or - * {@see \PHPForge\Scaffold\Scaffold\PathResolver}. + * Runs a scaffold console command: validates its input, resolves the project root and reports a + * {@see RuntimeException} of the command body as a `[scaffold]` error. */ abstract class AbstractScaffoldCommand extends Command { /** - * Returns the current working directory, or `null` after writing an error to `$output` when `getcwd()` fails. + * Runs the command body against the project root and returns its exit code. * - * Callers must return {@see Command::FAILURE} when the returned value is `null`. + * @param InputInterface $input Command input. + * @param SymfonyOutputWriter $out Output sink of the command. + * @param string $projectRoot Absolute path of the directory containing the project `composer.json`. * - * @param OutputInterface $output Symfony Console output used for the error message. + * @throws RuntimeException when the lock file or the project manifest cannot be read or written. * - * @return string|null Current working directory, or `null` when it cannot be determined. + * @return int Exit code of the command. */ - protected function resolveProjectRoot(OutputInterface $output): string|null + abstract protected function handle(InputInterface $input, SymfonyOutputWriter $out, string $projectRoot): int; + + /** + * Validates the input, resolves the project root and runs {@see self::handle()}. + * + * @param InputInterface $input Command input that may carry the global `--working-dir` option. + * @param OutputInterface $output Console output that receives the command output and the error messages. + * + * @return int Exit code of {@see self::handle()}; `1` when the project root is not found or a runtime error is + * reported; `2` when the input is invalid. + */ + final protected function execute(InputInterface $input, OutputInterface $output): int { - $cwd = getcwd(); + $out = new SymfonyOutputWriter($output); + + if (!$this->validate($input, $out)) { + return Command::INVALID; + } + + $projectRoot = $this->resolveProjectRoot($input, $out); + + if ($projectRoot === null) { + return Command::FAILURE; + } + + try { + return $this->handle($input, $out, $projectRoot); + } catch (RuntimeException $e) { + $out->writeStderr( + Message::SCAFFOLD_PREFIXED->getMessage($e->getMessage()), + ); + + return Command::FAILURE; + } + } + + /** + * Returns whether the input is valid, writing the error to the error output when it is not. + * + * @param InputInterface $input Command input. + * @param SymfonyOutputWriter $out Output sink that receives the error message. + * + * @return bool `true` when the command may run, `false` otherwise. + */ + protected function validate(InputInterface $input, SymfonyOutputWriter $out): bool + { + return true; + } + + /** + * Returns the nearest directory containing the Composer manifest, searching up from `--working-dir` when given or + * from the current working directory, or `null` after writing an error to the error output. + * + * @param InputInterface $input Command input that may carry the global `--working-dir` option. + * @param SymfonyOutputWriter $out Output sink that receives the error message. + * + * @return string|null Absolute project root, or `null` when the start directory or the manifest cannot be found. + */ + private function resolveProjectRoot(InputInterface $input, SymfonyOutputWriter $out): string|null + { + $workingDir = $input->hasOption('working-dir') ? $input->getOption('working-dir') : null; + + if (is_string($workingDir) && $workingDir !== '') { + if (!is_dir($workingDir)) { + $out->writeStderr( + Message::COMMAND_WORKING_DIR_NOT_FOUND->getMessage($workingDir), + ); + + return null; + } + + $start = PathResolver::realpathOrFallback($workingDir); + } else { + $cwd = getcwd(); + + if ($cwd === false) { + $out->writeStderr( + Message::COMMAND_CWD_UNRESOLVABLE->getMessage(), + ); + + return null; + } + + $start = $cwd; + } - if ($cwd === false) { - $output->writeln('[scaffold] Unable to determine current working directory.'); + $root = ProjectRootFinder::find($start); - return null; + if ($root === null) { + $out->writeStderr( + Message::COMMAND_MANIFEST_NOT_FOUND->getMessage(VendorDirResolver::manifestName(), $start), + ); } - return $cwd; + return $root; } } diff --git a/src/Console/Command/DiffCommand.php b/src/Console/Command/DiffCommand.php index 17d432f..99df9ba 100644 --- a/src/Console/Command/DiffCommand.php +++ b/src/Console/Command/DiffCommand.php @@ -4,55 +4,90 @@ namespace PHPForge\Scaffold\Console\Command; -use PHPForge\Scaffold\Console\{SymfonyOutputWriter, VendorDirResolver}; +use PHPForge\Scaffold\Config\ProjectContext; +use PHPForge\Scaffold\Console\{Message, SymfonyOutputWriter}; use PHPForge\Scaffold\Services\DiffService; use Symfony\Component\Console\Attribute\AsCommand; -use Symfony\Component\Console\Command\Command; -use Symfony\Component\Console\Input\{InputArgument, InputInterface}; -use Symfony\Component\Console\Output\OutputInterface; +use Symfony\Component\Console\Input\{InputArgument, InputInterface, InputOption}; + +use function is_string; /** - * Shows a git-style unified diff between the provider stub and the current on-disk file. - * - * Output is colorized on ANSI-capable terminals; pass `--no-ansi` to force plain output. - * - * Usage example: - * ```bash - * vendor/bin/scaffold diff config/params.php - * ``` + * Shows what applying the provider would change in a tracked file, or in every tracked file, as a unified diff. */ #[AsCommand( name: 'diff', - description: 'Shows a git-style unified diff between the provider stub and the current on-disk file.', + description: 'Shows what applying the provider would change in a tracked file, as a git-style unified diff.', )] final class DiffCommand extends AbstractScaffoldCommand { + /** + * Declares the optional `file` argument and the `--all` and `--exit-code` options. + */ protected function configure(): void { - $this->addArgument( - 'file', - InputArgument::REQUIRED, - "Destination path as recorded in 'scaffold-lock.json'.", - ); + $this + ->addArgument( + 'file', + InputArgument::OPTIONAL, + "Destination path as recorded in 'scaffold-lock.json'.", + ) + ->addOption( + 'all', + null, + InputOption::VALUE_NONE, + 'Diff every tracked, non-ejected file in lock order.', + ) + ->addOption( + 'exit-code', + null, + InputOption::VALUE_NONE, + 'Exit with 1 when applying would change a file.', + ); } - protected function execute(InputInterface $input, OutputInterface $output): int + /** + * Renders the diff of the given file, or of every file with `--all`. + * + * @param InputInterface $input Input with the `file` argument and the `--all` and `--exit-code` options. + * @param SymfonyOutputWriter $out Output sink that receives the diff and the error messages. + * @param string $projectRoot Absolute path of the project root. + * + * @return int Exit code of {@see DiffService::run()}. + */ + protected function handle(InputInterface $input, SymfonyOutputWriter $out, string $projectRoot): int { - $projectRoot = $this->resolveProjectRoot($output); - - if ($projectRoot === null) { - return Command::FAILURE; - } - - /** @var string $file */ $file = $input->getArgument('file'); return (new DiffService())->run( - $projectRoot, - VendorDirResolver::resolve($projectRoot), - $file, - new SymfonyOutputWriter($output), - $output->isDecorated(), + ProjectContext::create($projectRoot), + $out, + is_string($file) && $file !== '' ? $file : null, + $out->isDecorated(), + (bool) $input->getOption('exit-code'), ); } + + /** + * Returns whether exactly one of `file` and `--all` is given. + * + * @param InputInterface $input Input with the `file` argument and the `--all` option. + * @param SymfonyOutputWriter $out Output sink that receives the error message. + * + * @return bool `true` when exactly one target is given, `false` otherwise. + */ + protected function validate(InputInterface $input, SymfonyOutputWriter $out): bool + { + $file = $input->getArgument('file'); + + if ((is_string($file) && $file !== '') === (bool) $input->getOption('all')) { + $out->writeStderr( + Message::DIFF_TARGET_AMBIGUOUS->getMessage(), + ); + + return false; + } + + return true; + } } diff --git a/src/Console/Command/EjectCommand.php b/src/Console/Command/EjectCommand.php index dd0964a..16b2d07 100644 --- a/src/Console/Command/EjectCommand.php +++ b/src/Console/Command/EjectCommand.php @@ -7,47 +7,50 @@ use PHPForge\Scaffold\Console\SymfonyOutputWriter; use PHPForge\Scaffold\Services\EjectService; use Symfony\Component\Console\Attribute\AsCommand; -use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\{InputArgument, InputInterface, InputOption}; -use Symfony\Component\Console\Output\OutputInterface; /** - * Removes a file entry from `scaffold-lock.json` without deleting the file from disk. - * - * Usage example: - * ```bash - * vendor/bin/scaffold eject config/params.php --yes - * ``` + * Marks a file as ejected in `scaffold-lock.json` so scaffold stops managing it, without deleting it from disk. */ #[AsCommand( name: 'eject', - description: "Removes a file entry from 'scaffold-lock.json' without deleting the file from disk.", + description: "Marks a file as ejected in 'scaffold-lock.json' so scaffold stops managing it; it stays on disk.", )] final class EjectCommand extends AbstractScaffoldCommand { + /** + * Declares the `file` argument and the `--yes` option. + */ protected function configure(): void { $this - ->addArgument('file', InputArgument::REQUIRED, "Destination path as recorded in 'scaffold-lock.json'.") - ->addOption('yes', null, InputOption::VALUE_NONE, 'Confirm the ejection without prompting.'); + ->addArgument( + 'file', + InputArgument::REQUIRED, + "Destination path as recorded in 'scaffold-lock.json'.", + ) + ->addOption( + 'yes', + null, + InputOption::VALUE_NONE, + 'Confirm the ejection without prompting.', + ); } - protected function execute(InputInterface $input, OutputInterface $output): int + /** + * Ejects the given file, or previews the ejection without `--yes`. + * + * @param InputInterface $input Input with the `file` argument and the `--yes` option. + * @param SymfonyOutputWriter $out Output sink that receives the ejection notice and the error messages. + * @param string $projectRoot Absolute path of the project root. + * + * @return int Exit code of {@see EjectService::run()}. + */ + protected function handle(InputInterface $input, SymfonyOutputWriter $out, string $projectRoot): int { - $projectRoot = $this->resolveProjectRoot($output); - - if ($projectRoot === null) { - return Command::FAILURE; - } - /** @var string $file */ $file = $input->getArgument('file'); - return (new EjectService())->run( - $projectRoot, - $file, - (bool) $input->getOption('yes'), - new SymfonyOutputWriter($output), - ); + return (new EjectService())->run($projectRoot, $out, $file, (bool) $input->getOption('yes')); } } diff --git a/src/Console/Command/ProvidersCommand.php b/src/Console/Command/ProvidersCommand.php index 527e4e0..3fa7db1 100644 --- a/src/Console/Command/ProvidersCommand.php +++ b/src/Console/Command/ProvidersCommand.php @@ -7,17 +7,10 @@ use PHPForge\Scaffold\Console\SymfonyOutputWriter; use PHPForge\Scaffold\Services\ProvidersService; use Symfony\Component\Console\Attribute\AsCommand; -use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputInterface; -use Symfony\Component\Console\Output\OutputInterface; /** * Lists all scaffold providers recorded in `scaffold-lock.json` with their file counts. - * - * Usage example: - * ```bash - * vendor/bin/scaffold providers - * ``` */ #[AsCommand( name: 'providers', @@ -25,14 +18,17 @@ )] final class ProvidersCommand extends AbstractScaffoldCommand { - protected function execute(InputInterface $input, OutputInterface $output): int + /** + * Prints the provider table. + * + * @param InputInterface $input Input that may carry the global `--working-dir` option. + * @param SymfonyOutputWriter $out Output sink that receives the provider table and the error messages. + * @param string $projectRoot Absolute path of the project root. + * + * @return int Exit code of {@see ProvidersService::run()}. + */ + protected function handle(InputInterface $input, SymfonyOutputWriter $out, string $projectRoot): int { - $projectRoot = $this->resolveProjectRoot($output); - - if ($projectRoot === null) { - return Command::FAILURE; - } - - return (new ProvidersService())->run($projectRoot, new SymfonyOutputWriter($output)); + return (new ProvidersService())->run($projectRoot, $out); } } diff --git a/src/Console/Command/PruneCommand.php b/src/Console/Command/PruneCommand.php new file mode 100644 index 0000000..9535a1c --- /dev/null +++ b/src/Console/Command/PruneCommand.php @@ -0,0 +1,68 @@ +addOption( + 'force', + null, + InputOption::VALUE_NONE, + 'Remove orphan entries from scaffold-lock.json and delete orphans that hold only provider content.', + ) + ->addOption( + 'delete-modified', + null, + InputOption::VALUE_NONE, + 'With --force, also delete orphan files that hold consumer content (destructive).', + ) + ->addOption( + 'exit-code', + null, + InputOption::VALUE_NONE, + 'Without --force, exit with 1 when orphaned files exist.', + ); + } + + /** + * Previews or prunes the orphaned entries. + * + * @param InputInterface $input Input with the `--force`, `--delete-modified` and `--exit-code` options. + * @param SymfonyOutputWriter $out Output sink that receives the orphan report and the error messages. + * @param string $projectRoot Absolute path of the project root. + * + * @return int Exit code of {@see PruneService::run()}. + */ + protected function handle(InputInterface $input, SymfonyOutputWriter $out, string $projectRoot): int + { + return (new PruneService())->run( + ProjectContext::create($projectRoot), + $out, + (bool) $input->getOption('force'), + (bool) $input->getOption('delete-modified'), + (bool) $input->getOption('exit-code'), + ); + } +} diff --git a/src/Console/Command/ReapplyCommand.php b/src/Console/Command/ReapplyCommand.php index 28327b5..7a37a0e 100644 --- a/src/Console/Command/ReapplyCommand.php +++ b/src/Console/Command/ReapplyCommand.php @@ -4,23 +4,15 @@ namespace PHPForge\Scaffold\Console\Command; -use PHPForge\Scaffold\Console\{SymfonyOutputWriter, VendorDirResolver}; +use PHPForge\Scaffold\Config\ProjectContext; +use PHPForge\Scaffold\Console\SymfonyOutputWriter; use PHPForge\Scaffold\Services\ReapplyService; use Symfony\Component\Console\Attribute\AsCommand; -use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\{InputArgument, InputInterface, InputOption}; -use Symfony\Component\Console\Output\OutputInterface; /** - * Re-applies scaffold stubs to the project, optionally overwriting user-modified files. - * - * Usage example: - * ```bash - * vendor/bin/scaffold reapply - * vendor/bin/scaffold reapply config/params.php - * vendor/bin/scaffold reapply config/params.php --force - * vendor/bin/scaffold reapply --provider=php-forge/baseline - * ``` + * Reapplies provider stubs to tracked files; `--force` also overwrites ejected, adopted, user-modified, `preserve`, + * `append` and `prepend` files. */ #[AsCommand( name: 'reapply', @@ -28,6 +20,9 @@ )] final class ReapplyCommand extends AbstractScaffoldCommand { + /** + * Declares the optional `file` argument and the `--force`, `--provider`, `--dry-run` and `--exit-code` options. + */ protected function configure(): void { $this @@ -49,17 +44,33 @@ protected function configure(): void InputOption::VALUE_REQUIRED, "Restrict reapply to a provider package name (for example, 'php-forge/baseline').", '', + ) + ->addOption( + 'dry-run', + null, + InputOption::VALUE_NONE, + 'Print the diff of every file that would change without writing anything.', + ) + ->addOption( + 'exit-code', + null, + InputOption::VALUE_NONE, + 'With --dry-run, exit with 1 when any file would change.', ); } - protected function execute(InputInterface $input, OutputInterface $output): int + /** + * Reapplies the matching tracked files. + * + * @param InputInterface $input Input with the `file` argument and the `--force`, `--provider`, `--dry-run` and + * `--exit-code` options. + * @param SymfonyOutputWriter $out Output sink that receives the reapply report and the error messages. + * @param string $projectRoot Absolute path of the project root. + * + * @return int Exit code of {@see ReapplyService::run()}. + */ + protected function handle(InputInterface $input, SymfonyOutputWriter $out, string $projectRoot): int { - $projectRoot = $this->resolveProjectRoot($output); - - if ($projectRoot === null) { - return Command::FAILURE; - } - /** @var string $file */ $file = $input->getArgument('file'); @@ -67,12 +78,13 @@ protected function execute(InputInterface $input, OutputInterface $output): int $provider = $input->getOption('provider'); return (new ReapplyService())->run( - $projectRoot, - VendorDirResolver::resolve($projectRoot), + ProjectContext::create($projectRoot), + $out, $file, $provider, (bool) $input->getOption('force'), - new SymfonyOutputWriter($output), + (bool) $input->getOption('dry-run'), + (bool) $input->getOption('exit-code'), ); } } diff --git a/src/Console/Command/StatusCommand.php b/src/Console/Command/StatusCommand.php index 6131255..6f12913 100644 --- a/src/Console/Command/StatusCommand.php +++ b/src/Console/Command/StatusCommand.php @@ -4,35 +4,85 @@ namespace PHPForge\Scaffold\Console\Command; -use PHPForge\Scaffold\Console\SymfonyOutputWriter; +use PHPForge\Scaffold\Config\ProjectContext; +use PHPForge\Scaffold\Console\{Message, SymfonyOutputWriter}; use PHPForge\Scaffold\Services\StatusService; use Symfony\Component\Console\Attribute\AsCommand; -use Symfony\Component\Console\Command\Command; -use Symfony\Component\Console\Input\InputInterface; -use Symfony\Component\Console\Output\OutputInterface; +use Symfony\Component\Console\Input\{InputInterface, InputOption}; + +use function in_array; +use function is_string; /** - * Displays the status of all scaffold-tracked files relative to their recorded hashes. - * - * Usage example: - * ```bash - * vendor/bin/scaffold status - * ``` + * Displays the state of every scaffold-tracked file against the disk and the current provider stubs. */ #[AsCommand( name: 'status', - description: 'Displays the status of all scaffold-tracked files relative to their recorded hashes.', + description: 'Displays the state of every scaffold-tracked file against the disk and the current provider stubs.', )] final class StatusCommand extends AbstractScaffoldCommand { - protected function execute(InputInterface $input, OutputInterface $output): int + /** + * Declares the `--format` and `--exit-code` options. + */ + protected function configure(): void + { + $this + ->addOption( + 'format', + null, + InputOption::VALUE_REQUIRED, + 'Output format: "table" or "json".', + 'table', + ) + ->addOption( + 'exit-code', + null, + InputOption::VALUE_NONE, + 'Exit with 1 when any file is neither "synced" nor "ejected".', + ); + } + + /** + * Prints the status of the tracked files. + * + * @param InputInterface $input Input with the `--format` and `--exit-code` options. + * @param SymfonyOutputWriter $out Output sink that receives the status table or JSON document and the error + * messages. + * @param string $projectRoot Absolute path of the project root. + * + * @return int Exit code of {@see StatusService::run()}. + */ + protected function handle(InputInterface $input, SymfonyOutputWriter $out, string $projectRoot): int { - $projectRoot = $this->resolveProjectRoot($output); + return (new StatusService())->run( + ProjectContext::create($projectRoot), + $out, + $input->getOption('format') === 'json', + (bool) $input->getOption('exit-code'), + ); + } + + /** + * Returns whether `--format` is `table` or `json`. + * + * @param InputInterface $input Input with the `--format` option. + * @param SymfonyOutputWriter $out Output sink that receives the error message. + * + * @return bool `true` when the format is known, `false` otherwise. + */ + protected function validate(InputInterface $input, SymfonyOutputWriter $out): bool + { + $format = $input->getOption('format'); + + if (!is_string($format) || !in_array($format, ['table', 'json'], true)) { + $out->writeStderr( + Message::STATUS_FORMAT_UNKNOWN->getMessage(is_string($format) ? $format : ''), + ); - if ($projectRoot === null) { - return Command::FAILURE; + return false; } - return (new StatusService())->run($projectRoot, new SymfonyOutputWriter($output)); + return true; } } diff --git a/src/Console/Command/SyncCommand.php b/src/Console/Command/SyncCommand.php new file mode 100644 index 0000000..e63ea13 --- /dev/null +++ b/src/Console/Command/SyncCommand.php @@ -0,0 +1,68 @@ +addOption( + 'dry-run', + null, + InputOption::VALUE_NONE, + 'Print what applying the providers would change, and the orphans, without writing anything.', + ) + ->addOption( + 'exit-code', + null, + InputOption::VALUE_NONE, + 'With --dry-run, exit with 1 when applying would change a file or scaffold-lock.json.', + ) + ->addOption( + 'force', + null, + InputOption::VALUE_NONE, + 'Overwrite user-modified replace files, like reapply --force.', + ); + } + + /** + * Synchronizes the project. + * + * @param InputInterface $input Input with the `--dry-run`, `--exit-code` and `--force` options. + * @param SymfonyOutputWriter $out Output sink that receives the sync report and the error messages. + * @param string $projectRoot Absolute path of the project root. + * + * @return int Exit code of {@see SyncService::run()}. + */ + protected function handle(InputInterface $input, SymfonyOutputWriter $out, string $projectRoot): int + { + return (new SyncService())->run( + ProjectContext::create($projectRoot), + $out, + (bool) $input->getOption('dry-run'), + (bool) $input->getOption('exit-code'), + (bool) $input->getOption('force'), + $out->isDecorated(), + ); + } +} diff --git a/src/Console/ComposerIoWriter.php b/src/Console/ComposerIoWriter.php new file mode 100644 index 0000000..e6acae5 --- /dev/null +++ b/src/Console/ComposerIoWriter.php @@ -0,0 +1,42 @@ +io->writeError( + $message, + ); + } + + /** + * Writes `$message` with {@see \Composer\IO\IOInterface::write()}. + * + * @param string $message Message without a trailing newline; the writer appends one. + */ + public function writeStdout(string $message): void + { + $this->io->write( + $message, + ); + } +} diff --git a/src/Console/DiffColorizer.php b/src/Console/DiffColorizer.php index 2bc27af..f7df07e 100644 --- a/src/Console/DiffColorizer.php +++ b/src/Console/DiffColorizer.php @@ -9,30 +9,36 @@ use function str_starts_with; /** - * Wraps unified diff lines in raw ANSI color escape codes for decorated terminals. - * - * Styles the two leading `--- a/…` and `+++ b/…` file headers in bold, `@@` hunk headers in cyan, added lines in - * green, and removed lines in red. Header detection is positional (first two lines), so a removed body line that - * happens to start with `---` is still styled as removed. Raw escape codes keep the output compatible with - * {@see SymfonyOutputWriter}, which bypasses Symfony's formatter. - * - * Usage example: - * ```php - * $colorized = (new \PHPForge\Scaffold\Console\DiffColorizer())->colorize($unifiedDiff); - * ``` + * Colors unified diff lines with raw ANSI escape codes: the first two lines (file headers) in bold, hunk headers in + * cyan, added lines in green and removed lines in red. */ final class DiffColorizer { + /** + * ANSI escape code for bold text. + */ private const string BOLD = "\e[1m"; + /** + * ANSI escape code for cyan text. + */ private const string CYAN = "\e[36m"; + /** + * ANSI escape code for green text. + */ private const string GREEN = "\e[32m"; + /** + * ANSI escape code for red text. + */ private const string RED = "\e[31m"; + /** + * ANSI escape code that resets all text attributes. + */ private const string RESET = "\e[0m"; /** - * Colorizes a unified diff produced by {@see \PHPForge\Scaffold\Services\DiffService::buildDiff()}. + * Colors a unified diff whose first two lines are the `---` and `+++` file headers. * - * @param string $diff Unified diff whose first two lines are the `---`/`+++` file headers. + * @param string $diff Unified diff with `"\n"` line separators. * * @return string Diff with each styled line wrapped in ANSI escape codes; context lines stay unstyled. */ diff --git a/src/Console/ExitCode.php b/src/Console/ExitCode.php index 34d49dc..4948ed8 100644 --- a/src/Console/ExitCode.php +++ b/src/Console/ExitCode.php @@ -5,22 +5,18 @@ namespace PHPForge\Scaffold\Console; /** - * Standardized exit codes returned by scaffold services. - * - * Backed by `int` so service entry points can return the code via `->value` when called from Console commands - * controllers, both of which expect an integer exit status. + * Represents the exit codes that scaffold services return to the console commands. */ enum ExitCode: int { /** - * Recoverable error for example, an untracked file passed to `diff` / `eject`, an unsafe lock entry, a missing - * stub, or an I/O failure mid-run. + * Reports a failure such as an untracked file, an unsafe lock entry, a missing stub, a read error, or a `reapply` + * filter that matches no tracked file. */ case Error = 1; /** - * Success, including preview / no-op runs (for example, `reapply` with no changes to apply, or `eject` without - * `--yes`). + * Reports success, including previews and runs that change nothing. */ case Ok = 0; } diff --git a/src/Console/Message.php b/src/Console/Message.php new file mode 100644 index 0000000..b9f7cc8 --- /dev/null +++ b/src/Console/Message.php @@ -0,0 +1,489 @@ +` in a stub) that the - * default formatter would otherwise interpret as style tags and corrupt or crash on. - * - * When the underlying output is a {@see ConsoleOutputInterface}, stderr writes are routed through `getErrorOutput()`, - * matching Symfony's "split stdout/stderr" convention. + * Writes service messages to a Symfony Console output in raw mode, so stub content such as `` is never parsed + * as style tags. */ final readonly class SymfonyOutputWriter implements OutputWriter { + /** + * @param OutputInterface $output Console output that receives the messages and, through its error output when it + * is a {@see \Symfony\Component\Console\Output\ConsoleOutputInterface}, the standard error messages. + */ public function __construct(private OutputInterface $output) {} /** - * Writes `$message` to stderr followed by a single trailing newline, bypassing Symfony's formatter. + * Returns whether the console output supports ANSI decoration. * - * If the underlying output supports separate error output (i.e., implements {@see ConsoleOutputInterface}), the - * message is sent to that stream; otherwise, it falls back to writing to the main output stream. + * @return bool `true` when the main output is decorated, `false` otherwise. + */ + public function isDecorated(): bool + { + return $this->output->isDecorated(); + } + + /** + * Writes `$message` and a newline to the error output, or to the main output when no error output is available. * - * @param string $message Message to write. + * @param string $message Message without a trailing newline; the writer appends one. */ public function writeStderr(string $message): void { $sink = $this->output instanceof ConsoleOutputInterface ? $this->output->getErrorOutput() : $this->output; - $sink->writeln($message, OutputInterface::OUTPUT_RAW); + $sink->writeln( + $message, + OutputInterface::OUTPUT_RAW, + ); } /** - * Writes `$message` to stdout followed by a single trailing newline, bypassing Symfony's formatter. + * Writes `$message` and a newline to the main output. * - * @param string $message Message to write. + * @param string $message Message without a trailing newline; the writer appends one. */ public function writeStdout(string $message): void { - $this->output->writeln($message, OutputInterface::OUTPUT_RAW); + $this->output->writeln( + $message, + OutputInterface::OUTPUT_RAW, + ); } } diff --git a/src/Console/Table.php b/src/Console/Table.php new file mode 100644 index 0000000..18f6d04 --- /dev/null +++ b/src/Console/Table.php @@ -0,0 +1,47 @@ + $headers Column headers. + * @param list> $rows Rows with one cell per header. + * + * @return list Lines without trailing newlines or trailing spaces. + */ + public static function render(array $headers, array $rows): array + { + $widths = []; + + foreach ($headers as $column => $header) { + $widths[] = max(array_map(strlen(...), [$header, ...array_column($rows, $column)])); + } + + $line = static fn(array $cells): string => rtrim(implode(' ', array_map(str_pad(...), $cells, $widths))); + + return [ + $line($headers), + str_repeat('-', array_sum($widths) + 2 * (count($widths) - 1)), + ...array_map($line, $rows), + ]; + } +} diff --git a/src/Console/VendorDirResolver.php b/src/Console/VendorDirResolver.php deleted file mode 100644 index 3808e4e..0000000 --- a/src/Console/VendorDirResolver.php +++ /dev/null @@ -1,111 +0,0 @@ -/vendor`. - * - * Keeps the `diff` / `reapply` commands correct for projects that customise the vendor directory via Composer's - * `config.vendor-dir` key or the `COMPOSER_VENDOR_DIR` environment variable. - */ -final class VendorDirResolver -{ - /** - * Returns the absolute path to the vendor directory for the project rooted at `$projectRoot`. - * - * @param string $projectRoot Absolute path to the project root directory. - * - * @return string Absolute path to the resolved vendor directory. - */ - public static function resolve(string $projectRoot): string - { - $env = getenv('COMPOSER_VENDOR_DIR'); - - if (is_string($env) && $env !== '') { - return self::absolutize($env, $projectRoot); - } - - // Windows-only normalisation: rtrim of the backslash variant cannot be exercised on POSIX. - // @codeCoverageIgnoreStart - $trimmedRoot = rtrim($projectRoot, '/\\'); - // @codeCoverageIgnoreEnd - - $composerJson = $trimmedRoot . '/composer.json'; - - if (is_file($composerJson)) { - $raw = file_get_contents($composerJson); - - if (is_string($raw)) { - $decoded = json_decode($raw, true); - - $config = is_array($decoded) && isset($decoded['config']) && is_array($decoded['config']) - ? $decoded['config'] - : []; - - $custom = $config['vendor-dir'] ?? null; - - if (is_string($custom) && $custom !== '') { - return self::absolutize($custom, $projectRoot); - } - } - } - - return rtrim($projectRoot, '/\\') . '/vendor'; - } - - /** - * Converts `$path` to an absolute path, resolving relative segments against `$projectRoot`. - * - * Absoluteness detection runs on the original `$path` so Windows drive-relative inputs like `C:vendor` (distinct - * from the absolute `C:\vendor`) fall through to the `$projectRoot`-joined branch. Drive-root inputs like `C:\` and - * `C:/` keep their trailing separator intact because stripping it would turn them into the drive-relative `C:` - * token. - * - * @param string $path Absolute or relative filesystem path. - * @param string $projectRoot Absolute path used as the base for relative `$path` values. - * - * @return string Absolute path. A drive-root input preserves its trailing separator; every other absolute path has - * trailing separators stripped. - */ - private static function absolutize(string $path, string $projectRoot): string - { - $isAbsolute = str_starts_with($path, '/') - || str_starts_with($path, '\\') - || preg_match('#^[A-Za-z]:[/\\\\]#', $path) === 1; - - if ($isAbsolute) { - // Preserve drive-root separator: "C:\" and "C:/" must remain 3 characters. - if (preg_match('#^([A-Za-z]:)([/\\\\])$#', $path, $matches) === 1) { - return $matches[1] . $matches[2]; - } - - return rtrim($path, '/\\'); - } - - // Windows-only normalisation: ltrim of the backslash variant cannot be exercised on POSIX. - // @codeCoverageIgnoreStart - $strippedPath = ltrim($path, '/\\'); - // @codeCoverageIgnoreEnd - - return rtrim($projectRoot, '/\\') . '/' . rtrim($strippedPath, '/\\'); - } -} diff --git a/src/EventSubscriber.php b/src/EventSubscriber.php index a391fe7..3851d99 100644 --- a/src/EventSubscriber.php +++ b/src/EventSubscriber.php @@ -5,17 +5,17 @@ namespace PHPForge\Scaffold; use Composer\EventDispatcher\EventSubscriberInterface; -use Composer\IO\IOInterface; use Composer\Script\{Event, ScriptEvents}; +use PHPForge\Scaffold\Config\ProjectConfig; +use PHPForge\Scaffold\Console\{ComposerIoWriter, Message as ConsoleMessage}; +use PHPForge\Scaffold\Exception\{Message, ScaffoldException}; use PHPForge\Scaffold\Manifest\{ManifestExpander, ManifestLoader, ManifestSchema}; -use PHPForge\Scaffold\Scaffold\{Applier, Scaffolder}; -use PHPForge\Scaffold\Scaffold\Lock\{Hasher, LockFile}; -use PHPForge\Scaffold\Security\{PackageAllowlist, PathValidator}; +use PHPForge\Scaffold\Scaffold\{FileApplier, PathResolver, ScaffoldSummary, Scaffolder}; +use PHPForge\Scaffold\Scaffold\Lock\LockFile; +use PHPForge\Scaffold\Security\PathValidator; use Throwable; -use function is_array; -use function is_string; -use function sprintf; +use function dirname; /** * Listens to Composer script events and triggers the scaffold workflow. @@ -23,17 +23,15 @@ final class EventSubscriber implements EventSubscriberInterface { /** - * Set to `true` after `onPostInstall` executes in the current process. - * - * During `composer create-project`, Composer fires `post-install-cmd` before `post-create-project-cmd` within the - * same process. The install run applies all scaffold entries (including `append`/`prepend`) because the lock is - * empty. If the create-project handler were also to run a full scaffold, those entries would be re-applied and - * duplicated. This flag prevents that second run. + * Whether `post-install-cmd` or `post-update-cmd` fired in this process, so `post-create-project-cmd` does not run + * the workflow again. */ - private static bool $installScaffoldRan = false; + private static bool $scaffoldRan = false; /** - * @return array + * Returns the Composer script events handled by this subscriber. + * + * @return array Event name => handler method. */ public static function getSubscribedEvents(): array { @@ -45,141 +43,62 @@ public static function getSubscribedEvents(): array } /** - * Handles the post-create-project event to perform a full scaffold. + * Runs the scaffold workflow for `post-create-project-cmd`, unless `post-install-cmd` or `post-update-cmd` already + * fired in this process. * - * Skipped when `post-install-cmd` already ran in this process (i.e., during `composer create-project`), since the - * partial install scaffold with an empty lock is equivalent to a full scaffold. - * - * @param Event $event Composer event object containing context for the operation. + * @param Event $event The Composer event object. */ public function onPostCreateProject(Event $event): void { - if (self::$installScaffoldRan) { + if (self::$scaffoldRan) { return; } - $this->runScaffold($event, fullScaffold: true); + $this->runScaffold($event); } /** - * Handles the post-install event to perform a partial scaffold. + * Runs the scaffold workflow for `post-install-cmd`. * - * @param Event $event Composer event object containing context for the operation. + * @param Event $event The Composer event object. */ public function onPostInstall(Event $event): void { - self::$installScaffoldRan = true; + self::$scaffoldRan = true; - $this->runScaffold($event, fullScaffold: false); + $this->runScaffold($event); } /** - * Handles the post-update event to perform a partial scaffold. + * Runs the scaffold workflow for `post-update-cmd`. * - * @param Event $event Composer event object containing context for the operation. + * @param Event $event The Composer event object. */ public function onPostUpdate(Event $event): void { - $this->runScaffold($event, fullScaffold: false); - } - - /** - * Builds the Scaffolder instance with the necessary components. - * - * @param list $allowedPackages List of package names that are allowed to be scaffolded, extracted from - * `composer.json`. - * @param string $projectRoot Absolute path to the project root. - * @param IOInterface $io Composer IO interface for user interaction. - * - * @return Scaffolder Configured Scaffolder instance. - */ - private function buildScaffolder(array $allowedPackages, string $projectRoot, IOInterface $io): Scaffolder - { - return new Scaffolder( - new ManifestLoader(new ManifestSchema(), new ManifestExpander()), - new Applier(new PackageAllowlist($allowedPackages), new PathValidator(), new Hasher(), $io), - new LockFile($projectRoot), - $io, - ); - } - - /** - * Extracts the list of allowed packages from the `extra` section of `composer.json`. - * - * @param array $extra `extra` section from the root package's `composer.json`, which may contain scaffold - * configuration. - * @param IOInterface $io Composer IO interface for logging warnings about invalid configuration entries. - * - * @return list List of allowed package names that can be scaffolded. If the configuration is missing or - * invalid, an empty list is returned. - */ - private function extractAllowedPackages(array $extra, IOInterface $io): array - { - $scaffoldConfig = $extra['scaffold'] ?? null; - - if (!is_array($scaffoldConfig)) { - return []; - } - - $rawAllowed = $scaffoldConfig['allowed-packages'] ?? null; - - if (!is_array($rawAllowed)) { - return []; - } - - $allowed = []; - - foreach ($rawAllowed as $item) { - if (is_string($item)) { - $allowed[] = $item; - } else { - $io->writeError( - '[scaffold] Non-string entry in allowed-packages ignored.', - ); - } - } + self::$scaffoldRan = true; - return $allowed; + $this->runScaffold($event); } /** - * Reads the consumer's `extra.scaffold.auto` flag. + * Runs the scaffold workflow for the root package unless `extra.scaffold.auto` is `false`, ends with a summary line + * when a file was written or something needs attention, and fails the Composer command on errors. * - * Auto-trigger is enabled by default. Only an explicit `false` disables the post-install/post-update/ - * post-create-project hooks, in which case the consumer must invoke `vendor/bin/scaffold` manually to apply - * provider templates. Non-boolean values are treated as enabled to avoid silent disable on typo. + * @param Event $event Composer script event that provides the Composer instance and IO. * - * @param array $extra `extra` section from the root package's composer.json. - * - * @return bool `true` when auto-trigger is enabled, `false` only when explicitly disabled by the consumer. + * @throws ScaffoldException after the messages and the summary line are written, when the lock file cannot be read + * or written, the manifest of an allowed provider cannot be loaded, or a file fails to apply. */ - private function isAutoEnabled(array $extra): bool - { - $scaffold = $extra['scaffold'] ?? null; - - if (!is_array($scaffold)) { - return true; - } - - return ($scaffold['auto'] ?? null) !== false; - } - - /** - * Executes the scaffold process based on the given Composer event and scaffold type. - * - * @param Event $event Composer event object containing context for the operation. - * @param bool $fullScaffold Whether to perform a full scaffold (`true` for post-create-project) or a partial - * scaffold (`true` for post-install and post-update). - */ - private function runScaffold(Event $event, bool $fullScaffold): void + private function runScaffold(Event $event): void { $composer = $event->getComposer(); $io = $event->getIO(); - if (!$this->isAutoEnabled($composer->getPackage()->getExtra())) { - $io->write( - '[scaffold] Auto-scaffold disabled via "extra.scaffold.auto"; run "vendor/bin/scaffold" manually.', - ); + $config = ProjectConfig::fromExtra($composer->getPackage()->getExtra()); + + if (!$config->auto) { + $io->write(ConsoleMessage::SCAFFOLD_AUTO_DISABLED->getMessage()); return; } @@ -187,24 +106,29 @@ private function runScaffold(Event $event, bool $fullScaffold): void $vendorDirRaw = $composer->getConfig()->get('vendor-dir'); if ($vendorDirRaw === '') { - $io->writeError( - '[scaffold] Unable to resolve vendor-dir from Composer config; aborting scaffold.', - ); + $io->writeError(ConsoleMessage::SCAFFOLD_VENDOR_DIR_UNRESOLVABLE->getMessage()); return; } - $vendorDirResolved = realpath($vendorDirRaw); + $vendorDir = PathResolver::realpathOrFallback($vendorDirRaw); + $projectRoot = PathResolver::realpathOrFallback(dirname($composer->getConfig()->getConfigSource()->getName())); - $vendorDir = $vendorDirResolved !== false ? $vendorDirResolved : $vendorDirRaw; + for ($i = 0; $i < $config->ignoredEntries; $i++) { + $io->writeError(ConsoleMessage::SCAFFOLD_ALLOWED_ENTRY_IGNORED->getMessage()); + } - $projectRootRaw = dirname($composer->getConfig()->getConfigSource()->getName()); - $projectRootResolved = realpath($projectRootRaw); + $out = new ComposerIoWriter($io); + $summary = new ScaffoldSummary(); - $projectRoot = $projectRootResolved !== false ? $projectRootResolved : $projectRootRaw; + $scaffolder = new Scaffolder( + new ManifestLoader(new ManifestSchema(), new ManifestExpander()), + new FileApplier($config, new PathValidator(), $out), + new LockFile($projectRoot), + $out, + $summary, + ); - $allowedPackages = $this->extractAllowedPackages($composer->getPackage()->getExtra(), $io); - $scaffolder = $this->buildScaffolder($allowedPackages, $projectRoot, $io); $localRepo = $composer->getRepositoryManager()->getLocalRepository(); $installationManager = $composer->getInstallationManager(); @@ -218,18 +142,53 @@ private function runScaffold(Event $event, bool $fullScaffold): void } } + $failure = null; + try { $scaffolder->scaffold( - $composer->getPackage(), + $config, $localRepo->getPackages(), $projectRoot, $vendorDir, - $fullScaffold, $installPaths, ); + } catch (ScaffoldException $e) { + // The scaffolder already wrote the message. + $failure = $e; } catch (Throwable $e) { - $io->writeError( - sprintf('[scaffold] Scaffolding aborted: %s', $e->getMessage()), + $message = Message::SCAFFOLD_ABORTED->getMessage($e->getMessage()); + + $io->writeError($message); + + $summary->errors++; + + $failure = new ScaffoldException( + $message, + 0, + $e, + ); + } + + $line = $summary->line(); + + if ($line !== null) { + $io->write($line); + } + + if ($failure !== null) { + throw $failure; + } + + if ($summary->errors > 0) { + throw new ScaffoldException( + Message::SCAFFOLD_FILES_FAILED->getMessage( + $summary->errors, + Message::plural( + $summary->errors, + Message::SCAFFOLD_FRAGMENT_FAILED_FILE, + Message::SCAFFOLD_FRAGMENT_FAILED_FILES, + ), + ), ); } } diff --git a/src/Exception/Message.php b/src/Exception/Message.php new file mode 100644 index 0000000..3084428 --- /dev/null +++ b/src/Exception/Message.php @@ -0,0 +1,294 @@ + copy($source, $destination), $failure); + } + + /** + * Copies the permission bits of a file, masked by the current `umask`, onto another file. + * + * @param string $source Absolute path to the file whose permissions are copied. + * @param string $destination Absolute path to the file that receives the permissions. + * @param string $failure Message of the exception thrown on failure, before the PHP warning. + * + * @throws RuntimeException when the permissions cannot be read or set. + */ + public static function copyPermissions(string $source, string $destination, string $failure): void + { + $permissions = self::call(static fn(): int|false => fileperms($source), $failure); + + self::call(static fn(): bool => chmod($destination, $permissions & 0o777 & ~umask()), $failure); + } + + /** + * Returns the hexadecimal SHA-256 hash of a file. + * + * @param string $path Absolute path to the file. + * @param string $failure Message of the exception thrown on failure, before the PHP warning. + * + * @throws RuntimeException when the file cannot be read. + * + * @return string Hexadecimal SHA-256 hash of the file content. + */ + public static function hash(string $path, string $failure): string + { + return self::call(static fn(): string|false => hash_file('sha256', $path), $failure); + } + + /** + * Returns whether a directory holds no entry. + * + * @param string $directory Absolute path to the directory. + * @param string $failure Message of the exception thrown on failure, before the PHP warning. + * + * @throws RuntimeException when the directory cannot be read. + * + * @return bool `true` when the directory has no entry besides `.` and `..`, `false` otherwise. + */ + public static function isEmptyDirectory(string $directory, string $failure): bool + { + return count(self::call(static fn(): array|false => scandir($directory), $failure)) === 2; + } + + /** + * Creates a directory and its missing parents. + * + * @param string $directory Absolute path to the directory. + * @param string $failure Message of the exception thrown on failure, before the PHP warning. + * + * @throws RuntimeException when the directory cannot be created. + */ + public static function mkdir(string $directory, string $failure): void + { + self::call(static fn(): bool => mkdir($directory, 0o777, recursive: true), $failure); + } + + /** + * Returns the content of a file. + * + * @param string $path Absolute path to the file. + * @param string $failure Message of the exception thrown on failure, before the PHP warning. + * + * @throws RuntimeException when the file cannot be read. + * + * @return string Content of the file. + */ + public static function read(string $path, string $failure): string + { + return self::call(static fn(): string|false => file_get_contents($path), $failure); + } + + /** + * Returns the target of a symbolic link. + * + * @param string $path Absolute path to the symbolic link. + * @param string $failure Message of the exception thrown on failure, before the PHP warning. + * + * @throws RuntimeException when the link cannot be read. + * + * @return string Target of the link, as stored in the link. + */ + public static function readLink(string $path, string $failure): string + { + return self::call(static fn(): string|false => readlink($path), $failure); + } + + /** + * Deletes a file. + * + * @param string $path Absolute path to the file. + * @param string $failure Message of the exception thrown on failure, before the PHP warning. + * + * @throws RuntimeException when the file cannot be deleted. + */ + public static function remove(string $path, string $failure): void + { + self::call(static fn(): bool => unlink($path), $failure); + } + + /** + * Removes an empty directory. + * + * @param string $directory Absolute path to the directory. + * @param string $failure Message of the exception thrown on failure, before the PHP warning. + * + * @throws RuntimeException when the directory cannot be removed. + */ + public static function removeDirectory(string $directory, string $failure): void + { + self::call(static fn(): bool => rmdir($directory), $failure); + } + + /** + * Writes content to a file, creating or truncating it. + * + * @param string $path Absolute path to the file. + * @param string $content Content to write. + * @param string $failure Message of the exception thrown on failure, before the PHP warning. + * + * @throws RuntimeException when the file cannot be written. + */ + public static function write(string $path, string $content, string $failure): void + { + self::call(static fn(): int|false => file_put_contents($path, $content), $failure); + } + + /** + * Writes content to a temporary file next to `$path` and renames it over `$path`, removing the temporary file + * when the rename fails. + * + * @param string $path Absolute path to the file. + * @param string $content Content to write. + * @param string $failure Message of the exception thrown on failure, before the PHP warning. + * + * @throws RuntimeException when the temporary file cannot be written, renamed or removed. + */ + public static function writeAtomic(string $path, string $content, string $failure): void + { + $temporary = sprintf('%s.%s.tmp', $path, uniqid('', true)); + + try { + self::call(static fn(): int|false => file_put_contents($temporary, $content, LOCK_EX), $failure); + self::call(static fn(): bool => rename($temporary, $path), $failure); + } finally { + if (is_file($temporary)) { + self::remove($temporary, $failure); + } + } + } + + /** + * Runs a native filesystem call and throws when it raises a PHP diagnostic or returns `false`. + * + * @template T + * + * @param Closure(): (T|false) $operation Native call to run. + * @param string $failure Message of the exception thrown on failure, before the PHP warning. + * + * @throws RuntimeException when the call raises a PHP diagnostic or returns `false`. + * + * @return T Result of the call. + */ + private static function call(Closure $operation, string $failure): mixed + { + set_error_handler( + static function (int $level, string $message) use ($failure): never { + throw new RuntimeException( + Message::FILESYSTEM_FAILED->getMessage($failure, $message), + ); + }, + ); + + try { + $result = $operation(); + } finally { + restore_error_handler(); + } + + return $result !== false ? $result : throw new RuntimeException($failure); + } +} diff --git a/src/Manifest/DefaultExcludes.php b/src/Manifest/DefaultExcludes.php index fb568dd..5072a20 100644 --- a/src/Manifest/DefaultExcludes.php +++ b/src/Manifest/DefaultExcludes.php @@ -4,16 +4,9 @@ namespace PHPForge\Scaffold\Manifest; -use function str_ends_with; -use function substr; - /** - * Built-in exclusion patterns applied when {@see ManifestExpander} walks a directory listed in `scaffold.copy`. - * - * These patterns guarantee that provider meta-files (composer metadata, CI configuration, docs, etc.) never leak into - * the consumer project just because the provider's tree is copied wholesale. Providers that need to distribute a file - * that matches a default exclude may list it as an explicit file entry in `copy[]`; explicit file entries bypass the - * default excludes by design. + * Lists the provider meta-files that {@see ManifestExpander} skips when it walks a `copy[]` directory; explicit file + * entries in `copy[]` bypass these patterns. */ final class DefaultExcludes { @@ -25,7 +18,8 @@ final class DefaultExcludes 'composer.json', 'composer.lock', 'vendor/**', - // Version control. + // Version control ('.git' is a file in worktrees and submodules). + '.git', '.git/**', '.github/**', '.gitattributes', @@ -61,42 +55,9 @@ final class DefaultExcludes 'scaffold-lock.json', // Runtime bucket (providers ship explicit '.gitignore' if they want). 'runtime/**', + // Package managers and editor or OS artefacts. + 'node_modules/**', + '.idea/**', + '.DS_Store', ]; - - /** - * Returns `true` when `$relativePath` matches any built-in exclusion pattern. - * - * @param string $relativePath Path relative to the provider root, normalised to forward slashes. - * - * @return bool `true` when the path is default-excluded, `false` otherwise. - */ - public static function matches(string $relativePath): bool - { - foreach (self::PATTERNS as $pattern) { - if (Glob::matches($pattern, $relativePath)) { - return true; - } - } - - return false; - } - - /** - * Returns `true` when `$relativeDir` can be pruned from the walk because a pattern of the form `$relativeDir/**` - * would exclude every possible descendant. - * - * @param string $relativeDir Directory path relative to the walk root, normalised to forward slashes. - * - * @return bool `true` when descent into the directory is safe to skip entirely, `false` otherwise. - */ - public static function matchesDirectory(string $relativeDir): bool - { - foreach (self::PATTERNS as $pattern) { - if (str_ends_with($pattern, '/**') && substr($pattern, 0, -3) === $relativeDir) { - return true; - } - } - - return false; - } } diff --git a/src/Manifest/FileMapping.php b/src/Manifest/FileMapping.php index ca2b14c..74b5357 100644 --- a/src/Manifest/FileMapping.php +++ b/src/Manifest/FileMapping.php @@ -4,16 +4,28 @@ namespace PHPForge\Scaffold\Manifest; +use PHPForge\Scaffold\Merge\MergeStrategyKind; + /** - * Immutable value object representing a single file mapping from a scaffold provider. + * Represents one provider file to apply: its source, destination, write mode and merge strategy. */ final readonly class FileMapping { + /** + * @param string $destination Destination path relative to the project root, using forward slashes. + * @param string $source Source path relative to the provider root, using forward slashes. + * @param FileMode $mode Write mode applied to the destination. + * @param string $providerName Composer package name of the provider. + * @param string $providerPath Absolute path to the provider root on disk. + * @param MergeStrategyKind|null $mergeStrategy Merge strategy declared by the manifest `merge` map for the + * `append` mode, or `null` to resolve it from the destination basename. + */ public function __construct( public string $destination, public string $source, public FileMode $mode, public string $providerName, public string $providerPath, + public MergeStrategyKind|null $mergeStrategy = null, ) {} } diff --git a/src/Manifest/FileMode.php b/src/Manifest/FileMode.php index deff674..766bcde 100644 --- a/src/Manifest/FileMode.php +++ b/src/Manifest/FileMode.php @@ -5,27 +5,27 @@ namespace PHPForge\Scaffold\Manifest; /** - * Scaffold file write modes used in provider manifests and surfaced on {@see FileMapping}. + * Represents the write modes that a provider manifest assigns to destinations. */ enum FileMode: string { /** - * Append the source to the destination on the first apply (skipped on subsequent runs). + * Merges the provider entries missing from the destination on every run, creating the destination when missing. */ case Append = 'append'; /** - * Prepend the source to the destination on the first apply (skipped on subsequent runs). + * Prepends the provider block on every run unless the destination already contains it. */ case Prepend = 'prepend'; /** - * Write only when the destination does not exist; never overwrite without `--force`. + * Writes the destination only when it is missing; only `reapply --force` overwrites an existing file. */ case Preserve = 'preserve'; /** - * Overwrite the destination unless the user has modified it (hash mismatch = skip). + * Overwrites the destination unless it changed since its recorded hash or was adopted from an existing file. */ case Replace = 'replace'; } diff --git a/src/Manifest/Glob.php b/src/Manifest/Glob.php index 4d1ceef..b503b50 100644 --- a/src/Manifest/Glob.php +++ b/src/Manifest/Glob.php @@ -4,29 +4,59 @@ namespace PHPForge\Scaffold\Manifest; +use LogicException; +use PHPForge\Scaffold\Exception\Message; + +use function array_map; +use function explode; +use function implode; +use function in_array; +use function preg_last_error_msg; use function preg_match; use function preg_quote; use function preg_replace_callback; +use function str_ends_with; +use function str_starts_with; +use function substr; /** - * Glob-to-regex converter and matcher for scaffold manifest patterns. - * - * Supports the subset used by `scaffold.json`: - * - * - `*` any sequence of characters that does NOT include a path separator. - * - `**` any sequence, including path separators (matches across directories). - * - `?` a single character that is not a path separator. - * - literals everything else matches byte-exact. - * - * Paths are normalised to forward slashes before matching so providers can share patterns across POSIX and Windows. + * Matches forward-slash paths against manifest glob patterns: `*` and `?` within one path segment, `**` across + * segments, single-level `{a,b}` alternatives, and byte-exact literals for everything else. */ final class Glob { /** - * Returns `true` when `$path` matches `$pattern` under scaffold's glob semantics. + * Returns the value of the first key of `$map` that matches `$path`; an exact key wins over globs, which match in + * declaration order. + * + * @template TValue * - * @param string $pattern Glob pattern. - * @param string $path Relative path to test (normalised to forward slashes). + * @param array $map Values keyed by glob pattern; integer-like patterns are integer keys. + * @param string $path Relative path with forward slashes. + * + * @return TValue|null Value of the matching pattern, or `null` when no pattern matches. + */ + public static function lookup(array $map, string $path): mixed + { + if (isset($map[$path])) { + return $map[$path]; + } + + foreach ($map as $pattern => $value) { + // PHP turns integer-like patterns ("123") into integer array keys. + if (self::matches((string) $pattern, $path)) { + return $value; + } + } + + return null; + } + + /** + * Returns whether `$pattern` matches the whole of `$path`. + * + * @param string $pattern Glob pattern to match against. + * @param string $path Relative path with forward slashes; this method does not convert backslashes. * * @return bool `true` when the pattern matches the full path, `false` otherwise. */ @@ -36,30 +66,74 @@ public static function matches(string $pattern, string $path): bool } /** - * Converts a scaffold glob pattern into an anchored PCRE regex. + * Returns whether any of `$patterns` matches the whole of `$path`. + * + * @param list $patterns Glob patterns. + * @param string $path Relative path with forward slashes. + * + * @return bool `true` when at least one pattern matches the path, `false` otherwise. + */ + public static function matchesAny(array $patterns, string $path): bool + { + foreach ($patterns as $pattern) { + if (self::matches($pattern, $path)) { + return true; + } + } + + return false; + } + + /** + * Returns whether a `

/**` pattern of `$patterns` excludes every descendant of `$directory`, so a walk can skip + * it. + * + * @param list $patterns Glob patterns. + * @param string $directory Relative directory path with forward slashes. + * + * @return bool `true` when `$patterns` holds `/**`, `false` otherwise. + */ + public static function prunes(array $patterns, string $directory): bool + { + return in_array("{$directory}/**", $patterns, true); + } + + /** + * Converts a glob pattern into an anchored PCRE regex, for example `#^config/[^/]*\.php$#` for `config/*.php`. * - * @param string $pattern Glob pattern. + * @param string $pattern Glob pattern to convert. * - * @return string Anchored PCRE regex matching the full string (e.g. `'#^config/[^/]+\.php$#'`). + * @return string PCRE regex with the `#` delimiter, anchored to match the full string. */ public static function toRegex(string $pattern): string + { + return '#^' . self::convert($pattern) . '$#'; + } + + /** + * Converts a glob pattern, or one brace alternative, into an unanchored PCRE fragment for the `#` delimiter. + * + * @param string $pattern Glob pattern or single brace alternative to convert. + * + * @return string Unanchored PCRE fragment with literals quoted for the `#` delimiter. + */ + private static function convert(string $pattern): string { // '**/' expands to "any number of directories including zero" so '**/foo' matches both 'foo' and 'a/b/foo'. - // '(string)' cast is defensive; preg_replace_callback only returns null on invalid regex. - // @codeCoverageIgnoreStart - $regex = (string) preg_replace_callback( - '#\*\*/|\*\*|\*|\?|[^*?]+#', - static fn(array $match): string => match ($match[0]) { - '**/' => '(?:.*/)?', - '**' => '.*', - '*' => '[^/]*', - '?' => '[^/]', + return preg_replace_callback( + '#\*\*/|\*\*|\*|\?|\{[^{}]*,[^{}]*\}|\{|[^*?{]+#', + static fn(array $match): string => match (true) { + $match[0] === '**/' => '(?:.*/)?', + $match[0] === '**' => '.*', + $match[0] === '*' => '[^/]*', + $match[0] === '?' => '[^/]', + str_starts_with($match[0], '{') && str_ends_with($match[0], '}') => '(?:' . implode( + '|', + array_map(self::convert(...), explode(',', substr($match[0], 1, -1))), + ) . ')', default => preg_quote($match[0], '#'), }, $pattern, - ); - // @codeCoverageIgnoreEnd - - return "#^{$regex}$#"; + ) ?? throw new LogicException(Message::REGEX_FAILED->getMessage(preg_last_error_msg())); } } diff --git a/src/Manifest/ManifestExpander.php b/src/Manifest/ManifestExpander.php index 3f34585..8e06127 100644 --- a/src/Manifest/ManifestExpander.php +++ b/src/Manifest/ManifestExpander.php @@ -5,37 +5,30 @@ namespace PHPForge\Scaffold\Manifest; use FilesystemIterator; +use PHPForge\Scaffold\Exception\Message; +use PHPForge\Scaffold\Merge\MergeStrategyKind; use RecursiveCallbackFilterIterator; use RecursiveDirectoryIterator; use RecursiveIteratorIterator; use RuntimeException; use SplFileInfo; +use function array_values; use function is_dir; use function is_file; use function rtrim; use function sort; -use function sprintf; -use function str_ends_with; -use function str_replace; use function strlen; use function substr; /** - * Expands a validated `scaffold.json` manifest into a flat list of {@see FileMapping} entries. + * Expands a validated manifest into file mappings; a later `copy[]` entry overrides an earlier one per destination. * - * Walks each path listed in `copy`: - * - * - Explicit file entries pass through unconditionally (bypass default excludes). - * - Directory entries are walked recursively; the built-in {@see DefaultExcludes} patterns plus the manifest's own - * `exclude[]` list filter the walk output. - * - * Mode resolution falls back to {@see FileMode::Replace} when no pattern in `modes{}` matches the destination. - * - * @phpstan-type ValidatedManifest = array{ + * @phpstan-type ValidatedManifest array{ * copy: list, * exclude: list, - * modes: array, + * modes: array, + * merge?: array, * } */ final class ManifestExpander @@ -54,91 +47,45 @@ final class ManifestExpander public function expand(array $manifest, string $providerPath, string $providerName): array { $mappings = []; - $seen = []; foreach ($manifest['copy'] as $entry) { $from = $entry['from']; - $to = $entry['to']; $absolute = "{$providerPath}/{$from}"; - if (is_file($absolute)) { - $source = self::normalise($from); - $destination = self::normalise($to); - - if (isset($seen[$destination])) { - continue; - } - - // The seen-map value is irrelevant; only key existence matters in the isset() guard above. - // @codeCoverageIgnoreStart - $seen[$destination] = true; - // @codeCoverageIgnoreEnd + $pairs = match (true) { + is_file($absolute) => [$from => $entry['to']], + is_dir($absolute) => $this->expandDirectory($absolute, $from, $entry['to'], $manifest['exclude']), + default => throw new RuntimeException( + Message::MANIFEST_COPY_ENTRY_NOT_FOUND->getMessage($from, $providerPath), + ), + }; - $mappings[] = $this->buildMapping( + foreach ($pairs as $source => $destination) { + // Assigning an existing key keeps its position, so a later entry overrides an earlier one in place. + $mappings[$destination] = new FileMapping( $destination, - $source, - $this->resolveMode($destination, $manifest['modes']), + (string) $source, + Glob::lookup($manifest['modes'], $destination) ?? FileMode::Replace, $providerName, $providerPath, + Glob::lookup($manifest['merge'] ?? [], $destination), ); - - continue; } - - if (is_dir($absolute)) { - // The +1 offset in self::translate() already skips the prefix separator, so trailing slashes here are - // absorbed downstream; the rtrim is kept defensively for clarity and substring-safety. - // @codeCoverageIgnoreStart - $sourcePrefix = rtrim(self::normalise($from), '/'); - // @codeCoverageIgnoreEnd - $sourcePrefix = $sourcePrefix === '.' ? '' : $sourcePrefix; - $destPrefix = rtrim(self::normalise($to), '/'); - $destPrefix = $destPrefix === '.' ? '' : $destPrefix; - - foreach ($this->walk($absolute, $sourcePrefix, $manifest['exclude']) as $source) { - $destination = self::translate($source, $sourcePrefix, $destPrefix); - - if (isset($seen[$destination])) { - continue; - } - - // The seen-map value is irrelevant; only key existence matters in the isset() guard above. - // @codeCoverageIgnoreStart - $seen[$destination] = true; - // @codeCoverageIgnoreEnd - - $mappings[] = $this->buildMapping( - $destination, - $source, - $this->resolveMode($destination, $manifest['modes']), - $providerName, - $providerPath, - ); - } - - continue; - } - - throw new RuntimeException( - sprintf('Scaffold copy entry "%s" does not exist under provider root "%s".', $from, $providerPath), - ); } - return $mappings; + return array_values($mappings); } /** - * Recursive filter callback deciding whether an iterator entry should be visited. - * - * Files pass through unconditionally so they can be exclude-filtered at file level; directories are tested against - * the default and user dir-prune patterns so that excluded subtrees (for example `vendor/**`) are never descended. + * Returns whether the directory walk accepts `$current`: files always, directories only when no `/**` + * exclude prunes them. * - * @param SplFileInfo $current Filesystem entry offered by the inner iterator. - * @param string $absolutePrefix Rtrim'd absolute path of the walk root on disk. - * @param string $relativePrefix Relative directory prefix to prepend when deriving the walk-relative path. - * @param list $userExcludes User-declared exclude patterns from the manifest. + * @param SplFileInfo $current Entry the directory iterator is visiting. + * @param string $absolutePrefix Walked directory on disk, without trailing slash. + * @param string $relativePrefix Provider-relative path of the walked directory, or an empty string for the root. + * @param list $userExcludes Manifest `exclude` patterns. * - * @return bool `true` when the iterator should accept the entry (and descend, for dirs), `false` to prune it. + * @return bool `true` when the entry is a file or a directory the walk may descend into, `false` otherwise. */ private function acceptIteratorEntry( SplFileInfo $current, @@ -146,167 +93,73 @@ private function acceptIteratorEntry( string $relativePrefix, array $userExcludes, ): bool { - // Files pass through unconditionally; only directories are subject to the descent-prune patterns. Without - // this branch, a file like 'secrets' would be dropped when the manifest contains 'secrets/**', since - // canDescend treats matching exclude prefixes as a hard reject regardless of entry type. - // @codeCoverageIgnoreStart - if ($current->isDir() === false) { + // Files pass through unconditionally: a file named `secrets` is not pruned by a `secrets/**` exclude. + if (!$current->isDir()) { return true; } - // @codeCoverageIgnoreEnd - return self::canDescend( - self::relativise($current, $absolutePrefix, $relativePrefix), - $userExcludes, - ); - } + $directory = self::relativise($current, $absolutePrefix, $relativePrefix); - /** - * Builds a {@see FileMapping} for a given source-destination pair. - * - * @param string $destination Relative destination path inside the consumer project, using forward slashes. - * @param string $source Relative source path inside the provider root, using forward slashes. - * @param FileMode $mode Resolved file mode for the mapping. - * @param string $providerName Composer package name (used to attribute the mapping for provenance). - * @param string $providerPath Absolute path to the provider root on disk. - * - * @return FileMapping Concrete file mapping for the given source/destination pair and mode. - */ - private function buildMapping( - string $destination, - string $source, - FileMode $mode, - string $providerName, - string $providerPath, - ): FileMapping { - return new FileMapping( - destination: $destination, - source: $source, - mode: $mode, - providerName: $providerName, - providerPath: $providerPath, - ); + return !Glob::prunes(DefaultExcludes::PATTERNS, $directory) && !Glob::prunes($userExcludes, $directory); } /** - * Determines whether the iterator may descend into `$relativeDir` based on both default and user exclude patterns. - * - * The directory may be pruned whenever a pattern of the form `$relativeDir/**` exists in either layer, because - * every possible descendant would then match an exclude and be dropped at file level anyway. + * Returns the files under a `copy[]` directory with their destinations, by replacing the source directory prefix + * with the destination prefix of the entry. * - * @param string $relativeDir Directory path relative to the walk root, using forward slashes. - * @param list $userExcludes User-declared exclude patterns from the manifest. + * @param string $absoluteDir Absolute path of the directory. + * @param string $from Provider-relative `from` path of the entry. + * @param string $to Project-relative `to` path of the entry. + * @param list $userExcludes Manifest `exclude` patterns. * - * @return bool `true` when the iterator should descend, `false` when the subtree may be skipped entirely. + * @return array Project-relative destinations keyed by sorted provider-relative source; + * integer-like sources (`"123"`) are integer keys. */ - private static function canDescend(string $relativeDir, array $userExcludes): bool + private function expandDirectory(string $absoluteDir, string $from, string $to, array $userExcludes): array { - if (DefaultExcludes::matchesDirectory($relativeDir)) { - return false; - } + // A trailing slash (`config/`) would otherwise leave `config//file` paths that excludes do not match. + $sourcePrefix = rtrim($from, '/'); - foreach ($userExcludes as $pattern) { - if (str_ends_with($pattern, '/**') && substr($pattern, 0, -3) === $relativeDir) { - return false; - } - } + $sourcePrefix = $sourcePrefix === '.' ? '' : $sourcePrefix; - return true; - } + $destPrefix = rtrim($to, '/'); - /** - * Determines if a given relative path matches any of the provided glob patterns. - * - * @param list $patterns Glob patterns to evaluate. - * @param string $path Relative path to test, using forward slashes. - * - * @return bool `true` when `$path` matches any of the given glob patterns, `false` otherwise. - */ - private static function matchesAny(string $path, array $patterns): bool - { - foreach ($patterns as $pattern) { - if (Glob::matches($pattern, $path)) { - return true; - } - } + $destPrefix = $destPrefix === '.' ? '' : $destPrefix; - return false; - } + $pairs = []; - /** - * Normalises a relative path to forward slashes. - * - * This is a no-op on POSIX but ensures consistent path handling on Windows, where `copy[]` entries may be declared - * with either slash type. - * - * @param string $path Relative path to normalise, using either forward or backward slashes. - * - * @return string Normalised path with forward slashes. - */ - private static function normalise(string $path): string - { - // Windows-only normalisation: str_replace is a no-op on POSIX (no backslash separators). - // @codeCoverageIgnoreStart - return str_replace('\\', '/', $path); - // @codeCoverageIgnoreEnd + foreach ($this->walk($absoluteDir, $sourcePrefix, $userExcludes) as $source) { + $pairs[$source] = self::translate($source, $sourcePrefix, $destPrefix); + } + + return $pairs; } /** - * Derives the walk-relative path for a filesystem entry, using forward slashes. - * - * Called both by the recursive filter (to decide whether to prune a directory) and by the main loop (to emit file - * destinations), so it produces the exact same string for a given entry in either context. + * Returns the provider-relative path of a walked entry, with forward slashes. * - * @param SplFileInfo $entry Filesystem entry returned by the iterator. - * @param string $absolutePrefix Rtrim'd absolute path of the walk root on disk. - * @param string $relativePrefix Relative directory prefix to prepend, or an empty string when walking from root. + * @param SplFileInfo $entry Entry under the walked directory, joined with forward slashes. + * @param string $absolutePrefix Walked directory on disk, without trailing slash. + * @param string $relativePrefix Provider-relative path of the walked directory, or an empty string for the root. * - * @return string Path relative to the walk root, using forward slashes. + * @return string Provider-relative path of the entry. */ private static function relativise(SplFileInfo $entry, string $absolutePrefix, string $relativePrefix): string { - $absolute = self::normalise($entry->getPathname()); - - $tail = substr($absolute, strlen($absolutePrefix) + 1); + $tail = substr($entry->getPathname(), strlen($absolutePrefix) + 1); return $relativePrefix === '' ? $tail : "{$relativePrefix}/{$tail}"; } /** - * Resolves the {@see FileMode} for `$relative` against the manifest's `modes` map. + * Maps a walked source path to its destination by replacing the source directory prefix with the destination + * prefix of the `copy[]` entry. * - * Exact path matches win over globs; globs are evaluated in declaration order. + * @param string $source Provider-relative source path. + * @param string $sourcePrefix Source directory without trailing slash, or an empty string for the provider root. + * @param string $destPrefix Destination directory without trailing slash, or an empty string for the project root. * - * @param array $modes Mode overrides from the manifest. - */ - private function resolveMode(string $relative, array $modes): FileMode - { - if (isset($modes[$relative])) { - return $modes[$relative]; - } - - foreach ($modes as $pattern => $mode) { - if (Glob::matches($pattern, $relative)) { - return $mode; - } - } - - return FileMode::Replace; - } - - /** - * Translates a walk-relative source path into its destination path by swapping the source prefix for the - * destination prefix. - * - * Used when a `copy[]` entry remaps a directory (`{from: "metadata/.github", to: ".github"}`) so each file - * discovered under the source prefix lands at the equivalent location under the destination prefix. - * - * @param string $source Walk-relative source path (already prefixed with the source directory). - * @param string $sourcePrefix Source directory prefix without trailing slash, or empty when walking from root. - * @param string $destPrefix Destination directory prefix without trailing slash, or empty when destination is - * the consumer root. - * - * @return string Destination path equivalent to `$source` after prefix translation. + * @return string Project-relative destination path. */ private static function translate(string $source, string $sourcePrefix, string $destPrefix): string { @@ -320,22 +173,26 @@ private static function translate(string $source, string $sourcePrefix, string $ } /** - * Walks a directory listed in `copy[]`, filtering out paths matching either default excludes or user excludes. + * Returns the files under a `copy[]` directory that match neither a default nor a manifest exclude. * - * @param string $absoluteDir Absolute path to the directory to walk. - * @param string $relativePrefix Relative directory prefix to prepend to each discovered file. - * @param list $userExcludes Glob patterns declared in `scaffold.exclude`. + * @param string $absoluteDir Absolute path of the directory. + * @param string $relativePrefix Provider-relative path of the directory, or an empty string for the root. + * @param list $userExcludes Manifest `exclude` patterns. * - * @return list Ordered list of relative file paths inside the directory that survive both exclusion layers. + * @return list Sorted provider-relative file paths. */ private function walk(string $absoluteDir, string $relativePrefix, array $userExcludes): array { $results = []; - $absolutePrefix = rtrim(self::normalise($absoluteDir), '/'); + + $absolutePrefix = rtrim($absoluteDir, '/'); $iterator = new RecursiveIteratorIterator( new RecursiveCallbackFilterIterator( - new RecursiveDirectoryIterator($absoluteDir, FilesystemIterator::SKIP_DOTS), + new RecursiveDirectoryIterator( + $absoluteDir, + FilesystemIterator::SKIP_DOTS | FilesystemIterator::UNIX_PATHS, + ), fn(SplFileInfo $current): bool => $this->acceptIteratorEntry( $current, $absolutePrefix, @@ -349,18 +206,15 @@ private function walk(string $absoluteDir, string $relativePrefix, array $userEx foreach ($iterator as $entry) { $relative = self::relativise($entry, $absolutePrefix, $relativePrefix); - if (DefaultExcludes::matches($relative) || self::matchesAny($relative, $userExcludes)) { + if (Glob::matchesAny(DefaultExcludes::PATTERNS, $relative) || Glob::matchesAny($userExcludes, $relative)) { continue; } $results[] = $relative; } - // Determinism guarantee for cross-filesystem reproducibility; many filesystems already return sorted dirents, - // so removing the sort is mutation-equivalent on POSIX/ext4 testbeds. - // @codeCoverageIgnoreStart + // Directory entry order depends on the filesystem; sorting keeps the mappings reproducible. sort($results); - // @codeCoverageIgnoreEnd return $results; } diff --git a/src/Manifest/ManifestLoader.php b/src/Manifest/ManifestLoader.php index f3e4044..0d458ee 100644 --- a/src/Manifest/ManifestLoader.php +++ b/src/Manifest/ManifestLoader.php @@ -4,120 +4,147 @@ namespace PHPForge\Scaffold\Manifest; -use Composer\Package\PackageInterface; +use PHPForge\Scaffold\Exception\Message; +use PHPForge\Scaffold\Filesystem; +use PHPForge\Scaffold\Security\PathValidator; use RuntimeException; -use function in_array; use function is_array; use function is_file; use function is_string; use function json_decode; -use function preg_match; -use function preg_split; -use function sprintf; -use function str_starts_with; /** - * Loads and expands a scaffold provider's manifest into a flat list of {@see FileMapping} entries. - * - * Supports both inline `extra.scaffold` declarations and external JSON manifests referenced by - * `extra.scaffold.manifest` relative to the provider root. + * Loads a provider manifest, inline in `extra.scaffold` or in the provider file named by `extra.scaffold.manifest`, and + * expands it into file mappings. */ final readonly class ManifestLoader { + /** + * @param ManifestSchema $schema Validates the manifest. + * @param ManifestExpander $expander Expands the validated manifest into file mappings. + */ public function __construct(private ManifestSchema $schema, private ManifestExpander $expander) {} /** - * Loads the provider's manifest and expands it into concrete file mappings. + * Loads the provider manifest from the `extra` section of a provider package and expands it into file mappings, + * without Composer's package classes. * - * @param PackageInterface $package Provider Composer package. - * @param string $packagePath Absolute path to the provider root on disk. + * @param array $extra `extra` section of the provider package. + * @param string $packageName Composer package name of the provider. + * @param string $packagePath Absolute path to the provider root. * - * @throws RuntimeException when the manifest file is missing, malformed, or structurally invalid. + * @throws RuntimeException when the manifest file is missing or unreadable, the manifest is invalid, or a `copy[]` + * path does not exist. + * @throws \JsonException when the external manifest file is not valid JSON. * - * @return list File mappings ready for the scaffolder. + * @return list File mappings; empty when `$extra` declares no `scaffold` object. */ - public function load(PackageInterface $package, string $packagePath): array + public function loadFromExtra(array $extra, string $packageName, string $packagePath): array { - $extra = $package->getExtra(); - $scaffold = $extra['scaffold'] ?? null; if (!is_array($scaffold)) { return []; } - $raw = isset($scaffold['manifest']) - ? $this->readExternal($scaffold['manifest'], $package->getName(), $packagePath) - : $scaffold; + // The inline block may carry consumer-side keys ('manifest', 'allowed-packages', 'auto'); an external manifest + // body may not. + $validated = isset($scaffold['manifest']) + ? $this->schema->validate($this->readExternal($scaffold['manifest'], $packageName, $packagePath)) + : $this->schema->validate($scaffold, true); - $validated = $this->schema->validate($raw); - - return $this->expander->expand($validated, $packagePath, $package->getName()); + return $this->expander->expand($validated, $packagePath, $packageName); } /** - * Reads and decodes an external manifest file referenced from `extra.scaffold.manifest`. + * Loads the provider manifest from the `composer.json` at the provider root and expands it into file mappings, + * exactly like {@see self::loadFromExtra()}. * - * @param mixed $manifestPath Raw manifest path from the provider declaration, expected to be a non-empty string. - * @param string $packageName Provider Composer package name (used for error messages). - * @param string $packagePath Absolute path to the provider root on disk. + * @param string $packageName Composer package name of the provider. + * @param string $packagePath Absolute path to the provider root. * - * @throws RuntimeException on any failure to read or decode the file. + * @throws RuntimeException when the provider `composer.json` or the manifest file is missing, unreadable or + * invalid, or a `copy[]` path does not exist. + * @throws \JsonException when the provider `composer.json` or the external manifest file is not valid JSON. * - * @return array Raw decoded JSON content ready for {@see ManifestSchema::validate()}. + * @return list File mappings; empty when the package declares no `extra.scaffold` object. */ - private function readExternal(mixed $manifestPath, string $packageName, string $packagePath): array + public function loadFromPath(string $packageName, string $packagePath): array { - if (!is_string($manifestPath) || $manifestPath === '') { - throw new RuntimeException( - sprintf('Provider "%s": "manifest" must be a non-empty string.', $packageName), - ); - } - - // Reject absolute paths: POSIX ('/foo'), Windows UNC/backslash ('\foo'), Windows drive ('C:\foo'). - $isAbsolute = str_starts_with($manifestPath, '/') - || str_starts_with($manifestPath, '\\') - || preg_match('/^[A-Za-z]:/', $manifestPath) === 1; + $composerJson = $this->decodeFile( + $packagePath . '/composer.json', + $packageName, + 'composer.json', + ); - if ($isAbsolute) { - throw new RuntimeException( - sprintf('Provider "%s": "manifest" must be a relative path inside the provider root.', $packageName), - ); - } + $extra = $composerJson['extra'] ?? []; - $segments = preg_split('#[/\\\\]#', $manifestPath); + return $this->loadFromExtra(is_array($extra) ? $extra : [], $packageName, $packagePath); + } - if (is_array($segments) && in_array('..', $segments, true)) { + /** + * Reads and decodes a provider JSON file that must contain an object. + * + * @param string $absolutePath Absolute path to the file. + * @param string $packageName Provider package name, used in error messages. + * @param string $label File description used in error messages. + * + * @throws RuntimeException when the file is missing, unreadable, or not a JSON object. + * @throws \JsonException when the file is not valid JSON. + * + * @return array Decoded object. + */ + private function decodeFile(string $absolutePath, string $packageName, string $label): array + { + if (!is_file($absolutePath)) { throw new RuntimeException( - sprintf('Provider "%s": "manifest" must be a relative path inside the provider root.', $packageName), + Message::MANIFEST_PROVIDER_FILE_NOT_FOUND->getMessage($packageName, $label, $absolutePath), ); } - $absolutePath = $packagePath . '/' . $manifestPath; + $content = Filesystem::read( + $absolutePath, + Message::MANIFEST_PROVIDER_FILE_UNREADABLE->getMessage($packageName, $label, $absolutePath), + ); - if (!is_file($absolutePath)) { + $raw = json_decode($content, associative: true, flags: JSON_THROW_ON_ERROR); + + if (!is_array($raw)) { throw new RuntimeException( - sprintf('Provider "%s": manifest file not found at "%s".', $packageName, $absolutePath), + Message::MANIFEST_PROVIDER_FILE_NOT_OBJECT->getMessage($packageName, $label, $absolutePath), ); } - $content = file_get_contents($absolutePath); + return $raw; + } - if ($content === false) { + /** + * Reads and decodes the external manifest file named by `extra.scaffold.manifest`. + * + * @param mixed $manifestPath Raw `manifest` value, expected to be a non-empty relative path inside the provider. + * @param string $packageName Provider package name, used in error messages. + * @param string $packagePath Absolute path to the provider root. + * + * @throws RuntimeException when the path is invalid or the file is missing, unreadable, or not a JSON object. + * @throws \JsonException when the file is not valid JSON. + * + * @return array Decoded manifest. + */ + private function readExternal(mixed $manifestPath, string $packageName, string $packagePath): array + { + if (!is_string($manifestPath) || $manifestPath === '') { throw new RuntimeException( - sprintf('Provider "%s": could not read manifest file "%s".', $packageName, $absolutePath), + Message::MANIFEST_REFERENCE_EMPTY->getMessage($packageName), ); } - $raw = json_decode($content, associative: true, flags: JSON_THROW_ON_ERROR); - - if (!is_array($raw)) { + if (PathValidator::isAbsolute($manifestPath) || PathValidator::hasTraversal($manifestPath)) { throw new RuntimeException( - sprintf('Provider "%s": manifest file "%s" must decode to an object.', $packageName, $absolutePath), + Message::MANIFEST_REFERENCE_NOT_RELATIVE->getMessage($packageName), ); } - return $raw; + return $this->decodeFile($packagePath . '/' . $manifestPath, $packageName, 'manifest file'); } } diff --git a/src/Manifest/ManifestSchema.php b/src/Manifest/ManifestSchema.php index afff6d9..9596734 100644 --- a/src/Manifest/ManifestSchema.php +++ b/src/Manifest/ManifestSchema.php @@ -4,6 +4,10 @@ namespace PHPForge\Scaffold\Manifest; +use BackedEnum; +use PHPForge\Scaffold\Exception\Message; +use PHPForge\Scaffold\Merge\MergeStrategyKind; +use PHPForge\Scaffold\Security\PathValidator; use RuntimeException; use function array_column; @@ -13,44 +17,58 @@ use function in_array; use function is_array; use function is_string; -use function preg_match; -use function preg_split; -use function sprintf; -use function str_starts_with; +use function sort; +use function str_replace; /** - * Validates and normalises the `scaffold.json` manifest structure. - * - * Accepts the `copy` / `exclude` / `modes` schema introduced in `0.2.0` and returns a typed structure ready for - * {@see ManifestExpander} to consume. Throws {@see RuntimeException} with a descriptive message on the first - * structural violation found. - * - * `copy[]` entries may be either a plain string (path used as both source and destination) or an object - * `{"from": "", "to": ""}` for explicit source-to-destination remapping. The validator - * normalises strings into the object form so downstream consumers see a single shape. + * Validates a provider manifest and normalises it into typed `copy`, `exclude`, `modes` and `merge` entries. * * @phpstan-type CopyEntry array{from: string, to: string} - * @phpstan-type ValidatedManifest array{copy: list, exclude: list, modes: array} + * @phpstan-type ValidatedManifest array{ + * copy: list, + * exclude: list, + * modes: array, + * merge: array, + * } */ final class ManifestSchema { + /** + * Consumer-side keys that may share the inline `extra.scaffold` block with the manifest body. + */ + private const array CONSUMER_KEYS = ['allowed-packages', 'auto', 'manifest']; + /** + * Keys of a manifest body. + */ + private const array MANIFEST_KEYS = ['copy', 'exclude', 'merge', 'modes']; + /** * Validates a raw decoded manifest array and returns the typed structure. * * @param array $raw Decoded JSON content of the manifest (or the inline `extra.scaffold` array). + * @param bool $inline `true` when `$raw` is the inline `extra.scaffold` block, which may also carry the + * consumer-side keys `manifest`, `allowed-packages` and `auto`. * - * @throws RuntimeException when the manifest structure is invalid. + * @throws RuntimeException when the manifest structure is invalid or contains an unknown key. * - * @return array{copy: list, exclude: list, modes: array} - * Typed manifest with `copy[]` entries normalised to `{from, to}` form and `modes` values resolved to - * {@see FileMode} cases. + * @return array{ + * copy: list, + * exclude: list, + * modes: array, + * merge: array, + * } + * Typed manifest with `copy[]` entries normalised to `{from, to}` form, `modes` values resolved to + * {@see FileMode} cases and `merge` values resolved to {@see MergeStrategyKind} cases. */ - public function validate(array $raw): array + public function validate(array $raw, bool $inline = false): array { + $this->validateKeys($raw, $inline); + return [ 'copy' => $this->validateCopy($raw), 'exclude' => $this->validateExclude($raw), - 'modes' => $this->validateModes($raw), + 'modes' => $this->validateEnumMap($raw, 'modes', FileMode::class, 'mode', false), + 'merge' => $this->validateEnumMap($raw, 'merge', MergeStrategyKind::class, 'strategy', true), ]; } @@ -68,55 +86,64 @@ private function assertSafeRelativePath(mixed $path, string $key): void { if (!is_string($path) || $path === '') { throw new RuntimeException( - sprintf('Manifest "%s" entries must be non-empty strings.', $key), + Message::MANIFEST_ENTRY_EMPTY->getMessage($key), ); } - // Reject absolute paths: POSIX ('/foo'), Windows UNC/backslash ('\foo'), Windows drive ('C:\foo'). - $isAbsolute = str_starts_with($path, '/') - || str_starts_with($path, '\\') - || preg_match('/^[A-Za-z]:/', $path) === 1; - - if ($isAbsolute) { + if (PathValidator::isAbsolute($path)) { throw new RuntimeException( - sprintf('Manifest "%s" entry "%s" must be a relative path.', $key, $path), + Message::MANIFEST_ENTRY_ABSOLUTE->getMessage($key, $path), ); } - $segments = preg_split('#[/\\\\]#', $path); - - if (is_array($segments) && in_array('..', $segments, true)) { + if (PathValidator::hasTraversal($path)) { throw new RuntimeException( - sprintf('Manifest "%s" entry "%s" must not contain path traversal segments.', $key, $path), + Message::MANIFEST_ENTRY_TRAVERSAL->getMessage($key, $path), ); } } /** - * Validates the `copy` key. + * Converts the backslash separators of a path to forward slashes. + * + * @param string $path Path to convert. * - * Accepts plain string entries (treated as `from === to`) and `{from, to}` object entries for explicit - * source-to-destination remapping. The result always uses the object form for uniform downstream handling. + * @return string Path with forward slashes only. + */ + private static function toForwardSlashes(string $path): string + { + return str_replace('\\', '/', $path); + } + + /** + * Validates the required `copy` list, normalising string entries to `{from, to}` pairs with the same path and + * backslash separators to forward slashes. * * @param array $raw Raw manifest array. * + * @throws RuntimeException when `copy` is missing, empty, not a list, or holds an invalid entry. + * * @return list List of normalised entries; both fields are non-empty, relative, - * non-traversal paths. + * non-traversal paths with forward slashes. */ private function validateCopy(array $raw): array { if (!array_key_exists('copy', $raw) || !is_array($raw['copy'])) { - throw new RuntimeException('Manifest is missing required key "copy" or it is not an array.'); + throw new RuntimeException( + Message::MANIFEST_COPY_MISSING->getMessage(), + ); } if ($raw['copy'] !== [] && !array_is_list($raw['copy'])) { throw new RuntimeException( - 'Manifest "copy" must be a sequential list of entries, not an associative object.', + Message::MANIFEST_COPY_NOT_LIST->getMessage(), ); } if ($raw['copy'] === []) { - throw new RuntimeException('Manifest "copy" must declare at least one path.'); + throw new RuntimeException( + Message::MANIFEST_COPY_EMPTY->getMessage(), + ); } $entries = []; @@ -125,7 +152,9 @@ private function validateCopy(array $raw): array if (is_string($entry)) { $this->assertSafeRelativePath($entry, 'copy'); - $entries[] = ['from' => $entry, 'to' => $entry]; + $path = self::toForwardSlashes($entry); + + $entries[] = ['from' => $path, 'to' => $path]; continue; } @@ -134,17 +163,75 @@ private function validateCopy(array $raw): array $this->assertSafeRelativePath($entry['from'], 'copy.from'); $this->assertSafeRelativePath($entry['to'], 'copy.to'); - $entries[] = ['from' => $entry['from'], 'to' => $entry['to']]; + $entries[] = [ + 'from' => self::toForwardSlashes($entry['from']), + 'to' => self::toForwardSlashes($entry['to']), + ]; continue; } + throw new RuntimeException(Message::MANIFEST_COPY_ENTRY_INVALID->getMessage()); + } + + return $entries; + } + + /** + * Validates the optional `modes` or `merge` key: an object that maps safe patterns to values of `$enum`. + * + * @template TEnum of BackedEnum + * + * @param array $raw Raw manifest array. + * @param string $key Manifest key to validate (`modes` or `merge`). + * @param class-string $enum Enum whose backing values the map may use. + * @param string $label Name of one value in the error messages (`mode` or `strategy`). + * @param bool $rejectList Whether a non-empty list is rejected as not an object. + * + * @throws RuntimeException when the key is not an object or holds an unsafe pattern or unknown value. + * + * @return array Values keyed by pattern; integer-like patterns become integer keys. + */ + private function validateEnumMap(array $raw, string $key, string $enum, string $label, bool $rejectList): array + { + if (!array_key_exists($key, $raw)) { + return []; + } + + $map = $raw[$key]; + + if (!is_array($map) || ($rejectList && $map !== [] && array_is_list($map))) { throw new RuntimeException( - 'Manifest "copy" entries must be either a string or an object with "from" and "to" keys.', + Message::MANIFEST_MAP_NOT_OBJECT->getMessage($key), ); } - return $entries; + $resolved = []; + + foreach ($map as $pattern => $value) { + // PHP turns integer-like patterns ("123") into integer array keys. + $pattern = (string) $pattern; + + $this->assertSafeRelativePath($pattern, $key); + + if (!is_string($value)) { + throw new RuntimeException( + Message::MANIFEST_MAP_VALUE_NOT_STRING->getMessage($key, $pattern), + ); + } + + $resolved[$pattern] = $enum::tryFrom($value) ?? throw new RuntimeException( + Message::MANIFEST_MAP_VALUE_INVALID->getMessage( + $key, + $pattern, + $label, + $value, + implode(', ', array_column($enum::cases(), 'value')), + ), + ); + } + + return $resolved; } /** @@ -152,6 +239,8 @@ private function validateCopy(array $raw): array * * @param array $raw Raw manifest array. * + * @throws RuntimeException when `exclude` is not an array or holds an unsafe pattern. + * * @return list List of non-empty, relative, non-traversal patterns. */ private function validateExclude(array $raw): array @@ -161,7 +250,9 @@ private function validateExclude(array $raw): array } if (!is_array($raw['exclude'])) { - throw new RuntimeException('Manifest "exclude" must be an array when present.'); + throw new RuntimeException( + Message::MANIFEST_EXCLUDE_NOT_ARRAY->getMessage(), + ); } $patterns = []; @@ -176,49 +267,27 @@ private function validateExclude(array $raw): array } /** - * Validates the optional `modes` key. + * Rejects top-level keys outside the allowed set. * * @param array $raw Raw manifest array. + * @param bool $inline Whether the consumer-side keys are allowed too. * - * @return array Mode map keyed by pattern. + * @throws RuntimeException when a key is not allowed. */ - private function validateModes(array $raw): array + private function validateKeys(array $raw, bool $inline): void { - if (!array_key_exists('modes', $raw)) { - return []; - } - - if (!is_array($raw['modes'])) { - throw new RuntimeException('Manifest "modes" must be an object when present.'); - } + $allowed = $inline ? [...self::MANIFEST_KEYS, ...self::CONSUMER_KEYS] : self::MANIFEST_KEYS; - $resolved = []; + sort($allowed); - foreach ($raw['modes'] as $pattern => $modeValue) { - $this->assertSafeRelativePath($pattern, 'modes'); + foreach ($raw as $key => $_) { + $key = (string) $key; - if (!is_string($modeValue)) { + if (!in_array($key, $allowed, true)) { throw new RuntimeException( - sprintf('Manifest "modes" value for pattern "%s" must be a string.', $pattern), + Message::MANIFEST_KEY_UNKNOWN->getMessage($key, implode(', ', $allowed)), ); } - - $mode = FileMode::tryFrom($modeValue); - - if ($mode === null) { - throw new RuntimeException( - sprintf( - 'Manifest "modes" value for pattern "%s" has invalid mode "%s". Allowed: %s.', - $pattern, - $modeValue, - implode(', ', array_column(FileMode::cases(), 'value')), - ), - ); - } - - $resolved[$pattern] = $mode; } - - return $resolved; } } diff --git a/src/Merge/AbstractLineMergeStrategy.php b/src/Merge/AbstractLineMergeStrategy.php new file mode 100644 index 0000000..f556a7a --- /dev/null +++ b/src/Merge/AbstractLineMergeStrategy.php @@ -0,0 +1,64 @@ +>, blocks: list>} + */ +abstract class AbstractLineMergeStrategy implements MergeStrategy +{ + /** + * Computes the insertions that make the consumer satisfy the provider. + * + * @param list $provider Provider lines. + * @param list $consumer Consumer lines without terminators. + * + * @return MergePlan Lines to insert after a consumer line index (`-1` inserts at the top) and blocks to append at + * the end; both empty when the consumer already satisfies the provider. + */ + abstract protected function plan(array $provider, array $consumer): array; + + /** + * Adds the provider entries missing from the consumer. + * + * @param string $provider Provider content whose missing entries are added. + * @param string $consumer Consumer content; an empty string stands for an absent file. + * + * @return MergeResult Merged content and whether it differs from the consumer. + */ + public function merge(string $provider, string $consumer): MergeResult + { + $providerLines = Lines::split(Lines::normalise($provider)); + + if ($consumer === '') { + return new MergeResult($provider, $provider !== ''); + } + + $segments = Lines::splitRaw($consumer); + + $plan = $this->plan( + $providerLines, + array_map(static fn(array $segment): string => $segment[0], $segments), + ); + + if ($plan['insertAfter'] === [] && $plan['blocks'] === []) { + return new MergeResult($consumer, false); + } + + $content = Lines::rebuild( + $segments, + $plan['insertAfter'], + $plan['blocks'], + Lines::detectEol($consumer), + Lines::endsWithEol($consumer) || Lines::endsWithEol($provider), + ); + + return new MergeResult($content, $content !== $consumer); + } +} diff --git a/src/Merge/IniMergeStrategy.php b/src/Merge/IniMergeStrategy.php new file mode 100644 index 0000000..ba0c513 --- /dev/null +++ b/src/Merge/IniMergeStrategy.php @@ -0,0 +1,265 @@ +, + * body: list, + * keys: array, + * lastKey: int, + * } + * @phpstan-type Document array{ + * preambleKeys: array, + * preambleLastKey: int|null, + * preambleLength: int, + * sections: list
, + * } + * @phpstan-import-type MergePlan from AbstractLineMergeStrategy + */ +final class IniMergeStrategy extends AbstractLineMergeStrategy +{ + /** + * Plans missing preamble keys, missing keys inside existing sections and missing sections appended whole. + * + * @param list $provider Provider lines. + * @param list $consumer Consumer lines without terminators. + * + * @return MergePlan Lines to insert after a consumer line index and blocks to append; both empty when satisfied. + */ + protected function plan(array $provider, array $consumer): array + { + $source = self::parse($provider); + $target = self::parse($consumer); + + $insertAfter = []; + $blocks = []; + + $missingPreamble = []; + + foreach ($source['preambleKeys'] as $key => $line) { + if (!isset($target['preambleKeys'][$key])) { + $missingPreamble[] = $line; + } + } + + if ($missingPreamble !== []) { + if ($target['preambleLastKey'] !== null) { + $insertAfter[$target['preambleLastKey']] = $missingPreamble; + } else { + if ($target['preambleLength'] === 0 && $consumer !== []) { + // Keep one blank line between the inserted keys and the consumer's first section header. + $missingPreamble[] = ''; + } + + $insertAfter[-1] = $missingPreamble; + } + } + + // First occurrence of each consumer section, and the keys of every occurrence of that section. + $firstSection = []; + $sectionKeys = []; + + foreach ($target['sections'] as $section) { + $firstSection[$section['id']] ??= $section; + // Union keeps integer keys, which PHP makes of numeric INI keys and array unpacking would renumber. + $sectionKeys[$section['id']] = ($sectionKeys[$section['id']] ?? []) + $section['keys']; + } + + // Blocks appended for sections the consumer lacks, keyed by section identity. + $appended = []; + + foreach ($source['sections'] as $section) { + $id = $section['id']; + + if (isset($firstSection[$id])) { + foreach ($section['keys'] as $key => $line) { + if (!isset($sectionKeys[$id][$key])) { + $sectionKeys[$id][$key] = $line; + $insertAfter[$firstSection[$id]['lastKey']][] = $line; + } + } + + continue; + } + + if (isset($appended[$id])) { + // A provider section declared twice: its later keys extend the block already appended. + foreach ($section['keys'] as $key => $line) { + if (!isset($sectionKeys[$id][$key])) { + $sectionKeys[$id][$key] = $line; + $blocks[$appended[$id]][] = $line; + } + } + + continue; + } + + $appended[$id] = count($blocks); + $sectionKeys[$id] = $section['keys']; + $blocks[] = [...$section['lead'], $section['header'], ...$section['body']]; + } + + return [ + 'insertAfter' => $insertAfter, + 'blocks' => $blocks, + ]; + } + + /** + * Returns whether the trimmed line is a comment (`#` or `;`). + * + * @param string $trimmed Trimmed line. + * + * @return bool `true` when the line starts with `#` or `;`. + */ + private static function isComment(string $trimmed): bool + { + return str_starts_with($trimmed, '#') || str_starts_with($trimmed, ';'); + } + + /** + * Returns the lower-cased key of a trimmed `key = value` line, or `null` for any other line. + * + * @param string $trimmed Trimmed line. + * + * @return string|null Lower-cased, trimmed key, or `null` for blank, comment, header, keyless or `=`-less lines. + */ + private static function keyOf(string $trimmed): string|null + { + if ($trimmed === '' || self::isComment($trimmed) || self::sectionId($trimmed) !== null) { + return null; + } + + $position = strpos($trimmed, '='); + + if ($position === false) { + return null; + } + + $key = strtolower(trim(substr($trimmed, 0, $position))); + + return $key === '' ? null : $key; + } + + /** + * Parses lines into a preamble and sections; comments directly above a header belong to that header. + * + * @param list $lines Lines to parse. + * + * @return Document Parsed document. + */ + private static function parse(array $lines): array + { + $headers = []; + + foreach ($lines as $index => $line) { + $id = self::sectionId(trim($line)); + + if ($id !== null) { + $headers[$index] = ['id' => $id, 'line' => $line]; + } + } + + $count = count($lines); + + $preambleLength = array_key_first($headers) ?? $count; + $preambleKeys = []; + $preambleLastKey = null; + + foreach (array_slice($lines, 0, $preambleLength) as $index => $line) { + $trimmed = trim($line); + + $key = self::keyOf($trimmed); + + if ($key !== null) { + $preambleKeys[$key] ??= $trimmed; + $preambleLastKey = $index; + } + } + + // Start of each header's lead (comment lines directly above it). The climb stops at the previous header, which + // is never a comment, or before the first line, which reads as an empty line. + $spans = []; + + foreach ($headers as $headerIndex => $header) { + $start = $headerIndex; + + while (self::isComment(trim($lines[$start - 1] ?? ''))) { + $start--; + } + + $spans[] = ['index' => $headerIndex, 'header' => $header, 'leadStart' => $start]; + } + + $sections = []; + + foreach ($spans as $position => ['index' => $headerIndex, 'header' => $header, 'leadStart' => $leadStart]) { + $bodyEnd = $spans[$position + 1]['leadStart'] ?? $count; + $body = array_slice($lines, $headerIndex + 1, $bodyEnd - $headerIndex - 1); + + while ($body !== [] && trim($body[count($body) - 1]) === '') { + array_pop($body); + } + + $keys = []; + $lastKey = $headerIndex; + + foreach ($body as $offset => $line) { + $key = self::keyOf(trim($line)); + + if ($key !== null) { + $keys[$key] ??= $line; + $lastKey = $headerIndex + 1 + $offset; + } + } + + $sections[] = [ + 'id' => $header['id'], + 'header' => $header['line'], + 'lead' => array_slice($lines, $leadStart, $headerIndex - $leadStart), + 'body' => $body, + 'keys' => $keys, + 'lastKey' => $lastKey, + ]; + } + + return [ + 'preambleKeys' => $preambleKeys, + 'preambleLastKey' => $preambleLastKey, + 'preambleLength' => $preambleLength, + 'sections' => $sections, + ]; + } + + /** + * Returns the identity of a trimmed `[section]` header, which is the header without a trailing `#` or `;` comment. + * + * @param string $trimmed Trimmed line. + * + * @return string|null Header up to its closing `]`, or `null` when the line is no section header. + */ + private static function sectionId(string $trimmed): string|null + { + return preg_match('/^(\[.*\])\s*(?:[#;].*)?$/', $trimmed, $matches) === 1 ? $matches[1] : null; + } +} diff --git a/src/Merge/Lines.php b/src/Merge/Lines.php new file mode 100644 index 0000000..983b148 --- /dev/null +++ b/src/Merge/Lines.php @@ -0,0 +1,205 @@ +getMessage(preg_last_error_msg())); + } + + /** + * Rebuilds consumer segments verbatim with inserted lines and appended blocks, each block after one blank line. + * + * @param list $segments Consumer `[text, terminator]` segments. + * @param array> $insertAfter Lines to insert after the segment with the given index; index `-1` + * inserts before the first segment. + * @param list> $blocks Blocks of lines appended at the end, in order. + * @param string $eol End-of-line sequence used for inserted lines. + * @param bool $finalEol Whether the result must end with an end-of-line sequence. + * + * @return string Rebuilt content. + */ + public static function rebuild( + array $segments, + array $insertAfter, + array $blocks, + string $eol, + bool $finalEol, + ): string { + $output = isset($insertAfter[-1]) ? implode($eol, $insertAfter[-1]) . $eol : ''; + + foreach ($segments as $index => [$text, $terminator]) { + $output .= "{$text}{$terminator}"; + + if (isset($insertAfter[$index])) { + $output = self::terminate($output, $eol) . implode($eol, $insertAfter[$index]) . $eol; + } + } + + foreach ($blocks as $block) { + $output = self::terminate($output, $eol); + + if ($output !== '' && !self::endsWithBlankLine($output)) { + $output .= $eol; + } + + $output .= implode($eol, $block); + } + + if ($finalEol) { + return self::terminate($output, $eol); + } + + if (str_ends_with($output, "\r\n")) { + return substr($output, 0, -2); + } + + return self::endsWithEol($output) ? substr($output, 0, -1) : $output; + } + + /** + * Splits content normalised to `"\n"` into lines, ignoring the terminator of the last line. + * + * @param string $content Content normalised to `"\n"` terminators. + * + * @return list Lines; empty for empty content. + */ + public static function split(string $content): array + { + if ($content === '') { + return []; + } + + if (str_ends_with($content, "\n")) { + $content = substr($content, 0, -1); + } + + return explode("\n", $content); + } + + /** + * Splits raw content into lines that keep their original terminator. + * + * @param string $content Content with any mix of `"\r\n"`, `"\r"` and `"\n"` terminators. + * + * @return list `[text, terminator]` pairs; the last terminator is empty when the content + * does not end with an end-of-line sequence. + */ + public static function splitRaw(string $content): array + { + $segments = []; + + $chunks = explode("\n", $content); + $lastChunk = count($chunks) - 1; + + foreach ($chunks as $index => $chunk) { + $chunkEol = $index < $lastChunk ? "\n" : ''; + + if ($chunkEol === "\n" && str_ends_with($chunk, "\r")) { + $chunk = substr($chunk, 0, -1); + $chunkEol = "\r\n"; + } + + // Legacy Mac CR terminators inside the chunk produce their own segments; the final piece takes the chunk + // terminator, except for the empty piece a trailing terminator leaves behind. + $pieces = explode("\r", $chunk); + $lastPiece = count($pieces) - 1; + + foreach ($pieces as $pieceIndex => $piece) { + if ($pieceIndex < $lastPiece) { + $segments[] = [$piece, "\r"]; + } elseif ($piece !== '' || $chunkEol !== '') { + $segments[] = [$piece, $chunkEol]; + } + } + } + + return $segments; + } + + /** + * Returns whether the last line of terminated content is blank. + * + * @param string $output Content that ends with an end-of-line sequence. + * + * @return bool `true` when the content is a single terminator or ends with two consecutive terminators. + */ + private static function endsWithBlankLine(string $output): bool + { + $normalised = self::normalise($output); + + return $normalised === "\n" || str_ends_with($normalised, "\n\n"); + } + + /** + * Terminates non-empty content that does not end with an end-of-line sequence. + * + * @param string $output Content to terminate. + * @param string $eol End-of-line sequence to append. + * + * @return string Content ending with an end-of-line sequence, or the empty string unchanged. + */ + private static function terminate(string $output, string $eol): string + { + return $output !== '' && !self::endsWithEol($output) ? "{$output}{$eol}" : $output; + } +} diff --git a/src/Merge/ListMergeStrategy.php b/src/Merge/ListMergeStrategy.php new file mode 100644 index 0000000..6164a3d --- /dev/null +++ b/src/Merge/ListMergeStrategy.php @@ -0,0 +1,157 @@ + $provider Provider lines. + * @param list $consumer Consumer lines without terminators. + * + * @return MergePlan Lines to insert after a consumer line index and blocks to append; both empty when satisfied. + */ + protected function plan(array $provider, array $consumer): array + { + // Blank and comment lines never match a provider entry, so every trimmed consumer line can be indexed. + $present = array_flip(array_map(trim(...), $consumer)); + + $insertAfter = []; + $blocks = []; + + foreach (self::groups($provider) as [$comments, $entries]) { + $missing = []; + + foreach ($entries as $entry) { + if (!isset($present[$entry])) { + $present[$entry] = $entry; + $missing[] = $entry; + } + } + + if ($missing === []) { + continue; + } + + $anchor = $comments === [] ? null : self::locate($consumer, trim($comments[0])); + + if ($anchor === null) { + $blocks[] = [...$comments, ...$missing]; + + continue; + } + + foreach ($missing as $entry) { + $insertAfter[$anchor][] = $entry; + } + } + + return [ + 'insertAfter' => $insertAfter, + 'blocks' => $blocks, + ]; + } + + /** + * Parses provider lines into groups delimited by blank lines or by a comment that follows an entry. + * + * @param list $lines Provider lines. + * + * @return list, list}> `[comments, entries]` pairs; entries are trimmed, and comment + * blocks without entries are dropped because they add nothing to the merge. + */ + private static function groups(array $lines): array + { + $groups = []; + $comments = []; + $entries = []; + + foreach ($lines as $line) { + $trimmed = trim($line); + + if ($trimmed === '' || (str_starts_with($trimmed, '#') && $entries !== [])) { + if ($entries !== []) { + $groups[] = [$comments, $entries]; + } + + $comments = []; + $entries = []; + + if ($trimmed === '') { + continue; + } + } + + if (str_starts_with($trimmed, '#')) { + $comments[] = $line; + } else { + $entries[] = $trimmed; + } + } + + if ($entries !== []) { + $groups[] = [$comments, $entries]; + } + + return $groups; + } + + /** + * Returns the index of the last line of the consumer block headed by `$comment`. + * + * @param list $consumer Consumer lines. + * @param string $comment Trimmed first comment line of the provider group, matched byte-exact. + * + * @return int|null Index of the block's last entry (or last header line), or `null` when the comment is absent. + */ + private static function locate(array $consumer, string $comment): int|null + { + foreach ($consumer as $index => $line) { + if (trim($line) !== $comment) { + continue; + } + + $anchor = $index; + $lastEntry = null; + + // The scan starts at the header itself, a comment line that leaves the anchor on the header. + foreach (array_slice($consumer, $index, preserve_keys: true) as $next => $nextLine) { + $trimmed = trim($nextLine); + + if ($trimmed === '') { + break; + } + + if (str_starts_with($trimmed, '#')) { + if ($lastEntry !== null) { + break; + } + + $anchor = $next; + + continue; + } + + $lastEntry = $next; + } + + return $lastEntry ?? $anchor; + } + + return null; + } +} diff --git a/src/Merge/MergeResult.php b/src/Merge/MergeResult.php new file mode 100644 index 0000000..ba1d6d6 --- /dev/null +++ b/src/Merge/MergeResult.php @@ -0,0 +1,20 @@ + new IniMergeStrategy(), + MergeStrategyKind::ListFile => new ListMergeStrategy(), + MergeStrategyKind::Text => new TextMergeStrategy(), + }; + } + + /** + * Returns the default strategy kind for a destination basename. + * + * @param string $destination Destination path relative to the project root. + * + * @return MergeStrategyKind `Ini` for `.editorconfig` and `*.ini`, `ListFile` for known ignore lists, else `Text`. + */ + private static function defaultKind(string $destination): MergeStrategyKind + { + $slash = strrpos($destination, '/'); + + $basename = $slash === false ? $destination : substr($destination, $slash + 1); + + if ($basename === '.editorconfig' || str_ends_with($basename, '.ini')) { + return MergeStrategyKind::Ini; + } + + if (in_array($basename, self::LIST_BASENAMES, true)) { + return MergeStrategyKind::ListFile; + } + + return MergeStrategyKind::Text; + } +} diff --git a/src/Merge/TextMergeStrategy.php b/src/Merge/TextMergeStrategy.php new file mode 100644 index 0000000..5138475 --- /dev/null +++ b/src/Merge/TextMergeStrategy.php @@ -0,0 +1,48 @@ + $provider Provider lines. + * @param list $consumer Consumer lines without terminators. + * + * @return MergePlan No insertions, and one block of missing lines, or no block when the consumer has them all. + */ + protected function plan(array $provider, array $consumer): array + { + $present = array_flip(array_map(rtrim(...), $consumer)); + + $missing = []; + + foreach ($provider as $line) { + $line = rtrim($line); + + if ($line === '' || isset($present[$line])) { + continue; + } + + $present[$line] = $line; + $missing[] = $line; + } + + return [ + 'insertAfter' => [], + 'blocks' => $missing === [] ? [] : [$missing], + ]; + } +} diff --git a/src/MessageTemplate.php b/src/MessageTemplate.php new file mode 100644 index 0000000..071eb96 --- /dev/null +++ b/src/MessageTemplate.php @@ -0,0 +1,39 @@ +value, ...$argument); + } + + /** + * Returns the text of `$one` when `$count` is `1`, and the text of `$many` otherwise. + * + * @param int $count Number of items the fragment counts. + * @param self $one Fragment for a single item. + * @param self $many Fragment for zero or several items. + * + * @return string Text of the fragment that agrees with `$count`. + */ + public static function plural(int $count, self $one, self $many): string + { + return ($count === 1 ? $one : $many)->getMessage(); + } +} diff --git a/src/Plugin.php b/src/Plugin.php index 2c75ce5..de9d986 100644 --- a/src/Plugin.php +++ b/src/Plugin.php @@ -6,27 +6,38 @@ use Composer\Composer; use Composer\IO\IOInterface; -use Composer\Plugin\{Capable, PluginInterface}; +use Composer\Plugin\PluginInterface; /** - * Composer plugin entry point for scaffold. - * - * Registers the event subscriber that orchestrates multi-layer file scaffolding during `composer install`, - * `composer update`, and `composer create-project`. + * Registers the {@see EventSubscriber} that scaffolds provider files after `composer install`, `composer update` and + * `composer create-project`. */ -final class Plugin implements PluginInterface, Capable +final class Plugin implements PluginInterface { /** - * Event subscriber instance registered with Composer, or `null` if not currently registered. + * Subscriber registered with Composer's event dispatcher, or `null` while the plugin is inactive. */ private EventSubscriber|null $subscriber = null; + /** + * Creates the event subscriber and registers it with Composer's event dispatcher. + * + * @param Composer $composer Composer instance whose event dispatcher receives the subscriber. + * @param IOInterface $io Composer IO; unused. + */ public function activate(Composer $composer, IOInterface $io): void { $this->subscriber = new EventSubscriber(); + $composer->getEventDispatcher()->addSubscriber($this->subscriber); } + /** + * Removes the registered event subscriber from Composer's event dispatcher. + * + * @param Composer $composer Composer instance whose event dispatcher holds the subscriber. + * @param IOInterface $io Composer IO; unused. + */ public function deactivate(Composer $composer, IOInterface $io): void { if ($this->subscriber !== null) { @@ -36,13 +47,10 @@ public function deactivate(Composer $composer, IOInterface $io): void } /** - * @return array An associative array mapping capability class names to their implementing class - * names. + * Performs no cleanup; scaffolded files and `scaffold-lock.json` stay in the project. + * + * @param Composer $composer Composer instance; unused. + * @param IOInterface $io Composer IO; unused. */ - public function getCapabilities(): array - { - return []; - } - public function uninstall(Composer $composer, IOInterface $io): void {} } diff --git a/src/Scaffold/Applier.php b/src/Scaffold/Applier.php deleted file mode 100644 index aab4162..0000000 --- a/src/Scaffold/Applier.php +++ /dev/null @@ -1,76 +0,0 @@ -allowlist->assertAllowed($mapping->providerName); - $this->pathValidator->validateDestination($mapping->destination, $projectRoot); - $this->pathValidator->validateSource($mapping->source, $mapping->providerPath); - - $resolvedRoot = realpath($projectRoot); - - $safeRoot = $resolvedRoot !== false ? $resolvedRoot : $projectRoot; - - $resolvedProviderPath = realpath($mapping->providerPath); - - $safeProviderPath = $resolvedProviderPath !== false ? $resolvedProviderPath : $mapping->providerPath; - - $resolvedMapping = new FileMapping( - $mapping->destination, - $mapping->source, - $mapping->mode, - $mapping->providerName, - $safeProviderPath, - ); - - $result = $mode->apply($resolvedMapping, $safeRoot, $this->hasher, $hashAtScaffold); - - if ($result->warning !== null) { - $this->io->writeError('[scaffold] ' . $result->warning); - } - - return $result; - } -} diff --git a/src/Scaffold/ExpectedState.php b/src/Scaffold/ExpectedState.php new file mode 100644 index 0000000..fc33e56 --- /dev/null +++ b/src/Scaffold/ExpectedState.php @@ -0,0 +1,204 @@ + $mappings Expected mappings keyed by destination. + * @param list $failedProviders Allowed and installed providers whose manifest could not be loaded. + * @param list $warnings Messages about provider roots and manifests, prefixed with `[scaffold]`. + */ + public function __construct( + private array $mappings, + private array $failedProviders = [], + public array $warnings = [], + ) {} + + /** + * Returns every expected mapping keyed by destination, in `allowed-packages` and manifest order. + * + * @return array Mappings keyed by destination; integer-like destinations (`"123"`) are + * integer keys. + */ + public function all(): array + { + return $this->mappings; + } + + /** + * Loads the manifests of every allowed and installed provider, in `allowed-packages` order. + * + * @param ProjectContext $context Project whose providers are loaded. + * @param array $lockProviders `providers` map of `scaffold-lock.json`, used for recorded paths. + * @param ManifestLoader $loader Loads the provider manifests into file mappings. + * + * @return self Merged mappings, the providers whose manifest failed to load, and their warnings. + */ + public static function build( + ProjectContext $context, + array $lockProviders, + ManifestLoader $loader = new ManifestLoader(new ManifestSchema(), new ManifestExpander()), + ): self { + $resolved = $context->providers($lockProviders); + + $merged = []; + $failed = []; + $warnings = []; + + foreach ($resolved['providers'] as $name => $provider) { + if (isset($resolved['warnings'][$name])) { + $warnings[] = $resolved['warnings'][$name]; + } + + try { + $mappings = $loader->loadFromPath( + $name, + $provider->installPath ?? throw new LogicException( + Message::PROVIDER_INSTALL_PATH_MISSING->getMessage($name), + ), + ); + } catch (Throwable $e) { + $failed[] = $name; + $warnings[] = Message::SCAFFOLD_MANIFEST_LOAD_FAILED->getMessage($name, $e->getMessage()); + + continue; + } + + MappingMerger::merge($merged, $mappings); + } + + return new self($merged, $failed, $warnings); + } + + /** + * Returns the allowed and installed providers whose manifest could not be loaded. + * + * @return list Provider names in `allowed-packages` order. + */ + public function failedProviders(): array + { + return $this->failedProviders; + } + + /** + * Returns whether the manifest of `$provider` could not be loaded. + * + * @param string $provider Provider package name. + * + * @return bool `true` when the provider manifest failed to load, `false` otherwise. + */ + public function hasFailed(string $provider): bool + { + return in_array($provider, $this->failedProviders, true); + } + + /** + * Returns the expected mapping of `$destination`, or `null` when no allowed and installed provider ships it. + * + * @param string $destination Destination path relative to the project root. + * + * @return FileMapping|null Expected mapping, or `null` when no allowed and installed provider ships it. + */ + public function mapping(string $destination): FileMapping|null + { + return $this->mappings[$destination] ?? null; + } + + /** + * Returns the stderr lines that announce the orphans of `$files`: a header with the count and the `prune` hint, + * at most ten destinations with their provider, and the number of the others. + * + * @param array> $files `files` map of `scaffold-lock.json`. + * + * @return list Lines prefixed with `[scaffold]`; empty when there is no orphan. + */ + public function orphanReport(array $files): array + { + $orphans = $this->orphans($files); + + $total = count($orphans); + + if ($total === 0) { + return []; + } + + $lines = [ + ConsoleMessage::SCAFFOLD_ORPHAN_HEADER->getMessage( + $total, + ConsoleMessage::plural($total, ConsoleMessage::FRAGMENT_FILE, ConsoleMessage::FRAGMENT_FILES), + ), + ]; + + foreach (array_slice($orphans, 0, self::ORPHAN_LIST_LIMIT, true) as $destination => $entry) { + $provider = $entry['provider'] ?? null; + + $lines[] = ConsoleMessage::SCAFFOLD_ORPHAN_ENTRY->getMessage( + (string) $destination, + is_string($provider) ? $provider : ConsoleMessage::FRAGMENT_UNKNOWN_PROVIDER->getMessage(), + ); + } + + if ($total > self::ORPHAN_LIST_LIMIT) { + $lines[] = ConsoleMessage::SCAFFOLD_ORPHAN_MORE->getMessage($total - self::ORPHAN_LIST_LIMIT); + } + + return $lines; + } + + /** + * Returns the lock entries that no allowed and installed provider ships anymore; ejected entries and entries of a + * provider whose manifest could not be loaded are never orphans. + * + * @template TEntry of array + * + * @param array $files `files` map of `scaffold-lock.json`. + * + * @return array Orphan entries keyed by destination, in lock order; integer-like destinations + * (`"123"`) are integer keys. + */ + public function orphans(array $files): array + { + $orphans = []; + + foreach ($files as $destination => $entry) { + // PHP turns integer-like destinations ("123") into integer array keys. + if (($entry['ejected'] ?? false) === true || $this->mapping((string) $destination) !== null) { + continue; + } + + $provider = $entry['provider'] ?? null; + + if (is_string($provider) && $this->hasFailed($provider)) { + continue; + } + + $orphans[$destination] = $files[$destination]; + } + + return $orphans; + } +} diff --git a/src/Scaffold/FileApplier.php b/src/Scaffold/FileApplier.php new file mode 100644 index 0000000..eed6e49 --- /dev/null +++ b/src/Scaffold/FileApplier.php @@ -0,0 +1,82 @@ +config->isAllowed($mapping->providerName)) { + throw new RuntimeException( + ExceptionMessage::PACKAGE_NOT_ALLOWED->getMessage($mapping->providerName), + ); + } + + $realRoot = $this->pathValidator->validateDestination($mapping->destination, $projectRoot); + $realProviderPath = $this->pathValidator->validateSource($mapping->source, $mapping->providerPath); + + $result = $mode->apply( + new FileMapping( + $mapping->destination, + $mapping->source, + $mapping->mode, + $mapping->providerName, + $realProviderPath, + $mapping->mergeStrategy, + ), + $realRoot, + $hashAtScaffold, + ); + + if ($result->warning !== null) { + $this->out->writeStderr( + Message::SCAFFOLD_PREFIXED->getMessage($result->warning), + ); + } + + return $result; + } +} diff --git a/src/Scaffold/Lock/Hasher.php b/src/Scaffold/Lock/Hasher.php index c75f651..e37f19d 100644 --- a/src/Scaffold/Lock/Hasher.php +++ b/src/Scaffold/Lock/Hasher.php @@ -4,28 +4,15 @@ namespace PHPForge\Scaffold\Scaffold\Lock; +use PHPForge\Scaffold\Exception\Message; +use PHPForge\Scaffold\Filesystem; use RuntimeException; -use function sprintf; - /** - * Computes and compares SHA-256 hashes for scaffold file tracking. + * Computes the `sha256:` hashes that `scaffold-lock.json` records for scaffolded files. */ final class Hasher { - /** - * Returns `true` when two hash strings are identical. - * - * @param string $a First hash string. - * @param string $b Second hash string. - * - * @return bool `true` if the hashes are identical, `false` otherwise. - */ - public function equals(string $a, string $b): bool - { - return $a === $b; - } - /** * Returns a `sha256:` hash of the file at the given path. * @@ -33,24 +20,10 @@ public function equals(string $a, string $b): bool * * @throws RuntimeException when the file cannot be read. * - * @return string Computed hash string in the format `sha256:`. + * @return string Hash in the format `sha256:`. */ - public function hash(string $absolutePath): string + public static function hash(string $absolutePath): string { - if (!is_file($absolutePath) || !is_readable($absolutePath)) { - throw new RuntimeException( - sprintf('Could not hash file "%s": file is unreadable or does not exist.', $absolutePath), - ); - } - - $result = hash_file('sha256', $absolutePath); - - if ($result === false) { - throw new RuntimeException( - sprintf('Could not hash file "%s": file is unreadable or does not exist.', $absolutePath), - ); - } - - return "sha256:{$result}"; + return 'sha256:' . Filesystem::hash($absolutePath, Message::LOCK_HASH_FAILED->getMessage($absolutePath)); } } diff --git a/src/Scaffold/Lock/LockFile.php b/src/Scaffold/Lock/LockFile.php index b0c663c..bd43570 100644 --- a/src/Scaffold/Lock/LockFile.php +++ b/src/Scaffold/Lock/LockFile.php @@ -4,51 +4,90 @@ namespace PHPForge\Scaffold\Scaffold\Lock; +use JsonException; +use PHPForge\Scaffold\Exception\Message; +use PHPForge\Scaffold\Filesystem; use RuntimeException; +use function array_diff_key; +use function array_flip; +use function array_key_exists; use function is_array; +use function is_file; use function is_string; +use function json_decode; +use function json_encode; +use function ksort; +use function preg_match; +use function rtrim; /** - * Reads and writes the `scaffold-lock.json` file that tracks applied file hashes. + * Reads and writes `scaffold-lock.json`, which records the provider and hashes of every scaffolded file. + * + * @phpstan-type LockEntry array{ + * hash: string, + * provider: string, + * source: string, + * mode: string, + * stub-hash?: string, + * merge?: string, + * ejected?: bool, + * adopted?: bool, + * } */ final class LockFile { + /** + * Entry keys that this class manages; {@see self::write()} carries other entry keys over from disk. + */ + private const array ENTRY_KEYS = [ + 'adopted', + 'ejected', + 'hash', + 'merge', + 'mode', + 'provider', + 'source', + 'stub-hash', + ]; + /** * @var array{ * providers: array, - * files: array, + * files: array, * }|null Cached lock data to avoid redundant file reads. Set to `null` when the cache is invalidated. */ private array|null $cache = null; + /** + * @var array> Entry keys outside {@see self::ENTRY_KEYS} found in the lock on disk, + * keyed by destination. + */ + private array $unknownEntryKeys = []; + /** + * @var array|null Top-level keys other than `providers` and `files` found in the lock on disk, or + * `null` when the lock has not been read yet. + */ + private array|null $unknownKeys = null; + /** + * @param string $projectRoot Absolute path to the project root that holds `scaffold-lock.json`. + */ public function __construct(private readonly string $projectRoot) {} /** * Returns `true` when `scaffold-lock.json` exists on disk. + * + * @return bool `true` when the lock file exists, `false` otherwise. */ public function exists(): bool { return is_file($this->getPath()); } - /** - * Returns the hash recorded at scaffold time for the given destination, or `null` if not tracked. - * - * @param string $destination Relative destination path as declared in the manifest. - */ - public function getHashAtScaffold(string $destination): string|null - { - $data = $this->read(); - - $entry = $data['files'][$destination] ?? null; - $hash = $entry['hash'] ?? null; - - return is_string($hash) ? $hash : null; - } - /** * Returns the absolute path to `scaffold-lock.json`. + * + * @return string Absolute path to the lock file under the project root. */ public function getPath(): string { @@ -58,12 +97,13 @@ public function getPath(): string /** * Reads and returns the lock data, or a default empty structure when the file does not exist. * - * @throws RuntimeException when the file exists but cannot be decoded as valid JSON. + * @throws RuntimeException when the file exists but cannot be read or decoded as a JSON object; the message names + * the file and the JSON error, and reports Git conflict markers when present. * * @return array{ * providers: array, - * files: array, - * } Lock data structure containing provider information and tracked file hashes. + * files: array, + * } Lock data; integer-like destinations (`"123"`) come back as integer `files` keys. */ public function read(): array { @@ -74,30 +114,59 @@ public function read(): array $path = $this->getPath(); if (!is_file($path)) { + $this->unknownKeys = []; + $this->unknownEntryKeys = []; $this->cache = ['providers' => [], 'files' => []]; return $this->cache; } - $content = file_get_contents($path); + $content = Filesystem::read($path, Message::LOCK_UNREADABLE->getMessage($path)); - if ($content === false) { - throw new RuntimeException(sprintf('Could not read lock file "%s".', $path)); + try { + $decoded = json_decode($content, associative: true, flags: JSON_THROW_ON_ERROR); + } catch (JsonException $e) { + throw new RuntimeException( + self::decodeErrorMessage($path, $content, $e), + 0, + $e, + ); } - $decoded = json_decode($content, associative: true, flags: JSON_THROW_ON_ERROR); - if (!is_array($decoded)) { - throw new RuntimeException(sprintf('Lock file "%s" does not contain a valid JSON object.', $path)); + throw new RuntimeException( + Message::LOCK_NOT_OBJECT->getMessage($path), + ); } $providers = is_array($decoded['providers'] ?? null) ? $decoded['providers'] : []; $files = is_array($decoded['files'] ?? null) ? $decoded['files'] : []; + $unknownKeys = []; + + foreach ($decoded as $key => $value) { + if (is_string($key) && $key !== 'providers' && $key !== 'files') { + $unknownKeys[$key] = $value; + } + } + + $this->unknownKeys = $unknownKeys; + $this->unknownEntryKeys = []; + + foreach ($files as $destination => $entry) { + if (is_array($entry)) { + $extra = array_diff_key($entry, array_flip(self::ENTRY_KEYS)); + + if ($extra !== []) { + $this->unknownEntryKeys[(string) $destination] = $extra; + } + } + } + /** * @var array{ * providers: array, - * files: array, + * files: array, * } $normalized */ $normalized = ['providers' => $providers, 'files' => $files]; @@ -107,28 +176,99 @@ public function read(): array } /** - * Writes lock data to `scaffold-lock.json` with stable JSON formatting. + * Writes lock data atomically with `providers` and `files` as objects sorted by key, carrying over unknown + * top-level keys and the unknown keys of entries still present in `$data`. * * @param array $data Lock data to persist. * - * @throws RuntimeException when the file cannot be written. + * @throws RuntimeException when the data cannot be encoded, the existing lock cannot be read, or the file cannot + * be written. */ public function write(array $data): void { + if ($this->unknownKeys === null) { + // Load the keys to preserve from the lock on disk before replacing it. + $this->read(); + } + $this->cache = null; $path = $this->getPath(); - $json = json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR); + $files = $data['files'] ?? []; + + if (is_array($files)) { + foreach ($this->unknownEntryKeys as $destination => $extra) { + if (is_array($files[$destination] ?? null)) { + $files[$destination] += $extra; + } + } + } - $tmp = "{$path}.tmp"; + $payload = [ + 'providers' => self::sortedMap($data['providers'] ?? []), + 'files' => self::sortedMap($files), + ]; - if (file_put_contents($tmp, $json, LOCK_EX) === false || !rename($tmp, $path)) { - if (is_file($tmp)) { - unlink($tmp); + foreach ($data as $key => $value) { + if ($key !== 'providers' && $key !== 'files') { + $payload[$key] = $value; } + } - throw new RuntimeException(sprintf('Could not write lock file "%s".', $path)); + foreach ($this->unknownKeys ?? [] as $key => $value) { + if (!array_key_exists($key, $payload)) { + $payload[$key] = $value; + } } + + try { + $json = json_encode($payload, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR) . "\n"; + } catch (JsonException $e) { + throw new RuntimeException( + Message::LOCK_ENCODE_FAILED->getMessage($path, $e->getMessage()), + 0, + $e, + ); + } + + Filesystem::writeAtomic($path, $json, Message::LOCK_UNWRITABLE->getMessage($path)); + } + + /** + * Builds the error message for a lock file that is not valid JSON, pointing out Git conflict markers when present. + * + * @param string $path Absolute path to the lock file. + * @param string $content Raw content of the lock file. + * @param JsonException $error Decoding error raised for the content. + * + * @return string Error message that names the file and the JSON error. + */ + private static function decodeErrorMessage(string $path, string $content, JsonException $error): string + { + if (preg_match('/^(?:<{7}|={7}|>{7})/m', $content) === 1) { + return Message::LOCK_CONFLICT_MARKERS->getMessage($path, $error->getMessage()); + } + + return Message::LOCK_INVALID_JSON->getMessage($path, $error->getMessage()); + } + + /** + * Returns `$map` sorted by key in byte order as an object, so empty maps encode as `{}` and integer-like keys never + * turn the map into a JSON list. + * + * @param mixed $map Map to normalise; values that are not arrays are returned unchanged. + * + * @return mixed Key-sorted object for an array, or `$map` unchanged otherwise. + */ + private static function sortedMap(mixed $map): mixed + { + if (!is_array($map)) { + return $map; + } + + ksort($map, SORT_STRING); + + return (object) $map; } } diff --git a/src/Scaffold/MappingMerger.php b/src/Scaffold/MappingMerger.php new file mode 100644 index 0000000..9557907 --- /dev/null +++ b/src/Scaffold/MappingMerger.php @@ -0,0 +1,40 @@ + $merged Mappings keyed by destination, updated in place; integer-like + * destinations (`"123"`) become integer keys. + * @param list $mappings Mappings of the next provider, in manifest order. + * + * @return list Overrides across providers, as pairs of the new mapping and the + * mapping it replaced. + */ + public static function merge(array &$merged, array $mappings): array + { + $overrides = []; + + foreach ($mappings as $mapping) { + $previous = $merged[$mapping->destination] ?? null; + + if ($previous !== null && $previous->providerName !== $mapping->providerName) { + $overrides[] = [$mapping, $previous]; + } + + $merged[$mapping->destination] = $mapping; + } + + return $overrides; + } +} diff --git a/src/Scaffold/Modes/AppendMode.php b/src/Scaffold/Modes/AppendMode.php index 2d8aeeb..f365dd9 100644 --- a/src/Scaffold/Modes/AppendMode.php +++ b/src/Scaffold/Modes/AppendMode.php @@ -4,240 +4,62 @@ namespace PHPForge\Scaffold\Scaffold\Modes; +use PHPForge\Scaffold\Exception\Message; +use PHPForge\Scaffold\Filesystem; use PHPForge\Scaffold\Manifest\FileMapping; +use PHPForge\Scaffold\Merge\StrategyResolver; use PHPForge\Scaffold\Scaffold\Lock\Hasher; use PHPForge\Scaffold\Scaffold\PathResolver; use RuntimeException; -use SebastianBergmann\Diff\Differ; -use SebastianBergmann\Diff\Output\DiffOnlyOutputBuilder; - -use function array_column; -use function array_count_values; -use function count; -use function explode; -use function implode; -use function preg_replace; -use function sprintf; -use function str_contains; -use function str_ends_with; -use function substr; /** - * Applies a scaffold file by line-merging its content into the destination, or writing it fresh. - * - * Idempotent by design: when the destination already exists, provider lines missing from it are inserted at their - * contextual position relative to shared anchor lines (LCS alignment). Presence is decided by order-independent line - * counting, so a destination holding every provider line in a different order is left untouched. Existing lines keep - * their original terminators (mixed EOLs included) while inserted lines use the destination's dominant EOL. Repeated - * applications produce no duplication, and consumer-specific additions are never removed or reordered. + * Applies a file by merging the provider entries that the destination lacks, or by writing the source when the + * destination is missing. */ final class AppendMode implements ModeInterface { + /** + * Merges the source into the destination with the mapping's merge strategy, or the default strategy for the + * destination name, and writes only when the content changes. + * + * @param FileMapping $mapping File mapping to apply. + * @param string $projectRoot Absolute path to the project root. + * @param string|null $hashAtScaffold Hash recorded in the lock file, or `null` when the destination is untracked; + * this mode ignores it. + * + * @throws RuntimeException when a file cannot be read, written or hashed, or a directory cannot be created. + * + * @return ApplyResult `Written` with the new hash when the destination is missing or the merge changes it, + * `Skipped` with the current hash otherwise. + */ public function apply( FileMapping $mapping, string $projectRoot, - Hasher $hasher, string|null $hashAtScaffold, ): ApplyResult { $destination = PathResolver::destination($projectRoot, $mapping->destination); $source = PathResolver::source($mapping->providerPath, $mapping->source); + $providerContent = Filesystem::read($source, Message::MODE_SOURCE_UNREADABLE->getMessage($source)); - $providerContent = file_get_contents($source); - - if ($providerContent === false) { - throw new RuntimeException(sprintf('Could not read source file "%s".', $source)); - } - - PathResolver::ensureDirectory($destination); - - if (!file_exists($destination)) { - if (file_put_contents($destination, $providerContent) === false) { - throw new RuntimeException(sprintf('Could not write to "%s".', $destination)); - } - - return new ApplyResult(ApplyOutcome::Written, $hasher->hash($destination), null); - } - - $consumerContent = file_get_contents($destination); - - if ($consumerContent === false) { - throw new RuntimeException(sprintf('Could not read destination file "%s".', $destination)); - } - - // Dominant EOL style is used for inserted provider lines only; existing lines keep their own terminators. - $eol = self::detectEol($consumerContent); - - // Normalise the provider only: consumer lines are split with their raw terminators preserved, and the diff - // compares terminator-free texts, so CRLF/CR destinations still diff identically against an LF stub. - $providerContent = (string) preg_replace('/\r\n|\r/', "\n", $providerContent); - - $segments = self::splitRawSegments($consumerContent); - $consumerLines = array_column($segments, 0); - $providerLines = self::splitLines($providerContent); + $exists = file_exists($destination); - // Count-based multiset decides WHAT is missing (order-independent, multiplicity-preserving): a provider line - // is missing only when the destination holds fewer copies of it, so reordered destinations never duplicate. - $consumerCounts = array_count_values($consumerLines); - $missingCounts = []; + $consumerContent = $exists + ? Filesystem::read($destination, Message::MODE_DESTINATION_UNREADABLE->getMessage($destination)) + : ''; - foreach ($providerLines as $line) { - if (isset($consumerCounts[$line]) && $consumerCounts[$line] > 0) { - $consumerCounts[$line]--; + $strategy = $mapping->mergeStrategy !== null + ? StrategyResolver::forKind($mapping->mergeStrategy) + : StrategyResolver::for($mapping->destination); - continue; - } - - $missingCounts[$line] = ($missingCounts[$line] ?? 0) + 1; - } - - if ($missingCounts === []) { - return new ApplyResult(ApplyOutcome::Skipped, $hasher->hash($destination), null); - } - - $differ = new Differ(new DiffOnlyOutputBuilder('')); - - /** @var list $entries */ - $entries = $differ->diffToArray($providerLines, $consumerLines); - - // LCS alignment decides WHERE missing lines land: provider-only entries ('REMOVED') buffer until the next - // shared anchor ('OLD'), recording the insertion point as "before consumer segment N", while consumer-only - // lines ('ADDED') stay in place ahead of them. 'REMOVED' entries with no remaining missing quota are reorder - // artifacts: the same line exists elsewhere in the destination, so they are dropped instead of duplicated. - $pending = []; - $insertions = []; - $consumerIndex = 0; - - foreach ($entries as [$line, $type]) { - if ($type === Differ::REMOVED) { - if (isset($missingCounts[$line]) && $missingCounts[$line] > 0) { - $missingCounts[$line]--; - $pending[] = $line; - } - - continue; - } - - if ($type === Differ::OLD && $pending !== []) { - $insertions[$consumerIndex] = $pending; - $pending = []; - } - - $consumerIndex++; - } - - // Consumer segments are re-emitted verbatim (text plus original terminator) so existing line endings are - // never rewritten; only inserted provider lines use the dominant EOL. - $output = ''; - - foreach ($segments as $index => [$text, $segmentEol]) { - if (isset($insertions[$index])) { - $output .= implode($eol, $insertions[$index]) . $eol; - } - - $output .= $text . $segmentEol; - } - - if ($pending !== []) { - $separator = $output === '' || str_ends_with($output, "\n") || str_ends_with($output, "\r") ? '' : $eol; - $output .= $separator . implode($eol, $pending) . $eol; - } + $result = $strategy->merge($providerContent, $consumerContent); - if (file_put_contents($destination, $output) === false) { - throw new RuntimeException(sprintf('Could not write to "%s".', $destination)); + if ($exists && !$result->changed) { + return new ApplyResult(ApplyOutcome::Skipped, Hasher::hash($destination), null); } - return new ApplyResult(ApplyOutcome::Written, $hasher->hash($destination), null); - } - - /** - * Detects the dominant end-of-line sequence used by `$content`. - * - * Returns `"\r\n"` for Windows-style content, `"\r"` for legacy Mac-style content, and `"\n"` otherwise (Unix or - * empty). The result is used to emit inserted provider lines in the destination's dominant EOL style; existing - * lines keep their own terminators. - * - * @param string $content Original (un-normalised) destination content. - * - * @return string The detected EOL sequence. - */ - private static function detectEol(string $content): string - { - if (str_contains($content, "\r\n")) { - return "\r\n"; - } - - if (str_contains($content, "\r")) { - return "\r"; - } - - return "\n"; - } - - /** - * Splits a normalised text into its constituent lines, stripping at most one trailing newline. - * - * Stripping only the final EOL marker (not every trailing newline) preserves any intentional blank lines at the - * end of the file. Otherwise repeated runs would re-detect the trailing blank as missing on every full scaffold, - * defeating idempotency. - * - * @param string $content Normalised text whose lines must be extracted. - * - * @return list Ordered list of lines, never including a synthetic trailing empty entry from the final EOL. - */ - private static function splitLines(string $content): array - { - if ($content === '') { - return []; - } - - if (str_ends_with($content, "\n")) { - $content = substr($content, 0, -1); - } - - return explode("\n", $content); - } - - /** - * Splits raw destination content into `[text, terminator]` segments, preserving each line's original EOL bytes. - * - * Recognises `"\r\n"`, `"\r"`, and `"\n"` terminators so the produced texts align one-to-one with the normalised - * provider lines used for diffing, while re-emission keeps mixed line endings byte-identical. Built on `explode`, - * which always returns `array`, avoiding the defensive false-branch `preg_split` would have produced. - * - * @param string $content Raw (un-normalised) destination content. - * - * @return list Ordered `[text, terminator]` pairs; the final terminator is empty when the - * content does not end with a newline. - */ - private static function splitRawSegments(string $content): array - { - $segments = []; - - $chunks = explode("\n", $content); - $lastChunk = count($chunks) - 1; - - foreach ($chunks as $index => $chunk) { - $chunkEol = $index < $lastChunk ? "\n" : ''; - - if ($chunkEol === "\n" && str_ends_with($chunk, "\r")) { - $chunk = substr($chunk, 0, -1); - $chunkEol = "\r\n"; - } - - // Legacy Mac CR terminators inside the chunk produce their own segments; the final piece takes the chunk - // terminator, except for the synthetic empty piece a trailing terminator leaves behind. - $pieces = explode("\r", $chunk); - $lastPiece = count($pieces) - 1; - - foreach ($pieces as $pieceIndex => $piece) { - if ($pieceIndex < $lastPiece) { - $segments[] = [$piece, "\r"]; - } elseif ($piece !== '' || $chunkEol !== '') { - $segments[] = [$piece, $chunkEol]; - } - } - } + PathResolver::ensureDirectory($destination); + Filesystem::write($destination, $result->content, Message::MODE_WRITE_FAILED->getMessage($destination)); - return $segments; + return new ApplyResult(ApplyOutcome::Written, Hasher::hash($destination), null); } } diff --git a/src/Scaffold/Modes/ApplyOutcome.php b/src/Scaffold/Modes/ApplyOutcome.php index 1d72401..5ee4aaf 100644 --- a/src/Scaffold/Modes/ApplyOutcome.php +++ b/src/Scaffold/Modes/ApplyOutcome.php @@ -5,17 +5,17 @@ namespace PHPForge\Scaffold\Scaffold\Modes; /** - * Enumerates the possible outcomes after applying a scaffold file mapping. + * Represents the outcome of applying a file mapping. */ enum ApplyOutcome { /** - * File was skipped either preserved or user-modified. + * The destination was left unchanged. */ case Skipped; /** - * File was written or overwritten successfully. + * The destination was created or rewritten. */ case Written; } diff --git a/src/Scaffold/Modes/ApplyResult.php b/src/Scaffold/Modes/ApplyResult.php index 46c3487..f4cd08b 100644 --- a/src/Scaffold/Modes/ApplyResult.php +++ b/src/Scaffold/Modes/ApplyResult.php @@ -5,10 +5,16 @@ namespace PHPForge\Scaffold\Scaffold\Modes; /** - * Represents the outcome of applying a single scaffold file mapping. + * Represents the result of applying a file mapping: its outcome, the destination hash and an optional warning. */ final readonly class ApplyResult { + /** + * @param ApplyOutcome $outcome Whether the destination was written or left unchanged. + * @param string $newHash Hash of the destination after the operation, or an empty string when a user-modified + * destination was skipped. + * @param string|null $warning Message for the user, or `null` when there is nothing to report. + */ public function __construct( public ApplyOutcome $outcome, public string $newHash, diff --git a/src/Scaffold/Modes/ModeInterface.php b/src/Scaffold/Modes/ModeInterface.php index 51b5af5..c440eaa 100644 --- a/src/Scaffold/Modes/ModeInterface.php +++ b/src/Scaffold/Modes/ModeInterface.php @@ -5,30 +5,27 @@ namespace PHPForge\Scaffold\Scaffold\Modes; use PHPForge\Scaffold\Manifest\FileMapping; -use PHPForge\Scaffold\Scaffold\Lock\Hasher; use RuntimeException; /** - * Contract for all scaffold file-application strategies. + * Defines how a write mode applies a file mapping to the project. */ interface ModeInterface { /** - * Applies a file mapping to the project root and returns the result. + * Applies a file mapping to the project and returns the outcome, the destination hash and an optional warning. * * @param FileMapping $mapping File mapping to apply. * @param string $projectRoot Absolute path to the project root. - * @param Hasher $hasher Hash utility for computing and comparing file hashes. - * @param string|null $hashAtScaffold Hash recorded in the lock file at last scaffold time, or `null` if untracked. + * @param string|null $hashAtScaffold Hash recorded in the lock file, or `null` when the destination is untracked. * - * @throws RuntimeException when the source file cannot be read or the destination cannot be written. + * @throws RuntimeException when a file cannot be read, written or hashed, or a directory cannot be created. * - * @return ApplyResult Result of the apply operation, including the outcome, new hash, and any warning message. + * @return ApplyResult Outcome, destination hash and optional warning of the operation. */ public function apply( FileMapping $mapping, string $projectRoot, - Hasher $hasher, string|null $hashAtScaffold, ): ApplyResult; } diff --git a/src/Scaffold/Modes/PrependMode.php b/src/Scaffold/Modes/PrependMode.php index 8071de0..ca1a7ff 100644 --- a/src/Scaffold/Modes/PrependMode.php +++ b/src/Scaffold/Modes/PrependMode.php @@ -4,51 +4,113 @@ namespace PHPForge\Scaffold\Scaffold\Modes; +use PHPForge\Scaffold\Exception\Message; +use PHPForge\Scaffold\Filesystem; use PHPForge\Scaffold\Manifest\FileMapping; +use PHPForge\Scaffold\Merge\Lines; use PHPForge\Scaffold\Scaffold\Lock\Hasher; use PHPForge\Scaffold\Scaffold\PathResolver; use RuntimeException; -use function sprintf; +use function array_keys; +use function array_slice; +use function count; +use function implode; /** - * Applies a scaffold file by prepending its content before an existing destination, or writing it fresh. + * Applies a file by prepending the source block unless the destination already contains it. */ final class PrependMode implements ModeInterface { + /** + * Prepends the source block, terminated with the destination end-of-line sequence, when the destination lacks it + * as a contiguous run of lines. + * + * @param FileMapping $mapping File mapping to apply. + * @param string $projectRoot Absolute path to the project root. + * @param string|null $hashAtScaffold Hash recorded in the lock file, or `null` when the destination is untracked; + * this mode ignores it. + * + * @throws RuntimeException when a file cannot be read, written or hashed, or a directory cannot be created. + * + * @return ApplyResult `Written` with the new hash when the block is prepended, `Skipped` with the current hash + * when the destination already contains it. + */ public function apply( FileMapping $mapping, string $projectRoot, - Hasher $hasher, string|null $hashAtScaffold, ): ApplyResult { $destination = PathResolver::destination($projectRoot, $mapping->destination); $source = PathResolver::source($mapping->providerPath, $mapping->source); + $sourceContent = Filesystem::read($source, Message::MODE_SOURCE_UNREADABLE->getMessage($source)); - $sourceContent = file_get_contents($source); + $existing = file_exists($destination) + ? Filesystem::read($destination, Message::MODE_DESTINATION_UNREADABLE->getMessage($destination)) + : null; - if ($sourceContent === false) { - throw new RuntimeException(sprintf('Could not read source file "%s".', $source)); + $content = self::prepend($sourceContent, $existing); + + if ($content === null) { + return new ApplyResult(ApplyOutcome::Skipped, Hasher::hash($destination), null); } - if (file_exists($destination)) { - $existing = file_get_contents($destination); + PathResolver::ensureDirectory($destination); + + Filesystem::write($destination, $content, Message::MODE_WRITE_FAILED->getMessage($destination)); - if ($existing === false) { - throw new RuntimeException(sprintf('Could not read destination file "%s".', $destination)); - } + return new ApplyResult(ApplyOutcome::Written, Hasher::hash($destination), null); + } - $combined = $sourceContent . $existing; - } else { - $combined = $sourceContent; + /** + * Returns the destination content after prepending the source block, terminated with the destination end-of-line + * sequence, or `null` when the destination already contains the block as a contiguous run of lines. + * + * @param string $source Provider content. + * @param string|null $existing Destination content, or `null` when the destination does not exist. + * + * @return string|null Content to write, or `null` when the destination already contains the block. + */ + public static function prepend(string $source, string|null $existing): string|null + { + if ($existing === null) { + return $source; } - PathResolver::ensureDirectory($destination); + $block = Lines::split(Lines::normalise($source)); + + if ($block === [] || self::containsBlock(Lines::split(Lines::normalise($existing)), $block)) { + return null; + } - if (file_put_contents($destination, $combined) === false) { - throw new RuntimeException(sprintf('Could not write to "%s".', $destination)); + if ($existing === '') { + return $source; + } + + $eol = Lines::detectEol($existing); + + return implode($eol, $block) . $eol . $existing; + } + + /** + * Returns whether the block occurs in the lines as a contiguous run. + * + * @param list $lines Destination lines. + * @param non-empty-list $block Provider lines. + * + * @return bool `true` when the block occurs as a contiguous run of lines, `false` otherwise. + */ + private static function containsBlock(array $lines, array $block): bool + { + $size = count($block); + + // A run that starts too close to the end is shorter than the block, so it never matches. + foreach (array_keys($lines) as $offset) { + if (array_slice($lines, $offset, $size) === $block) { + return true; + } } - return new ApplyResult(ApplyOutcome::Written, $hasher->hash($destination), null); + return false; } } diff --git a/src/Scaffold/Modes/PreserveMode.php b/src/Scaffold/Modes/PreserveMode.php index bf69129..851268c 100644 --- a/src/Scaffold/Modes/PreserveMode.php +++ b/src/Scaffold/Modes/PreserveMode.php @@ -4,45 +4,51 @@ namespace PHPForge\Scaffold\Scaffold\Modes; +use PHPForge\Scaffold\Exception\Message; +use PHPForge\Scaffold\Filesystem; use PHPForge\Scaffold\Manifest\FileMapping; use PHPForge\Scaffold\Scaffold\Lock\Hasher; use PHPForge\Scaffold\Scaffold\PathResolver; use RuntimeException; -use function sprintf; - /** - * Applies a scaffold file only when the destination does not already exist. - * - * If the destination exists it is never overwritten; the existing hash is returned so the lock file can record the - * current state. + * Applies a file only when the destination does not exist. */ final class PreserveMode implements ModeInterface { + /** + * Copies the source when the destination is missing; otherwise returns `Skipped` with the current hash. + * + * @param FileMapping $mapping File mapping to apply. + * @param string $projectRoot Absolute path to the project root. + * @param string|null $hashAtScaffold Hash recorded in the lock file, or `null` when the destination is untracked; + * this mode ignores it. + * + * @throws RuntimeException when a file cannot be read, written or hashed, or a directory cannot be created. + * + * @return ApplyResult `Written` with the new hash and any permission warning when the destination is missing, + * `Skipped` with the current hash otherwise. + */ public function apply( FileMapping $mapping, string $projectRoot, - Hasher $hasher, string|null $hashAtScaffold, ): ApplyResult { $destination = PathResolver::destination($projectRoot, $mapping->destination); if (file_exists($destination)) { - return new ApplyResult(ApplyOutcome::Skipped, $hasher->hash($destination), null); + return new ApplyResult(ApplyOutcome::Skipped, Hasher::hash($destination), null); } $source = PathResolver::source($mapping->providerPath, $mapping->source); PathResolver::ensureDirectory($destination); + Filesystem::copy($source, $destination, Message::MODE_COPY_FAILED->getMessage($source, $destination)); - if (copy($source, $destination) === false) { - throw new RuntimeException( - sprintf('Could not copy "%s" to "%s".', $source, $destination), - ); - } - - PathResolver::syncPermissions($source, $destination); - - return new ApplyResult(ApplyOutcome::Written, $hasher->hash($destination), null); + return new ApplyResult( + ApplyOutcome::Written, + Hasher::hash($destination), + PathResolver::syncPermissions($source, $destination), + ); } } diff --git a/src/Scaffold/Modes/ReplaceMode.php b/src/Scaffold/Modes/ReplaceMode.php index ad15c02..b3f146e 100644 --- a/src/Scaffold/Modes/ReplaceMode.php +++ b/src/Scaffold/Modes/ReplaceMode.php @@ -4,52 +4,67 @@ namespace PHPForge\Scaffold\Scaffold\Modes; +use PHPForge\Scaffold\Console\Message as ConsoleMessage; +use PHPForge\Scaffold\Exception\Message; +use PHPForge\Scaffold\Filesystem; use PHPForge\Scaffold\Manifest\FileMapping; use PHPForge\Scaffold\Scaffold\Lock\Hasher; use PHPForge\Scaffold\Scaffold\PathResolver; use RuntimeException; -use function sprintf; - /** - * Applies a scaffold file by overwriting the destination, unless the user has modified it. - * - * When a lock hash exists and the current file hash differs, the file is considered user-modified and the write is - * skipped with a warning. When no lock hash exists, or hashes match, the source is copied unconditionally. + * Applies a file by overwriting the destination unless it changed since its recorded hash. */ final class ReplaceMode implements ModeInterface { + /** + * Copies the source over the destination, skipping a destination whose hash differs from the recorded one and + * warning when it overwrites an untracked destination with different content. + * + * @param FileMapping $mapping File mapping to apply. + * @param string $projectRoot Absolute path to the project root. + * @param string|null $hashAtScaffold Hash recorded in the lock file, or `null` when the destination is untracked. + * + * @throws RuntimeException when a file cannot be read, written or hashed, or a directory cannot be created. + * + * @return ApplyResult `Written` with the new hash and any warning, or `Skipped` with an empty hash and a warning + * when the destination is user-modified. + */ public function apply( FileMapping $mapping, string $projectRoot, - Hasher $hasher, string|null $hashAtScaffold, ): ApplyResult { $destination = PathResolver::destination($projectRoot, $mapping->destination); $source = PathResolver::source($mapping->providerPath, $mapping->source); - if (file_exists($destination) && $hashAtScaffold !== null) { - $currentHash = $hasher->hash($destination); + $warning = null; + + if (file_exists($destination)) { + $currentHash = Hasher::hash($destination); - if (!$hasher->equals($currentHash, $hashAtScaffold)) { + if ($hashAtScaffold !== null && $currentHash !== $hashAtScaffold) { return new ApplyResult( ApplyOutcome::Skipped, '', - sprintf('User-modified file skipped: "%s".', $mapping->destination), + ConsoleMessage::SCAFFOLD_USER_MODIFIED_SKIPPED->getMessage($mapping->destination), ); } + + if ($hashAtScaffold === null && $currentHash !== Hasher::hash($source)) { + $warning = ConsoleMessage::SCAFFOLD_UNTRACKED_OVERWRITTEN->getMessage($mapping->destination); + } } PathResolver::ensureDirectory($destination); + Filesystem::copy($source, $destination, Message::MODE_COPY_FAILED->getMessage($source, $destination)); - if (copy($source, $destination) === false) { - throw new RuntimeException( - sprintf('Could not copy "%s" to "%s".', $source, $destination), - ); - } + $permissionWarning = PathResolver::syncPermissions($source, $destination); - PathResolver::syncPermissions($source, $destination); + if ($permissionWarning !== null) { + $warning = $warning === null ? $permissionWarning : "{$warning} {$permissionWarning}"; + } - return new ApplyResult(ApplyOutcome::Written, $hasher->hash($destination), null); + return new ApplyResult(ApplyOutcome::Written, Hasher::hash($destination), $warning); } } diff --git a/src/Scaffold/PathResolver.php b/src/Scaffold/PathResolver.php index 5558b5b..f7705dd 100644 --- a/src/Scaffold/PathResolver.php +++ b/src/Scaffold/PathResolver.php @@ -4,27 +4,26 @@ namespace PHPForge\Scaffold\Scaffold; +use PHPForge\Scaffold\Console\Message as ConsoleMessage; +use PHPForge\Scaffold\Exception\Message; +use PHPForge\Scaffold\Filesystem; +use PHPForge\Scaffold\Security\PathValidator; use RuntimeException; -use function chmod; use function dirname; -use function fileperms; use function is_array; +use function is_dir; use function is_string; use function ltrim; -use function preg_match; use function realpath; use function rtrim; -use function sprintf; use function str_replace; use function str_starts_with; -use function umask; +use function stripos; /** - * Resolves absolute scaffold paths from base roots and relative segments. - * - * Centralizes path joining, directory creation, and provider-root resolution used by mode strategies and console - * controllers. Callers remain responsible for validating the relative segments with {@see PathValidator} beforehand. + * Resolves absolute scaffold paths from roots and relative segments that callers have already validated with + * {@see \PHPForge\Scaffold\Security\PathValidator}. */ final class PathResolver { @@ -45,14 +44,16 @@ public static function destination(string $projectRoot, string $destination): st /** * Creates the parent directory for the given absolute file path when it does not exist. * + * @param string $absoluteFilePath Absolute path to the file whose parent directory is created. + * * @throws RuntimeException when the directory cannot be created. */ public static function ensureDirectory(string $absoluteFilePath): void { $dir = dirname($absoluteFilePath); - if (!is_dir($dir) && mkdir($dir, 0o777, recursive: true) === false && !is_dir($dir)) { - throw new RuntimeException(sprintf('Could not create directory "%s".', $dir)); + if (!is_dir($dir)) { + Filesystem::mkdir($dir, Message::PATH_DIRECTORY_CREATE_FAILED->getMessage($dir)); } } @@ -71,20 +72,17 @@ public static function realpathOrFallback(string $path): string } /** - * Resolves the absolute root of a provider package, honoring the lock-recorded path when it stays inside the vendor - * directory. - * - * Accepts both relative paths (resolved against `$projectRoot`) and legacy absolute paths written by earlier plugin - * versions. + * Resolves the absolute root of a provider from its lock-recorded path when that path, relative or absolute, stays + * inside the vendor directory, falling back to `/`. * * @param string $vendorDir Absolute path to the Composer vendor directory. - * @param string $providerName Provider package name (for example, `php-forge/baseline`). - * @param mixed $providerLock Decoded `providers.` entry from `scaffold-lock.json`, when present. - * @param string $projectRoot Absolute path to the project root; required to expand relative lock paths. Pass an - * empty string only when the caller knows that lock-recorded paths are absolute (legacy). + * @param string $providerName Composer package name of the provider, used for the fallback root. + * @param mixed $providerLock Decoded `providers.` entry of `scaffold-lock.json`, or `null` when absent. + * @param string $projectRoot Absolute path to the project root that relative recorded paths are joined to; an empty + * string leaves them unexpanded. * - * @return array{root: string, warning: string|null} An array containing the resolved provider root and an optional - * warning message when the lock-recorded path is invalid. + * @return array{root: string, warning: string|null} Provider root, and a warning when the recorded path resolves + * outside the vendor directory. */ public static function resolveProviderRoot( string $vendorDir, @@ -97,79 +95,91 @@ public static function resolveProviderRoot( $defaultRoot = $safeVendorDir . DIRECTORY_SEPARATOR . $providerName; if (!is_array($providerLock) || !is_string($providerLock['path'] ?? null)) { - return ['root' => $defaultRoot, 'warning' => null]; + return [ + 'root' => $defaultRoot, + 'warning' => null, + ]; } $recordedPath = $providerLock['path']; - $isAbsolute = str_starts_with($recordedPath, '/') - || str_starts_with($recordedPath, '\\') - || preg_match('/^[A-Za-z]:/', $recordedPath) === 1; - $expanded = $isAbsolute || $projectRoot === '' + $expanded = PathValidator::isAbsolute($recordedPath) || $projectRoot === '' ? $recordedPath : rtrim($projectRoot, '/\\') . DIRECTORY_SEPARATOR . $recordedPath; $candidate = self::realpathOrFallback($expanded); - if (str_starts_with($candidate . DIRECTORY_SEPARATOR, $safeVendorDir . DIRECTORY_SEPARATOR)) { - return ['root' => $candidate, 'warning' => null]; + if (self::isWithin($candidate, $safeVendorDir, DIRECTORY_SEPARATOR === '\\')) { + return [ + 'root' => $candidate, + 'warning' => null, + ]; } return [ 'root' => $defaultRoot, - 'warning' => sprintf( - '[scaffold] Provider root for "%s" resolves outside vendor dir; using default path.', - $providerName, - ), + 'warning' => ConsoleMessage::SCAFFOLD_PROVIDER_ROOT_OUTSIDE_VENDOR->getMessage($providerName), ]; } /** - * Joins a provider root with a relative source path using the platform separator. - * - * Forward slashes inside `$source` are normalized to the platform separator. + * Joins a provider root with a relative source path. * * @param string $providerPath Absolute path to the provider root directory. * @param string $source Relative path to a source file or directory inside the provider, using forward slashes as * separators. * - * @return string Absolute path to the source file or directory inside the provider, with platform separators. + * @return string Absolute path to the source file or directory inside the provider. */ public static function source(string $providerPath, string $source): string { - $relative = ltrim($source, '/\\'); - - // Windows-only normalisation: str_replace is a no-op on POSIX (separator is '/'). - // @codeCoverageIgnoreStart - $relative = str_replace('/', DIRECTORY_SEPARATOR, $relative); - // @codeCoverageIgnoreEnd - - return rtrim($providerPath, '/\\') . DIRECTORY_SEPARATOR . $relative; + return rtrim($providerPath, '/\\') . DIRECTORY_SEPARATOR . ltrim($source, '/\\'); } /** - * Copies the source file's permission bits onto the destination, preserving the executable bit for CLI stubs - * such as `yii` or shell scripts, while honoring the caller's `umask` so restrictive setups (for example, `0077` - * on shared hosts or CI) are not silently widened. - * - * On POSIX systems, PHP's `copy()` and `file_put_contents()` honor the current umask rather than the source's - * permissions, which silently drops the executable bit. This helper brings the destination back in line with the - * source, masked by the current umask. Failures are swallowed because permission changes are best-effort on - * Windows and restricted mounts. + * Copies the source permission bits, masked by the current `umask`, onto the destination so executable stubs stay + * executable, and reports a failure instead of raising a PHP warning. * * @param string $source Absolute path to the source file. * @param string $destination Absolute path to the destination file. + * + * @return string|null Warning without the `[scaffold]` prefix when the permissions could not be read or set, or + * `null` on success. */ - public static function syncPermissions(string $source, string $destination): void + public static function syncPermissions(string $source, string $destination): string|null { - $perms = @fileperms($source); - - if ($perms === false) { - return; + try { + Filesystem::copyPermissions( + $source, + $destination, + ConsoleMessage::SCAFFOLD_PERMISSIONS_COPY_FAILED->getMessage($source, $destination), + ); + } catch (RuntimeException $e) { + return $e->getMessage(); } - $currentUmask = umask(); + return null; + } + + /** + * Returns whether `$path` is `$directory` or lies inside it, treating `/` and `\` as the same separator and + * ignoring case when `$caseInsensitive` is `true`. + * + * A path that `realpath()` could not resolve keeps the separators it was joined with, so on Windows it can mix both. + * + * @param string $path Absolute path to check. + * @param string $directory Absolute path of the containing directory. + * @param bool $caseInsensitive Whether to compare ignoring case, as Windows filesystems do. + * + * @return bool `true` when `$path` is `$directory` or one of its descendants, `false` otherwise. + */ + private static function isWithin(string $path, string $directory, bool $caseInsensitive): bool + { + $normalizedPath = str_replace('\\', '/', $path) . '/'; + $normalizedDirectory = str_replace('\\', '/', $directory) . '/'; - @chmod($destination, $perms & 0o777 & ~$currentUmask); + return $caseInsensitive + ? stripos($normalizedPath, $normalizedDirectory) === 0 + : str_starts_with($normalizedPath, $normalizedDirectory); } } diff --git a/src/Scaffold/ScaffoldRunner.php b/src/Scaffold/ScaffoldRunner.php new file mode 100644 index 0000000..35ed413 --- /dev/null +++ b/src/Scaffold/ScaffoldRunner.php @@ -0,0 +1,451 @@ + Mode implementations keyed by the backing value of {@see FileMode}. + */ + private array $modes; + + /** + * @param ManifestLoader $loader Loads provider manifests into file mappings. + * @param FileApplier $applier Validates and applies each mapping. + * @param LockFile $lockFile Lock file of the project. + * @param OutputWriter $out Output sink: notices on stdout, warnings and errors on stderr. + * @param ScaffoldSummary $summary Counters that the runs of this runner update. + */ + public function __construct( + private ManifestLoader $loader, + private FileApplier $applier, + private LockFile $lockFile, + private OutputWriter $out, + private ScaffoldSummary $summary, + ) { + $this->modes = [ + FileMode::Replace->value => new ReplaceMode(), + FileMode::Preserve->value => new PreserveMode(), + FileMode::Append->value => new AppendMode(), + FileMode::Prepend->value => new PrependMode(), + ]; + } + + /** + * Applies the files of every provider listed in `allowed-packages` and installed, and records them in + * `scaffold-lock.json`; a later provider overrides an earlier one per destination, and ejected files stay + * untouched. + * + * @param ProjectConfig $config Consumer settings that list the allowed providers in order. + * @param array $providers Installed packages keyed by package name. + * @param string $projectRoot Absolute path to the project root. + * @param bool $force Whether to overwrite user-modified and adopted `replace` destinations. + * + * @throws ScaffoldException when the manifest of an allowed and installed provider cannot be loaded; the message + * is written to stderr first and nothing is applied. + * @throws \RuntimeException when the lock file cannot be read or written. + * + * @return ScaffoldSummary Counters of the run; a mapping that fails to apply is reported, counted in + * {@see ScaffoldSummary::$errors}, and does not stop the run. + */ + public function run( + ProjectConfig $config, + array $providers, + string $projectRoot, + bool $force = false, + ): ScaffoldSummary { + $merged = []; + $providerEntries = []; + + foreach ($config->allowedPackages as $name) { + $provider = $providers[$name] ?? null; + + if ($provider === null) { + $this->out->writeStderr( + ConsoleMessage::SCAFFOLD_PROVIDER_NOT_INSTALLED->getMessage($name), + ); + + $this->summary->warnings++; + + continue; + } + + if ($provider->installPath === null) { + $this->out->writeStderr( + ConsoleMessage::SCAFFOLD_PROVIDER_INSTALL_PATH_MISSING->getMessage($name), + ); + + $this->summary->warnings++; + + continue; + } + + try { + $mappings = $provider->extra === null + ? $this->loader->loadFromPath($name, $provider->installPath) + : $this->loader->loadFromExtra($provider->extra, $name, $provider->installPath); + } catch (Throwable $e) { + $message = Message::SCAFFOLD_MANIFEST_LOAD_FAILED->getMessage($name, $e->getMessage()); + + $this->out->writeStderr( + $message, + ); + + $this->summary->errors++; + + // Applying the other providers could write the wrong owner of a shared destination: abort first. + throw new ScaffoldException($message, previous: $e); + } + + // Recorded only after a successful load, so a failing provider never advances its version in the lock. + $providerEntries[$name] = [ + 'version' => $provider->prettyVersion, + // Both sides are canonical, so symlinked or short-name roots still yield a relative path. + 'path' => self::toProjectRelative( + PathResolver::realpathOrFallback($provider->installPath), + PathResolver::realpathOrFallback($projectRoot), + ), + ]; + + if ($mappings === []) { + $this->out->writeStderr( + ConsoleMessage::SCAFFOLD_PROVIDER_MAPPINGS_EMPTY->getMessage($name), + ); + + $this->summary->warnings++; + + continue; + } + + foreach (MappingMerger::merge($merged, $mappings) as [$mapping, $previous]) { + $this->out->writeStdout( + ConsoleMessage::SCAFFOLD_OVERRIDE->getMessage( + $mapping->destination, + $mapping->providerName, + $previous->providerName, + ), + ); + } + } + + if ($merged === []) { + if ($this->lockFile->exists()) { + $this->reportOrphans(new ExpectedState([]), $this->lockFile->read()['files']); + } + + return $this->summary; + } + + $lockData = $this->lockFile->read(); + + $dirty = false; + $conflictsBefore = $this->summary->conflict; + + foreach ($providerEntries as $providerName => $entry) { + $existing = $lockData['providers'][$providerName] ?? null; + + if (!is_array($existing) || $existing !== $entry) { + $lockData['providers'][$providerName] = $entry; + $dirty = true; + } + } + + // Keys are not used: PHP turns integer-like destinations ("123") into integer array keys. + foreach ($merged as $mapping) { + $destination = $mapping->destination; + $existing = $lockData['files'][$destination] ?? null; + + // Ejected files belong to the user: never touched, never rehashed. + if (($existing['ejected'] ?? false) === true) { + $this->summary->unchanged++; + + continue; + } + + try { + $entry = $this->applyMapping($mapping, $existing, $projectRoot, $force); + + if ($entry !== null && $entry !== $existing) { + $lockData['files'][$destination] = $entry; + $dirty = true; + } + } catch (Throwable $e) { + $this->out->writeStderr( + ConsoleMessage::SCAFFOLD_APPLY_FAILED->getMessage($destination, $e->getMessage()), + ); + + $this->summary->errors++; + } + } + + if ($dirty) { + $this->lockFile->write($lockData); + } + + $conflicts = $this->summary->conflict - $conflictsBefore; + + if ($conflicts > 0) { + $this->out->writeStderr( + ConsoleMessage::SCAFFOLD_CONFLICTS->getMessage( + $conflicts, + ConsoleMessage::plural( + $conflicts, + ConsoleMessage::FRAGMENT_CONFLICT_FILE, + ConsoleMessage::FRAGMENT_CONFLICT_FILES, + ), + ), + ); + } + + $this->reportOrphans(new ExpectedState($merged), $lockData['files']); + + return $this->summary; + } + + /** + * Applies one mapping and returns the lock entry to record for it. + * + * @param FileMapping $mapping File mapping to apply. + * @param LockEntry|null $existing Current lock entry, or `null` when the destination is untracked. + * @param string $projectRoot Absolute path to the project root. + * @param bool $force Whether to overwrite a user-modified or adopted `replace` destination. + * + * @throws \RuntimeException when a path fails validation or a file cannot be read, written or hashed. + * + * @return LockEntry|null Entry to record, or `null` when the current entry must stay unchanged. + */ + private function applyMapping( + FileMapping $mapping, + array|null $existing, + string $projectRoot, + bool $force, + ): array|null { + $destination = $mapping->destination; + $destPath = PathResolver::destination($projectRoot, $destination); + + $existed = file_exists($destPath); + $hashAtScaffold = is_string($existing['hash'] ?? null) ? $existing['hash'] : null; + + if ($mapping->mode === FileMode::Replace && $existed) { + if ($force) { + // A forced replace treats the current content as pristine, so the stub overwrites it silently. + $hashAtScaffold = Hasher::hash($destPath); + + unset($existing['adopted']); + } elseif (($existing['adopted'] ?? false) === true) { + $this->out->writeStderr( + ConsoleMessage::SCAFFOLD_ADOPTED_SKIPPED->getMessage($destination), + ); + + $this->summary->warnings++; + + if ($this->stubChanged($mapping, $existing)) { + $this->summary->conflict++; + } + + return null; + } + } + + $result = $this->applier->apply($mapping, $projectRoot, $this->modes[$mapping->mode->value], $hashAtScaffold); + + $this->count($result, $existed ? $hashAtScaffold : null); + + if ($result->outcome === ApplyOutcome::Skipped && $this->stubChanged($mapping, $existing)) { + // Only a user-modified `replace` destination is skipped without a hash. + if ($result->newHash === '') { + // The consumer changed the file and the provider changed its stub: the update is not taken. + $this->summary->conflict++; + } elseif ($mapping->mode === FileMode::Preserve) { + $this->summary->outdated++; + } + } + + return $this->buildEntry($mapping, $result, $existing); + } + + /** + * Returns the lock entry to record for an applied mapping, with a fresh `stub-hash`. + * + * @param FileMapping $mapping Applied file mapping. + * @param ApplyResult $result Result returned by the mode for the mapping. + * @param array|null $existing Current lock entry, or `null` when untracked. + * + * @throws \RuntimeException when the provider source cannot be hashed. + * + * @return LockEntry|null Entry to record, or `null` when the current entry must stay unchanged. + */ + private function buildEntry(FileMapping $mapping, ApplyResult $result, array|null $existing): array|null + { + if ($result->outcome === ApplyOutcome::Skipped && $result->newHash === '') { + return null; + } + + $existingHash = $existing['hash'] ?? null; + $written = $result->outcome === ApplyOutcome::Written; + + $entry = [ + 'hash' => !$written && is_string($existingHash) ? $existingHash : $result->newHash, + 'provider' => $mapping->providerName, + 'source' => $mapping->source, + 'mode' => $mapping->mode->value, + 'stub-hash' => Hasher::hash(PathResolver::source($mapping->providerPath, $mapping->source)), + ]; + + if ($mapping->mergeStrategy !== null) { + $entry['merge'] = $mapping->mergeStrategy->value; + } + + $adopted = ($existing['adopted'] ?? false) === true + || ($existing === null && $mapping->mode === FileMode::Preserve); + + if (!$written && $adopted) { + $entry['adopted'] = true; + } + + return $entry; + } + + /** + * Counts an apply result as written, unchanged or warned; rewriting an existing destination with the content it + * already had counts as unchanged. + * + * @param ApplyResult $result Result returned by the mode for the mapping. + * @param string|null $previousHash Recorded hash of a destination that existed before the apply, or `null`. + */ + private function count(ApplyResult $result, string|null $previousHash): void + { + $rewritten = $previousHash !== null && $previousHash === $result->newHash; + + if ($result->outcome === ApplyOutcome::Written && !$rewritten) { + $this->summary->written++; + } elseif ($result->warning === null) { + $this->summary->unchanged++; + } + + if ($result->warning !== null) { + $this->summary->warnings++; + } + } + + /** + * Returns whether `$haystack` starts with `$needle`, ignoring case when `$caseInsensitive` is `true`. + * + * @param string $haystack String to inspect. + * @param string $needle Prefix to look for. + * @param bool $caseInsensitive Whether to compare ignoring case. + * + * @return bool `true` when `$haystack` starts with `$needle`, `false` otherwise. + */ + private static function prefixMatches(string $haystack, string $needle, bool $caseInsensitive): bool + { + return $caseInsensitive + ? stripos($haystack, $needle) === 0 + : str_starts_with($haystack, $needle); + } + + /** + * Lists on stderr the lock entries that no allowed and installed provider ships anymore, with the `prune` hint; + * nothing is deleted. + * + * @param ExpectedState $expected Destinations that the allowed and installed providers ship. + * @param array $files `files` map of `scaffold-lock.json`. + */ + private function reportOrphans(ExpectedState $expected, array $files): void + { + $lines = $expected->orphanReport($files); + + if ($lines === []) { + return; + } + + $this->summary->orphan += count($expected->orphans($files)); + + foreach ($lines as $line) { + $this->out->writeStderr( + $line, + ); + } + } + + /** + * Returns whether the provider stub of `$mapping` differs from the `stub-hash` recorded at the last apply; `false` + * when no `stub-hash` is recorded. + * + * @param FileMapping $mapping File mapping whose provider source is hashed. + * @param array|null $existing Current lock entry, or `null` when untracked. + * + * @throws \RuntimeException when the provider source cannot be hashed. + * + * @return bool `true` when the recorded `stub-hash` differs from the current source hash, `false` otherwise. + */ + private function stubChanged(FileMapping $mapping, array|null $existing): bool + { + $recorded = $existing['stub-hash'] ?? null; + + if (!is_string($recorded)) { + return false; + } + + $current = Hasher::hash(PathResolver::source($mapping->providerPath, $mapping->source)); + + return $recorded !== $current; + } + + /** + * Converts a canonical absolute path to a project-relative path with forward slashes, comparing the root prefix + * case-insensitively on Windows. + * + * @param string $absolutePath Absolute path to convert. + * @param string $projectRoot Absolute path to the project root. + * + * @return string Relative path, or the absolute path with forward slashes when it lies outside the project root. + */ + private static function toProjectRelative(string $absolutePath, string $projectRoot): string + { + $normalizedRoot = rtrim(str_replace('\\', '/', $projectRoot), '/') . '/'; + $normalizedPath = str_replace('\\', '/', $absolutePath); + + if (self::prefixMatches($normalizedPath . '/', $normalizedRoot, DIRECTORY_SEPARATOR === '\\')) { + return substr($normalizedPath, strlen($normalizedRoot)); + } + + return $normalizedPath; + } +} diff --git a/src/Scaffold/ScaffoldSummary.php b/src/Scaffold/ScaffoldSummary.php new file mode 100644 index 0000000..840d2e1 --- /dev/null +++ b/src/Scaffold/ScaffoldSummary.php @@ -0,0 +1,114 @@ +getMessage( + $this->written, + Message::plural($this->written, Message::FRAGMENT_FILE, Message::FRAGMENT_FILES), + ), + Message::FRAGMENT_COUNT_UNCHANGED->getMessage($this->unchanged), + ]; + + $states = [ + [$this->outdated, Message::FRAGMENT_OUTDATED], + [$this->conflict, Message::FRAGMENT_CONFLICT], + [$this->orphan, Message::FRAGMENT_ORPHAN], + ]; + + foreach ($states as [$count, $state]) { + if ($count > 0) { + $parts[] = Message::FRAGMENT_COUNT->getMessage($count, $state->getMessage()); + } + } + + if ($this->warnings > 0) { + $parts[] = Message::FRAGMENT_COUNT->getMessage( + $this->warnings, + Message::plural($this->warnings, Message::FRAGMENT_WARNING, Message::FRAGMENT_WARNINGS), + ); + } + + if ($this->errors > 0) { + $parts[] = Message::FRAGMENT_COUNT->getMessage( + $this->errors, + Message::plural($this->errors, Message::FRAGMENT_ERROR, Message::FRAGMENT_ERRORS), + ); + } + + return Message::SCAFFOLD_SUMMARY->getMessage( + $command === '' ? '' : Message::FRAGMENT_COMMAND->getMessage($command), + implode(', ', $parts), + ); + } + + /** + * Returns the summary line of {@see self::format()}, or `null` when nothing was written and nothing needs + * attention. + * + * @return string|null Summary line, or `null` when every counter except `unchanged` is zero. + */ + public function line(): string|null + { + $quiet = $this->written === 0 + && $this->warnings === 0 + && $this->errors === 0 + && $this->outdated === 0 + && $this->conflict === 0 + && $this->orphan === 0; + + return $quiet ? null : $this->format(); + } +} diff --git a/src/Scaffold/Scaffolder.php b/src/Scaffold/Scaffolder.php index 3b9b17d..d60f173 100644 --- a/src/Scaffold/Scaffolder.php +++ b/src/Scaffold/Scaffolder.php @@ -4,272 +4,85 @@ namespace PHPForge\Scaffold\Scaffold; -use Composer\IO\IOInterface; use Composer\Package\PackageInterface; -use PHPForge\Scaffold\Manifest\{FileMode, ManifestLoader}; +use PHPForge\Scaffold\Config\{ProjectConfig, ProviderPackage}; +use PHPForge\Scaffold\Console\{Message, OutputWriter}; +use PHPForge\Scaffold\Manifest\ManifestLoader; use PHPForge\Scaffold\Scaffold\Lock\LockFile; -use PHPForge\Scaffold\Scaffold\Modes\{AppendMode, ApplyOutcome, ModeInterface, PrependMode, PreserveMode, ReplaceMode}; -use Throwable; - -use function is_array; -use function is_string; -use function rtrim; -use function sprintf; -use function str_replace; -use function str_starts_with; -use function stripos; -use function strlen; -use function substr; /** - * Orchestrates the full scaffold lifecycle: provider resolution, manifest loading, mode application, and lock writing. + * Applies every authorized provider's files to the project inside a Composer run by converting Composer's packages + * for the Composer-free {@see ScaffoldRunner}. */ final readonly class Scaffolder { /** - * @var array Pre-instantiated mode implementations keyed by the backing value of - * {@see FileMode} for efficient resolution during scaffolding. + * @param ManifestLoader $loader Loads provider manifests into file mappings. + * @param FileApplier $applier Validates and applies each mapping. + * @param LockFile $lockFile Lock file of the project. + * @param OutputWriter $out Output sink for notices and warnings. + * @param ScaffoldSummary $summary Counters that the runs of this scaffolder update. */ - private array $modes; - public function __construct( private ManifestLoader $loader, - private Applier $applier, + private FileApplier $applier, private LockFile $lockFile, - private IOInterface $io, - ) { - $this->modes = [ - FileMode::Replace->value => new ReplaceMode(), - FileMode::Preserve->value => new PreserveMode(), - FileMode::Append->value => new AppendMode(), - FileMode::Prepend->value => new PrependMode(), - ]; - } + private OutputWriter $out, + private ScaffoldSummary $summary, + ) {} /** - * Runs the scaffold process for all authorized providers. + * Applies the files of every installed provider listed in `allowed-packages` and records them in + * `scaffold-lock.json`; a later provider overrides an earlier one per destination, and ejected files stay + * untouched. * - * @param PackageInterface $rootPackage Root Composer package providing the configuration. - * @param PackageInterface[] $installedPackages All packages currently installed in the project. + * @param ProjectConfig $config Consumer settings of the root package. + * @param PackageInterface[] $installedPackages Packages installed in the project. * @param string $projectRoot Absolute path to the project root. - * @param string $vendorDir Absolute path to the Composer vendor directory (used as fallback for install paths). - * @param bool $fullScaffold When `true`, applies all modes including `append` and `prepend`. When `false`, skips - * `append`/`prepend` for files already recorded in the lock file. - * @param array $installPaths Map of package name to absolute install path resolved by Composer's - * `InstallationManager`. When provided, these paths take precedence over the default vendor-dir concatenation, - * enabling correct path resolution for packages with custom installer strategies. + * @param string $vendorDir Absolute path to the vendor directory, used for providers missing from `$installPaths`. + * @param array $installPaths Absolute install paths keyed by package name, as resolved by + * Composer's `InstallationManager`. + * + * @throws \PHPForge\Scaffold\Exception\ScaffoldException when the manifest of an allowed provider cannot be loaded. + * @throws \RuntimeException when the lock file cannot be read or written. */ public function scaffold( - PackageInterface $rootPackage, + ProjectConfig $config, array $installedPackages, string $projectRoot, string $vendorDir, - bool $fullScaffold, array $installPaths = [], ): void { - $extra = $rootPackage->getExtra(); - - $scaffoldConfig = $extra['scaffold'] ?? null; - - if (!is_array($scaffoldConfig)) { - $this->io->write('[scaffold] No extra.scaffold configuration found. Skipping scaffold.'); + if (!$config->declared) { + $this->out->writeStdout( + Message::SCAFFOLD_CONFIG_MISSING->getMessage(), + ); return; } - $rawAllowed = $scaffoldConfig['allowed-packages'] ?? null; - - if (!is_array($rawAllowed) || $rawAllowed === []) { - $this->io->write('[scaffold] No allowed-packages configured. Skipping scaffold.'); + if ($config->allowedPackages === [] && $config->ignoredEntries === 0) { + $this->out->writeStdout( + Message::SCAFFOLD_NO_ALLOWED_PACKAGES->getMessage(), + ); return; } - // Index installed packages by name for O(1) lookup. - $byName = []; + $providers = []; foreach ($installedPackages as $package) { - $byName[$package->getName()] = $package; - } - - // Merge file mappings in allowed-packages order; last provider wins for duplicate destinations. - $merged = []; - $providerEntries = []; - - foreach ($rawAllowed as $allowedName) { - if (!is_string($allowedName)) { - continue; - } - - $package = $byName[$allowedName] ?? null; - - if ($package === null) { - $this->io->write(sprintf('[scaffold] Provider "%s" is not installed. Skipping.', $allowedName)); - - continue; - } - - $packagePath = $installPaths[$allowedName] ?? "{$vendorDir}/{$allowedName}"; - $providerEntries[$allowedName] = [ - 'version' => $package->getPrettyVersion(), - 'path' => self::toProjectRelative($packagePath, $projectRoot), - ]; - - try { - $mappings = $this->loader->load($package, $packagePath); - } catch (Throwable $e) { - $this->io->writeError( - sprintf('[scaffold] Failed to load manifest for "%s": %s', $allowedName, $e->getMessage()), - ); - - continue; - } - - foreach ($mappings as $mapping) { - $merged[$mapping->destination] = $mapping; - } - } - - if ($merged === []) { - return; - } - - $lockData = $this->lockFile->read(); - $dirty = false; - - foreach ($providerEntries as $providerName => $entry) { - $existing = $lockData['providers'][$providerName] ?? null; - - if (!is_array($existing) || $existing !== $entry) { - $lockData['providers'][$providerName] = $entry; - $dirty = true; - } - } - - foreach ($merged as $destination => $mapping) { - if ( - !$fullScaffold - && ($mapping->mode === FileMode::Append || $mapping->mode === FileMode::Prepend) - && isset($lockData['files'][$destination]) - ) { - continue; - } - - try { - $mode = $this->resolveMode($mapping->mode); - $hashAtScaffold = $this->extractHash($lockData, $destination); - - $result = $this->applier->apply($mapping, $projectRoot, $mode, $hashAtScaffold); - - if ($result->outcome === ApplyOutcome::Written) { - $lockData['files'][$destination] = [ - 'hash' => $result->newHash, - 'provider' => $mapping->providerName, - 'source' => $mapping->source, - 'mode' => $mapping->mode->value, - ]; - $dirty = true; - } elseif ($result->newHash !== '') { - // Refresh ownership metadata when a different provider claims the file but the on-disk content - // is already in sync; the hash is left intact so replace-mode user-modification detection keeps - // its original baseline. - $expected = [ - 'hash' => $lockData['files'][$destination]['hash'] ?? $result->newHash, - 'provider' => $mapping->providerName, - 'source' => $mapping->source, - 'mode' => $mapping->mode->value, - ]; - - if (($lockData['files'][$destination] ?? null) !== $expected) { - $lockData['files'][$destination] = $expected; - $dirty = true; - } - } - } catch (Throwable $e) { - $this->io->writeError( - sprintf('[scaffold] Error applying "%s": %s', $destination, $e->getMessage()), - ); - } - } - - if ($dirty) { - $this->lockFile->write($lockData); - } - } - - /** - * Extracts the hash for a given destination from the lock data, if it exists. - * - * @param array{ - * providers: array, - * files: array, - * } $lockData Decoded lock file data. - * @param string $destination Destination path to look up. - * - * @return string|null Hash if found, or `null` if the destination is not in the lock data. - */ - private function extractHash(array $lockData, string $destination): string|null - { - $entry = $lockData['files'][$destination] ?? null; - $hash = $entry['hash'] ?? null; - - return is_string($hash) ? $hash : null; - } - - /** - * Byte-exact or case-insensitive prefix match, depending on `$caseInsensitive`. - * - * Extracted from {@see self::toProjectRelative()} so both branches remain reachable under tests regardless of the - * host platform's `DIRECTORY_SEPARATOR`. - * - * @param string $haystack String to inspect. - * @param string $needle Prefix to look for. - * @param bool $caseInsensitive `true` to match case-insensitively (Windows/NTFS semantics), `false` for byte-exact. - * - * @return bool `true` when `$haystack` starts with `$needle` under the requested comparison. - */ - private static function prefixMatches(string $haystack, string $needle, bool $caseInsensitive): bool - { - return $caseInsensitive - ? stripos($haystack, $needle) === 0 - : str_starts_with($haystack, $needle); - } - - /** - * Resolves a {@see FileMode} to its corresponding {@see ModeInterface} implementation. - * - * @param FileMode $mode Mode case to resolve. - * - * @return ModeInterface Corresponding mode implementation. - */ - private function resolveMode(FileMode $mode): ModeInterface - { - return $this->modes[$mode->value]; - } - - /** - * Converts an absolute path to one relative to the project root, using forward slashes. - * - * Returns the input unchanged (with forward slashes) when it lies outside the project root; storing an absolute - * path is a safe fallback for unusual deployments where the provider lives outside the root. - * - * The prefix check is case-insensitive on Windows because NTFS is case-insensitive and Composer may hand back paths - * whose casing differs between `projectRoot` and `packagePath` (for example, `C:\Users\foo` vs. `c:\users\FOO`). - * - * @param string $absolutePath Absolute path to convert. - * @param string $projectRoot Absolute path to the project root. - * - * @return string Relative path using forward slashes, or the normalized absolute path when outside the root. - */ - private static function toProjectRelative(string $absolutePath, string $projectRoot): string - { - $normalizedRoot = rtrim(str_replace('\\', '/', $projectRoot), '/') . '/'; - $normalizedPath = str_replace('\\', '/', $absolutePath); - - if (self::prefixMatches($normalizedPath . '/', $normalizedRoot, DIRECTORY_SEPARATOR === '\\')) { - return rtrim(substr($normalizedPath, strlen($normalizedRoot)), '/'); + $name = $package->getName(); + + $providers[$name] = new ProviderPackage( + $name, + $package->getPrettyVersion(), + $package->getType() === 'metapackage' ? null : $installPaths[$name] ?? "{$vendorDir}/{$name}", + $package->getExtra(), + ); } - return rtrim($normalizedPath, '/'); + (new ScaffoldRunner($this->loader, $this->applier, $this->lockFile, $this->out, $this->summary)) + ->run($config, $providers, $projectRoot); } } diff --git a/src/Security/PackageAllowlist.php b/src/Security/PackageAllowlist.php deleted file mode 100644 index 9f0f2a4..0000000 --- a/src/Security/PackageAllowlist.php +++ /dev/null @@ -1,52 +0,0 @@ - $allowedPackages Package names from `extra.scaffold.allowed-packages`. - */ - public function __construct(private array $allowedPackages) {} - - /** - * Asserts that the given package is authorized to write scaffold files. - * - * @throws RuntimeException when the package is not in the allowlist. - */ - public function assertAllowed(string $packageName): void - { - if (!$this->isAllowed($packageName)) { - throw new RuntimeException( - sprintf( - 'Package "%s" is not authorized to scaffold files. Add it to extra.scaffold.allowed-packages.', - $packageName, - ), - ); - } - } - - /** - * Returns whether the given package name is in the allowlist. - * - * @param string $packageName Name of the package to check. - * - * @return bool `true` if the package is allowed to scaffold files, `false` otherwise. - */ - public function isAllowed(string $packageName): bool - { - return in_array($packageName, $this->allowedPackages, strict: true); - } -} diff --git a/src/Security/PathValidator.php b/src/Security/PathValidator.php index a51919f..01e5675 100644 --- a/src/Security/PathValidator.php +++ b/src/Security/PathValidator.php @@ -4,47 +4,83 @@ namespace PHPForge\Scaffold\Security; +use PHPForge\Scaffold\Exception\Message; +use PHPForge\Scaffold\Filesystem; use RuntimeException; -use function sprintf; - /** - * Validates scaffold paths against path traversal and absolute path injection. - * - * Both destination (project-relative) and source (provider-relative) paths are validated before any filesystem - * operation. Rejects paths containing `..` as a segment and paths that begin with a directory separator. + * Rejects source and destination paths that are absolute, contain `..` segments, escape their root through a symlink, + * or address the reserved `scaffold-lock.json`. */ final class PathValidator { + /** + * Maximum number of symlink hops followed when resolving a dangling symlink leaf, as the `ELOOP` limit of Linux. + */ + private const int MAX_SYMLINK_HOPS = 40; + + /** + * Destination reserved for the lock file written by the plugin. + */ + private const string RESERVED_DESTINATION = 'scaffold-lock.json'; + + /** + * Returns whether `$path` contains a `..` segment, splitting on forward slashes and backslashes. + * + * @param string $path Path to check. + * + * @return bool `true` when a segment is `..`, `false` otherwise. + */ + public static function hasTraversal(string $path): bool + { + return in_array('..', explode('/', str_replace('\\', '/', $path)), true); + } + + /** + * Returns whether `$path` starts with a directory separator or a Windows drive letter. + * + * @param string $path Path to check. + * + * @return bool `true` when the path is absolute or drive-qualified, `false` otherwise. + */ + public static function isAbsolute(string $path): bool + { + return str_starts_with($path, '/') + || str_starts_with($path, '\\') + || preg_match('/^[A-Za-z]:/', $path) === 1; + } + /** * Validates that a destination path does not escape the project root. * * @param string $destination Relative destination path declared in the manifest. * @param string $projectRoot Absolute path to the project root directory. * - * @throws RuntimeException on path traversal or absolute path attempt. + * @throws RuntimeException when the project root does not exist, or the destination is absolute, contains `..`, + * escapes the root through a symlink, or is reserved. + * + * @return string Canonical absolute path of the project root. */ - public function validateDestination(string $destination, string $projectRoot): void + public function validateDestination(string $destination, string $projectRoot): string { $this->assertRelative($destination, 'destination'); $this->assertNoTraversal($destination, 'destination'); + $this->assertNotReserved($destination); $realRoot = realpath($projectRoot); if ($realRoot === false) { throw new RuntimeException( - sprintf('Project root does not exist or is not accessible: "%s".', $projectRoot), + Message::PATH_PROJECT_ROOT_INACCESSIBLE->getMessage($projectRoot), ); } - /** - * After assertRelative + assertNoTraversal the relative segment cannot escape the base, so normalizePath's - * literal concatenation is guaranteed to stay under $realRoot; the remaining risk is a symlinked ancestor, - * which assertNoSymlinkEscape covers below. - */ + // A relative path without '..' segments stays under $realRoot; only symlinks can make it escape. $normalized = $this->normalizePath($realRoot, $destination); $this->assertNoSymlinkEscape($normalized, $realRoot, 'destination', $destination); + + return $realRoot; } /** @@ -53,9 +89,12 @@ public function validateDestination(string $destination, string $projectRoot): v * @param string $source Relative source path declared in the manifest. * @param string $providerRoot Absolute path to the provider root inside vendor. * - * @throws RuntimeException on path traversal or absolute path attempt. + * @throws RuntimeException when the provider root does not exist, or the source is absolute, contains `..` or + * escapes the root through a symlink. + * + * @return string Canonical absolute path of the provider root. */ - public function validateSource(string $source, string $providerRoot): void + public function validateSource(string $source, string $providerRoot): string { $this->assertRelative($source, 'source'); $this->assertNoTraversal($source, 'source'); @@ -64,34 +103,82 @@ public function validateSource(string $source, string $providerRoot): void if ($realRoot === false) { throw new RuntimeException( - sprintf('Provider root does not exist or is not accessible: "%s".', $providerRoot), + Message::PATH_PROVIDER_ROOT_INACCESSIBLE->getMessage($providerRoot), ); } - /** - * See validateDestination: the redundant containment check was removed because normalizePath's literal - * concatenation cannot escape $realRoot after assertRelative + assertNoTraversal; symlink ancestors are - * still verified below. - */ + // A relative path without '..' segments stays under $realRoot; only symlinks can make it escape. $normalized = $this->normalizePath($realRoot, $source); $this->assertNoSymlinkEscape($normalized, $realRoot, 'source', $source); + + return $realRoot; } /** - * Walks up from the deepest existing ancestor of `$normalized` and rejects the path if that ancestor resolves - * outside `$realRoot` via a symlink. + * Rejects `$normalized` when it starts a symlink chain that exceeds `MAX_SYMLINK_HOPS` hops, or in which a target + * parent directory cannot be resolved or lies outside `$realRoot`. * - * Checking only `realpath(dirname($normalized))` misses the case where the immediate parent does not yet exist but - * a higher-level ancestor is a symlink that escapes the root. This method finds the deepest path segment that - * already exists on disk, resolves it, and enforces containment. + * @param string $normalized Absolute, traversal-free path whose `realpath()` failed. + * @param string $realRoot Resolved root boundary (output of `realpath()`). + * @param string $context Human-readable label for error messages (`'source'` or `'destination'`). + * @param string $originalPath Original user-supplied path, used only in the exception message. + * + * @throws RuntimeException when the symlink target escapes `$realRoot` or cannot be resolved. + */ + private function assertDanglingSymlinkContained( + string $normalized, + string $realRoot, + string $context, + string $originalPath, + ): void { + $current = $normalized; + $hops = 0; + + while (is_link($current)) { + $target = Filesystem::readLink( + $current, + Message::PATH_SYMLINK_UNRESOLVABLE->getMessage(ucfirst($context), $originalPath), + ); + + if (++$hops > self::MAX_SYMLINK_HOPS) { + throw new RuntimeException( + Message::PATH_SYMLINK_UNRESOLVABLE->getMessage(ucfirst($context), $originalPath), + ); + } + + if (!self::isAbsolute($target)) { + $target = dirname($current) . DIRECTORY_SEPARATOR . $target; + } + + $parent = realpath(dirname($target)); + + if ($parent === false) { + throw new RuntimeException( + Message::PATH_SYMLINK_UNRESOLVABLE->getMessage(ucfirst($context), $originalPath), + ); + } + + if (!str_starts_with($parent . DIRECTORY_SEPARATOR, $realRoot . DIRECTORY_SEPARATOR)) { + throw new RuntimeException( + Message::PATH_SYMLINK_ESCAPE->getMessage(ucfirst($context), $originalPath), + ); + } + + $current = $parent . DIRECTORY_SEPARATOR . basename($target); + } + } + + /** + * Rejects `$normalized` when the path itself, the target of a dangling symlink leaf, or any existing ancestor + * resolves outside `$realRoot`. * * @param string $normalized Absolute, traversal-free path to validate. * @param string $realRoot Resolved root boundary (output of `realpath()`). * @param string $context Human-readable label for error messages (`'source'` or `'destination'`). * @param string $originalPath Original user-supplied path, used only in the exception message. * - * @throws RuntimeException when a symlink ancestor escapes `$realRoot`. + * @throws RuntimeException when the path escapes `$realRoot` through a symlink or a symlink cannot be resolved. */ private function assertNoSymlinkEscape( string $normalized, @@ -104,13 +191,15 @@ private function assertNoSymlinkEscape( if ($resolved !== false) { if (!str_starts_with($resolved . DIRECTORY_SEPARATOR, $realRoot . DIRECTORY_SEPARATOR)) { throw new RuntimeException( - sprintf('%s path escapes the root via symlink: "%s".', ucfirst($context), $originalPath), + Message::PATH_SYMLINK_ESCAPE->getMessage(ucfirst($context), $originalPath), ); } return; } + $this->assertDanglingSymlinkContained($normalized, $realRoot, $context, $originalPath); + $dir = dirname($normalized); while ($dir !== $realRoot && $dir !== dirname($dir)) { @@ -121,7 +210,7 @@ private function assertNoSymlinkEscape( && !str_starts_with($resolved . DIRECTORY_SEPARATOR, $realRoot . DIRECTORY_SEPARATOR) ) { throw new RuntimeException( - sprintf('%s path escapes the root via symlink: "%s".', ucfirst($context), $originalPath), + Message::PATH_SYMLINK_ESCAPE->getMessage(ucfirst($context), $originalPath), ); } @@ -139,59 +228,65 @@ private function assertNoSymlinkEscape( */ private function assertNoTraversal(string $path, string $context): void { - /** - * Normalize both separators to `/` then split; `explode` always returns array, avoiding the - * defensive false-branch that `preg_split` would have produced for malformed input. - */ - $segments = explode('/', str_replace('\\', '/', $path)); - - foreach ($segments as $segment) { - if ($segment === '..') { + if (self::hasTraversal($path)) { + throw new RuntimeException( + Message::PATH_TRAVERSAL->getMessage($context, $path), + ); + } + } + + /** + * Asserts that `$destination` addresses neither `scaffold-lock.json` nor a path below it, ignoring case so that + * case-insensitive filesystems cannot bypass the check. + * + * @param string $destination Relative destination path declared in the manifest. + * + * @throws RuntimeException when the destination is reserved. + */ + private function assertNotReserved(string $destination): void + { + foreach (explode('/', str_replace('\\', '/', $destination)) as $segment) { + if ($segment === '' || $segment === '.') { + continue; + } + + if (strcasecmp($segment, self::RESERVED_DESTINATION) === 0) { throw new RuntimeException( - sprintf('Path traversal detected in %s: "%s".', $context, $path), + Message::PATH_RESERVED->getMessage($destination), ); } + + return; } } /** * Asserts that a path is relative (does not start with a directory separator or drive letter). * + * @param string $path Path to check. + * @param string $context Path kind named in the error message (`destination` or `source`). + * * @throws RuntimeException when an absolute path is detected. */ private function assertRelative(string $path, string $context): void { - if ( - str_starts_with($path, '/') - || str_starts_with($path, '\\') - || preg_match('/^[A-Za-z]:/', $path) === 1 - ) { + if (self::isAbsolute($path)) { throw new RuntimeException( - sprintf('Absolute path is not allowed in %s: "%s".', $context, $path), + Message::PATH_ABSOLUTE->getMessage($context, $path), ); } } /** - * Normalizes a base + relative path without requiring the target to exist on disk. - * - * The relative path must have already passed traversal validation this method does not re-validate and assumes no - * `..` segments are present. + * Joins an absolute base and a relative path already checked for `..` segments, without touching the filesystem. * * @param string $base Absolute base path. * @param string $relative Relative path to combine with the base. * - * @return string Normalized absolute path combining the base and relative segments. + * @return string Absolute path without trailing separator. */ private function normalizePath(string $base, string $relative): string { - // Windows-only normalisation: str_replace is a no-op on POSIX (separator is '/'). - // @codeCoverageIgnoreStart - $normalizedRelative = str_replace('/', DIRECTORY_SEPARATOR, $relative); - // @codeCoverageIgnoreEnd - - $combined = $base . DIRECTORY_SEPARATOR . $normalizedRelative; - - return rtrim($combined, DIRECTORY_SEPARATOR); + return rtrim($base . DIRECTORY_SEPARATOR . $relative, DIRECTORY_SEPARATOR); } } diff --git a/src/Services/ApplyPreview.php b/src/Services/ApplyPreview.php new file mode 100644 index 0000000..9536490 --- /dev/null +++ b/src/Services/ApplyPreview.php @@ -0,0 +1,74 @@ +exists || $this->current !== $this->proposed; + } + + /** + * Returns whether the current and proposed contents differ only in their line endings. + * + * @return bool `true` when the destination exists and its content equals the proposed one after normalising line + * endings, `false` otherwise. + */ + public function differsOnlyInLineEndings(): bool + { + return $this->exists + && $this->current !== $this->proposed + && self::normaliseLineEndings($this->current) === self::normaliseLineEndings($this->proposed); + } + + /** + * Normalises `\r\n` and `\r` line endings to `\n`. + * + * @param string $text Text to normalise. + * + * @return string Text with `\n` line endings only. + */ + private static function normaliseLineEndings(string $text): string + { + return preg_replace('/\r\n|\r/', "\n", $text) + ?? throw new LogicException(Message::REGEX_FAILED->getMessage(preg_last_error_msg())); + } +} diff --git a/src/Services/ApplyPreviewer.php b/src/Services/ApplyPreviewer.php new file mode 100644 index 0000000..c88984c --- /dev/null +++ b/src/Services/ApplyPreviewer.php @@ -0,0 +1,113 @@ +providerPath, $mapping->source); + + if (!is_file($stubPath)) { + throw new RuntimeException( + Message::SERVICE_STUB_NOT_FOUND->getMessage($stubPath), + ); + } + + $stub = Filesystem::read($stubPath, Message::SERVICE_STUB_UNREADABLE->getMessage($stubPath)); + + $destPath = PathResolver::destination($projectRoot, $mapping->destination); + $exists = file_exists($destPath); + + $current = $exists + ? Filesystem::read($destPath, Message::SERVICE_CURRENT_FILE_UNREADABLE->getMessage($destPath)) + : ''; + + return match ($mapping->mode) { + FileMode::Replace => new ApplyPreview( + $mapping, + $exists, + $current, + $stub, + userModified: $exists && $this->isUserModified($destPath, $entry), + ), + FileMode::Preserve => new ApplyPreview( + $mapping, + $exists, + $current, + $stub, + informational: $exists, + ), + FileMode::Append => new ApplyPreview( + $mapping, + $exists, + $current, + ( + $mapping->mergeStrategy !== null + ? StrategyResolver::forKind($mapping->mergeStrategy) + : StrategyResolver::for($mapping->destination) + )->merge($stub, $current)->content, + ), + FileMode::Prepend => new ApplyPreview( + $mapping, + $exists, + $current, + PrependMode::prepend($stub, $exists ? $current : null) ?? $current, + ), + }; + } + + /** + * Returns whether an existing `replace` destination is adopted or differs from its recorded hash. + * + * @param string $destPath Absolute path to the existing destination. + * @param LockEntry|null $entry Lock entry of the destination, or `null` when it is untracked. + * + * @throws RuntimeException when the destination cannot be hashed. + * + * @return bool `true` when the tracked destination is adopted or changed since the last apply, `false` otherwise. + */ + private function isUserModified(string $destPath, array|null $entry): bool + { + if ($entry === null) { + return false; + } + + if (($entry['adopted'] ?? false) === true) { + return true; + } + + return Hasher::hash($destPath) !== $entry['hash']; + } +} diff --git a/src/Services/DiffService.php b/src/Services/DiffService.php index 36fe657..10fade1 100644 --- a/src/Services/DiffService.php +++ b/src/Services/DiffService.php @@ -4,146 +4,230 @@ namespace PHPForge\Scaffold\Services; -use PHPForge\Scaffold\Console\{DiffColorizer, ExitCode, OutputWriter}; +use PHPForge\Diff\UnifiedDiffRenderer; +use PHPForge\Scaffold\Config\ProjectContext; +use PHPForge\Scaffold\Console\{DiffColorizer, ExitCode, Message, OutputWriter}; +use PHPForge\Scaffold\Scaffold\ExpectedState; use PHPForge\Scaffold\Scaffold\Lock\LockFile; -use PHPForge\Scaffold\Scaffold\PathResolver; use PHPForge\Scaffold\Security\PathValidator; use RuntimeException; -use SebastianBergmann\Diff\Differ; -use SebastianBergmann\Diff\Output\StrictUnifiedDiffOutputBuilder; - -use function is_file; -use function preg_replace; -use function sprintf; -use function str_ends_with; -use function substr; /** - * Computes and renders a git-style unified diff between a scaffold provider stub and the current on-disk file. + * Renders Git-compatible unified diffs of what applying the provider would change in tracked files. */ final class DiffService { /** - * Builds a git-style unified diff between `$stubContent` and `$currentContent`. - * - * Renders `--- a/$file` and `+++ b/$file` headers followed by `@@ -l,c +l,c @@` hunks with three context lines. - * Lines present only in the stub are prefixed with `-`, and lines present only in the current file with `+`. + * Writes the header and diff of one preview, `no changes`, or the line-ending notice. * - * @param string $stubContent Content from the provider stub file. - * @param string $currentContent Content of the current on-disk file. - * @param string $file Destination path used in the `a/`–`b/` header labels. + * @param ApplyPreview $preview Preview of the destination to render. + * @param OutputWriter $out Output sink. + * @param bool $decorated Whether to wrap the diff lines in ANSI color escape codes. * - * @return string Unified diff output without a trailing newline. Empty string if the contents are identical. + * @return bool `true` when applying the mapping would create or change the destination, `false` otherwise. */ - public function buildDiff(string $stubContent, string $currentContent, string $file): string + public function renderPreview(ApplyPreview $preview, OutputWriter $out, bool $decorated = false): bool { - $stubContent = (string) preg_replace('/\r\n|\r/', "\n", $stubContent); - $currentContent = (string) preg_replace('/\r\n|\r/', "\n", $currentContent); - - // The builder defaults match git: three context lines and collapsed single-line ranges. It returns an empty - // string for identical contents, so only the header labels need configuring. - $differ = new Differ( - new StrictUnifiedDiffOutputBuilder( - [ - 'fromFile' => 'a/' . $file, - 'toFile' => 'b/' . $file, - ], + $file = $preview->mapping->destination; + + if (!$preview->changes()) { + $out->writeStdout( + Message::DIFF_NO_CHANGES->getMessage($file), + ); + + return false; + } + + if ($preview->differsOnlyInLineEndings()) { + $out->writeStdout( + Message::DIFF_LINE_ENDINGS_ONLY->getMessage($file), + ); + + return true; + } + + $suffix = match (true) { + $preview->userModified => Message::FRAGMENT_USER_MODIFIED_PREVIEW->getMessage(), + $preview->informational => Message::FRAGMENT_PRESERVE_PREVIEW->getMessage(), + default => '', + }; + + $out->writeStdout( + Message::DIFF_PREVIEW_HEADER->getMessage( + $file, + $preview->mapping->mode->value, + $preview->mapping->providerName, + $suffix, ), ); - $diff = $differ->diff($stubContent, $currentContent); + $diff = (new UnifiedDiffRenderer()) + ->render($preview->current, $preview->proposed, 'a/' . $file, 'b/' . $file); + + if ($diff === '') { + $out->writeStdout( + Message::DIFF_CREATED_EMPTY->getMessage($file), + ); - // The builder always terminates its output with exactly one newline; strip it because 'writeStdout()' appends - // the final newline itself. - return str_ends_with($diff, "\n") ? substr($diff, 0, -1) : $diff; + return true; + } + + $out->writeStdout( + $decorated ? (new DiffColorizer())->colorize($diff) : $diff, + ); + + return true; } /** - * Renders the diff for `$file` tracked in `scaffold-lock.json`. + * Renders what applying the provider would change in `$file`, or in every tracked, non-ejected file when `$file` + * is `null`, against the current disk content; orphans are reported, not diffed. * - * @param string $projectRoot Absolute path to the project root. - * @param string $vendorDir Absolute path to the Composer vendor directory. - * @param string $file Destination path as recorded in `scaffold-lock.json`. + * @param ProjectContext $context Project to inspect. * @param OutputWriter $out Output sink. + * @param string|null $file Destination path as recorded in `scaffold-lock.json`, or `null` for every file. * @param bool $decorated Whether to wrap the diff lines in ANSI color escape codes. + * @param bool $exitCode Whether to return `1` when applying the provider would change any file. + * + * @throws RuntimeException when the lock file cannot be read. * - * @return int `0` on success, non-zero on unsafe lock entry, missing stub, or I/O failure. + * @return int `1` when the file is not tracked, an entry is unsafe, its provider is not allowed, or a file cannot + * be read, or with `$exitCode` when any file would change; `0` otherwise. */ public function run( - string $projectRoot, - string $vendorDir, - string $file, + ProjectContext $context, OutputWriter $out, + string|null $file = null, bool $decorated = false, + bool $exitCode = false, ): int { - $data = (new LockFile($projectRoot))->read(); - - $entry = $data['files'][$file] ?? null; + $data = (new LockFile($context->projectRoot))->read(); - if ($entry === null) { - $out->writeStderr(sprintf('[scaffold] "%s" is not tracked in scaffold-lock.json.', $file)); + if ($file !== null && !isset($data['files'][$file])) { + $out->writeStderr( + Message::COMMAND_FILE_NOT_TRACKED->getMessage($file), + ); return ExitCode::Error->value; } - $resolved = PathResolver::resolveProviderRoot( - $vendorDir, - $entry['provider'], - $data['providers'][$entry['provider']] ?? null, - $projectRoot, - ); - - $providerRoot = $resolved['root']; + $expected = ExpectedState::build($context, $data['providers']); - if ($resolved['warning'] !== null) { - $out->writeStderr($resolved['warning']); + foreach ($expected->warnings as $warning) { + $out->writeStderr($warning); } $validator = new PathValidator(); + $previewer = new ApplyPreviewer(); - try { - $validator->validateDestination($file, $projectRoot); - $validator->validateSource($entry['source'], $providerRoot); - } catch (RuntimeException $e) { - $out->writeStderr(sprintf('[scaffold] Unsafe lock entry for "%s": %s', $file, $e->getMessage())); + $errors = 0; + $changes = 0; - return ExitCode::Error->value; - } + foreach ($data['files'] as $destination => $entry) { + // PHP turns integer-like destinations ("123") into integer array keys. + $destination = (string) $destination; - $currentPath = PathResolver::destination($projectRoot, $file); + if ($file !== null && $destination !== $file) { + continue; + } - if (is_file($currentPath)) { - $rawCurrent = file_get_contents($currentPath); + if (($entry['ejected'] ?? false) === true) { + if ($file !== null) { + $out->writeStdout( + Message::DIFF_EJECTED->getMessage($file), + ); + } - if ($rawCurrent === false) { - $out->writeStderr(sprintf('[scaffold] Could not read current file "%s".', $currentPath)); + continue; + } - return ExitCode::Error->value; + try { + $validator->validateDestination($destination, $context->projectRoot); + + $mapping = $expected->mapping($destination); + + if ($mapping === null) { + if ($this->reportUnmapped($destination, $entry['provider'], $context, $expected, $out)) { + $errors++; + } + + continue; + } + + $validator->validateSource($mapping->source, $mapping->providerPath); + } catch (RuntimeException $e) { + $out->writeStderr( + Message::COMMAND_UNSAFE_ENTRY->getMessage($destination, $e->getMessage()), + ); + + $errors++; + + continue; } - $currentContent = $rawCurrent; - } else { - $currentContent = ''; - } + try { + $preview = $previewer->preview($mapping, $context->projectRoot, $entry); + } catch (RuntimeException $e) { + $out->writeStderr( + Message::COMMAND_FILE_ERROR->getMessage($destination, $e->getMessage()), + ); + + $errors++; - $stubPath = PathResolver::source($providerRoot, $entry['source']); + continue; + } - if (!is_file($stubPath)) { - $out->writeStderr(sprintf('[scaffold] Stub not found: "%s".', $stubPath)); + if ($this->renderPreview($preview, $out, $decorated)) { + $changes++; + } + } + if ($errors > 0) { return ExitCode::Error->value; } - $stubContent = (string) file_get_contents($stubPath); + return $exitCode && $changes > 0 ? ExitCode::Error->value : ExitCode::Ok->value; + } + + /** + * Reports a tracked file that no allowed and installed provider ships. + * + * @param string $destination Destination path as recorded in `scaffold-lock.json`. + * @param string $provider Provider recorded in the lock entry. + * @param ProjectContext $context Project the entry belongs to. + * @param ExpectedState $expected Expected mappings, used to detect a provider whose manifest failed to load. + * @param OutputWriter $out Output sink. + * + * @return bool `true` when the provider is not allowed or its manifest could not be loaded, `false` when the entry + * is an orphan. + */ + private function reportUnmapped( + string $destination, + string $provider, + ProjectContext $context, + ExpectedState $expected, + OutputWriter $out, + ): bool { + if (!$context->config->isAllowed($provider)) { + $out->writeStderr( + Message::COMMAND_PROVIDER_NOT_ALLOWED->getMessage($destination, $provider), + ); + + return true; + } - $diff = $this->buildDiff($stubContent, $currentContent, $file); + if ($expected->hasFailed($provider)) { + $out->writeStderr( + Message::DIFF_MANIFEST_NOT_LOADED->getMessage($destination, $provider), + ); - if ($diff === '') { - $out->writeStdout('[scaffold] No differences found.'); - } else { - $out->writeStdout($decorated ? (new DiffColorizer())->colorize($diff) : $diff); + return true; } - return ExitCode::Ok->value; + $out->writeStdout( + Message::DIFF_ORPHAN->getMessage($destination), + ); + + return false; } } diff --git a/src/Services/EjectService.php b/src/Services/EjectService.php index 4022b9f..576e609 100644 --- a/src/Services/EjectService.php +++ b/src/Services/EjectService.php @@ -4,61 +4,62 @@ namespace PHPForge\Scaffold\Services; -use PHPForge\Scaffold\Console\{ExitCode, OutputWriter}; +use PHPForge\Scaffold\Console\{ExitCode, Message, OutputWriter}; use PHPForge\Scaffold\Scaffold\Lock\LockFile; -use function sprintf; - /** - * Removes a file entry from `scaffold-lock.json` without deleting the file from disk. + * Marks a file entry as ejected in `scaffold-lock.json` so scaffold stops writing it; the file stays on disk. */ final class EjectService { /** - * Ejects `$file` from the lock file under `$projectRoot`. - * - * Without `$confirmed=true`, only prints what would happen. With it, removes the entry and rewrites the lock. - * The on-disk file is never deleted. + * Marks the entry of `$file` as ejected, or only previews the change when `$confirmed` is `false`. * * @param string $projectRoot Absolute path to the project root. - * @param string $file Destination path as recorded in `scaffold-lock.json`. - * @param bool $confirmed When `true`, performs the ejection. Otherwise only previews. * @param OutputWriter $out Output sink. + * @param string $file Destination path as recorded in `scaffold-lock.json`. + * @param bool $confirmed Whether to write the ejection; `false` only previews it. + * + * @throws \RuntimeException when the lock file cannot be read or written. * - * @return int `0` on success (including previews), non-zero when the entry is not tracked. + * @return int `0` on success, including previews and entries already ejected; `1` when the entry is not tracked. */ - public function run(string $projectRoot, string $file, bool $confirmed, OutputWriter $out): int + public function run(string $projectRoot, OutputWriter $out, string $file, bool $confirmed = false): int { $lock = new LockFile($projectRoot); $data = $lock->read(); if (!isset($data['files'][$file])) { - $out->writeStderr(sprintf('[scaffold] "%s" is not tracked in scaffold-lock.json.', $file)); + $out->writeStderr( + Message::COMMAND_FILE_NOT_TRACKED->getMessage($file), + ); return ExitCode::Error->value; } + if (($data['files'][$file]['ejected'] ?? false) === true) { + $out->writeStdout( + Message::EJECT_ALREADY_EJECTED->getMessage($file), + ); + + return ExitCode::Ok->value; + } + if (!$confirmed) { $out->writeStdout( - sprintf( - '[scaffold] Would remove "%s" from scaffold-lock.json. Run with --yes to confirm.', - $file, - ), + Message::EJECT_CONFIRMATION_REQUIRED->getMessage($file), ); return ExitCode::Ok->value; } - unset($data['files'][$file]); + $data['files'][$file]['ejected'] = true; $lock->write($data); $out->writeStdout( - sprintf( - '[scaffold] Removed "%s" from scaffold-lock.json. The file was not deleted from disk.', - $file, - ), + Message::EJECT_EJECTED->getMessage($file), ); return ExitCode::Ok->value; diff --git a/src/Services/FileStatus.php b/src/Services/FileStatus.php new file mode 100644 index 0000000..c75cd15 --- /dev/null +++ b/src/Services/FileStatus.php @@ -0,0 +1,76 @@ + Every state in summary order, from `synced` to `error`. + */ + public static function summaryOrder(): array + { + return [ + self::Synced, + self::Pending, + self::Outdated, + self::Modified, + self::Conflict, + self::Missing, + self::Orphan, + self::Ejected, + self::Error, + ]; + } +} diff --git a/src/Services/ProvidersService.php b/src/Services/ProvidersService.php index d581ea1..3cb7dc7 100644 --- a/src/Services/ProvidersService.php +++ b/src/Services/ProvidersService.php @@ -4,13 +4,11 @@ namespace PHPForge\Scaffold\Services; -use PHPForge\Scaffold\Console\{ExitCode, OutputWriter}; +use PHPForge\Scaffold\Console\{ExitCode, Message, OutputWriter, Table}; use PHPForge\Scaffold\Scaffold\Lock\LockFile; use function array_fill_keys; use function array_keys; -use function sprintf; -use function str_repeat; /** * Lists scaffold providers recorded in `scaffold-lock.json` with their file counts. @@ -18,21 +16,19 @@ final class ProvidersService { /** - * Returns the `provider-name => file-count` map derived from `scaffold-lock.json` under `$projectRoot`. + * Returns the number of tracked files of every provider recorded in `scaffold-lock.json` under `$projectRoot`. * * @param string $projectRoot Absolute path to the project root. * + * @throws \RuntimeException when the lock file cannot be read. + * * @return array Map of provider package names to the number of files tracked for them. */ public function getProviders(string $projectRoot): array { $data = (new LockFile($projectRoot))->read(); - /** - * Seed with every provider recorded in the lock's top-level map so providers with zero tracked files - * (for example, `append` / `prepend`-only providers scaffolded but not yet registered) still appear in the - * listing. - */ + // Providers whose manifests produced no tracked files still appear, with a count of zero. $providers = array_fill_keys(array_keys($data['providers']), 0); foreach ($data['files'] as $entry) { @@ -49,6 +45,8 @@ public function getProviders(string $projectRoot): array * @param string $projectRoot Absolute path to the project root directory. * @param OutputWriter $out Output sink used for stdout writes. * + * @throws \RuntimeException when the lock file cannot be read. + * * @return int `0` on success. */ public function run(string $projectRoot, OutputWriter $out): int @@ -56,16 +54,23 @@ public function run(string $projectRoot, OutputWriter $out): int $providers = $this->getProviders($projectRoot); if ($providers === []) { - $out->writeStdout('[scaffold] No providers tracked in scaffold-lock.json.'); + $out->writeStdout( + Message::PROVIDERS_NONE->getMessage(), + ); return ExitCode::Ok->value; } - $out->writeStdout(sprintf('%-44s %s', 'Provider', 'Files')); - $out->writeStdout(str_repeat('-', 52)); + $rows = []; foreach ($providers as $name => $count) { - $out->writeStdout(sprintf('%-44s %d', $name, $count)); + $rows[] = [$name, (string) $count]; + } + + foreach (Table::render(['Provider', 'Files'], $rows) as $line) { + $out->writeStdout( + $line, + ); } return ExitCode::Ok->value; diff --git a/src/Services/PruneService.php b/src/Services/PruneService.php new file mode 100644 index 0000000..6849e65 --- /dev/null +++ b/src/Services/PruneService.php @@ -0,0 +1,370 @@ +projectRoot); + + $data = $lock->read(); + + $expected = ExpectedState::build($context, $data['providers']); + + foreach ($expected->warnings as $warning) { + $out->writeStderr($warning); + } + + $errors = count($expected->failedProviders()); + + /** @var array $rows */ + $rows = []; + + foreach ($expected->orphans($data['files']) as $destination => $entry) { + // PHP turns integer-like destinations ("123") into integer array keys. + $disk = $this->diskState((string) $destination, $entry, $context->projectRoot); + + if ($disk === self::ERROR) { + $errors++; + } + + $rows[$destination] = [ + 'provider' => $entry['provider'], + 'disk' => $disk, + 'action' => self::action($disk, $deleteModified), + ]; + } + + if ($rows === []) { + if ($force && $this->dropStaleProviders($data, $context)) { + $lock->write($data); + } + + $out->writeStdout( + Message::PRUNE_NO_ORPHANS->getMessage(), + ); + + return $errors > 0 ? ExitCode::Error->value : ExitCode::Ok->value; + } + + if (!$force) { + $this->renderTable($rows, $out); + + $counts = self::count($rows); + + $out->writeStdout( + Message::PRUNE_DRY_RUN_SUMMARY->getMessage( + $counts['removed'], + $counts['kept'], + $errors, + Message::plural($errors, Message::FRAGMENT_ERROR, Message::FRAGMENT_ERRORS), + ), + ); + + return $errors > 0 || $exitCode ? ExitCode::Error->value : ExitCode::Ok->value; + } + + $removed = 0; + $kept = 0; + + foreach ($rows as $key => $row) { + // PHP turns integer-like destinations ("123") into integer array keys. + $file = (string) $key; + + if ($row['action'] === 'delete' || $row['action'] === 'delete (modified)') { + if (!$this->delete($file, $context->projectRoot, $out)) { + $errors++; + + continue; + } + + $out->writeStdout( + Message::PRUNE_DELETED->getMessage( + $file, + $row['disk'] === self::UNMODIFIED + ? '' + : Message::FRAGMENT_PARENTHESIZED->getMessage($row['disk']), + ), + ); + $removed++; + } elseif ($row['action'] === 'keep') { + $out->writeStdout( + Message::PRUNE_KEPT->getMessage($file, $row['disk']), + ); + + $kept++; + } else { + $out->writeStdout( + Message::PRUNE_ENTRY_DROPPED->getMessage($file, $row['disk']), + ); + + $removed++; + } + + unset($data['files'][$file]); + } + + $this->dropStaleProviders($data, $context); + + $lock->write($data); + + $out->writeStdout( + Message::PRUNE_SUMMARY->getMessage( + $removed, + $kept, + $errors, + Message::plural($errors, Message::FRAGMENT_ERROR, Message::FRAGMENT_ERRORS), + ), + ); + + return $errors > 0 ? ExitCode::Error->value : ExitCode::Ok->value; + } + + /** + * Returns what `--force` does with an orphan in disk state `$disk`. + * + * @param string $disk Disk state of the orphan, as returned by {@see self::diskState()}. + * @param bool $deleteModified Whether `--force` also deletes orphan files that hold consumer content. + * + * @return string Action shown in the table: `delete`, `delete (modified)`, `drop entry` or `keep`. + */ + private static function action(string $disk, bool $deleteModified): string + { + return match ($disk) { + self::UNMODIFIED => 'delete', + 'missing', 'unsafe' => 'drop entry', + self::ERROR => 'keep', + default => $deleteModified ? 'delete (modified)' : 'keep', + }; + } + + /** + * Returns the number of orphans that `--force` would remove and keep. + * + * @param array $rows Orphan rows keyed by + * destination. + * + * @return array{removed: int, kept: int} Number of orphans that `--force` would remove and keep. + */ + private static function count(array $rows): array + { + $kept = 0; + + foreach ($rows as $row) { + if ($row['action'] === 'keep') { + $kept++; + } + } + + return [ + 'removed' => count($rows) - $kept, + 'kept' => $kept, + ]; + } + + /** + * Deletes an orphan file and the empty parent directories it leaves behind, up to the project root. + * + * @param string $file Destination of the orphan, relative to `$projectRoot`. + * @param string $projectRoot Absolute path to the project root. + * @param OutputWriter $out Output sink for deletion failures. + * + * @return bool `true` when the file was deleted, even if an empty parent directory could not be removed; `false` + * otherwise. + */ + private function delete(string $file, string $projectRoot, OutputWriter $out): bool + { + $path = PathResolver::destination($projectRoot, $file); + + try { + Filesystem::remove($path, Message::PRUNE_FILE_DELETE_FAILED->getMessage($path)); + } catch (RuntimeException $e) { + $out->writeStderr( + $e->getMessage(), + ); + + return false; + } + + // The relative parents end at `.`, the project root, which is never removed. + $parent = dirname($file); + + try { + while ($parent !== '.') { + $dir = PathResolver::destination($projectRoot, $parent); + $failure = Message::PRUNE_DIRECTORY_REMOVE_FAILED->getMessage($dir); + + if (is_link($dir) || !Filesystem::isEmptyDirectory($dir, $failure)) { + break; + } + + Filesystem::removeDirectory($dir, $failure); + + $parent = dirname($parent); + } + } catch (RuntimeException $e) { + $out->writeStderr( + $e->getMessage(), + ); + } + + return true; + } + + /** + * Returns the disk state of an orphan: `unmodified` when the file holds only the provider content recorded at the + * last apply, `modified`, `merged` (append or prepend content mixed with consumer content), `adopted`, `missing`, + * `unsafe` when the destination fails validation, or `error` when it cannot be read. + * + * @param string $destination Destination path as recorded in `scaffold-lock.json`. + * @param LockEntry $entry Lock entry of the orphan. + * @param string $projectRoot Absolute path to the project root. + * + * @return string Disk state: `unmodified`, `modified`, `merged`, `adopted`, `missing`, `unsafe` or `error`. + */ + private function diskState(string $destination, array $entry, string $projectRoot): string + { + try { + (new PathValidator()) + ->validateDestination($destination, $projectRoot); + } catch (RuntimeException) { + return 'unsafe'; + } + + $path = PathResolver::destination($projectRoot, $destination); + + if (!file_exists($path)) { + return 'missing'; + } + + if (($entry['adopted'] ?? false) === true) { + return 'adopted'; + } + + try { + $hash = Hasher::hash($path); + } catch (RuntimeException) { + return self::ERROR; + } + + if ($hash !== $entry['hash']) { + return 'modified'; + } + + $merged = $entry['mode'] === FileMode::Append->value || $entry['mode'] === FileMode::Prepend->value; + + // An append or prepend file holds only provider bytes when it equals the stub recorded at the last apply. + if ($merged && $hash !== ($entry['stub-hash'] ?? '')) { + return 'merged'; + } + + return self::UNMODIFIED; + } + + /** + * Removes from the lock `providers` map the providers that have no file entry left and are no longer allowed or + * installed. + * + * @param array{providers: array, files: array} $data Lock data, updated in + * place. + * @param ProjectContext $context Project whose allowed and installed providers are kept. + * + * @return bool `true` when a provider was removed, `false` otherwise. + */ + private function dropStaleProviders(array &$data, ProjectContext $context): bool + { + $owners = array_column($data['files'], 'provider'); + + $dropped = false; + + foreach ($data['providers'] as $name => $info) { + if ( + in_array($name, $owners, true) + || ($context->config->isAllowed($name) && $context->isInstalled($name, $info)) + ) { + continue; + } + + unset($data['providers'][$name]); + + $dropped = true; + } + + return $dropped; + } + + /** + * Writes the orphan table. + * + * @param array $rows Orphan rows keyed by + * destination. + * @param OutputWriter $out Output sink. + */ + private function renderTable(array $rows, OutputWriter $out): void + { + $cells = []; + + foreach ($rows as $file => $row) { + $cells[] = [(string) $file, $row['provider'], $row['disk'], $row['action']]; + } + + foreach (Table::render(['File', 'Provider', 'Disk', 'With --force'], $cells) as $line) { + $out->writeStdout( + $line, + ); + } + } +} diff --git a/src/Services/ReapplyService.php b/src/Services/ReapplyService.php index 48c1c41..e5bbbd3 100644 --- a/src/Services/ReapplyService.php +++ b/src/Services/ReapplyService.php @@ -4,49 +4,69 @@ namespace PHPForge\Scaffold\Services; -use PHPForge\Scaffold\Console\{ExitCode, OutputWriter}; +use PHPForge\Scaffold\Config\ProjectContext; +use PHPForge\Scaffold\Console\{ExitCode, Message, OutputWriter}; +use PHPForge\Scaffold\Exception\Message as ExceptionMessage; +use PHPForge\Scaffold\Filesystem; +use PHPForge\Scaffold\Manifest\{FileMapping, FileMode}; +use PHPForge\Scaffold\Merge\MergeStrategyKind; +use PHPForge\Scaffold\Scaffold\ExpectedState; use PHPForge\Scaffold\Scaffold\Lock\{Hasher, LockFile}; +use PHPForge\Scaffold\Scaffold\Modes\{AppendMode, ApplyOutcome, PrependMode, ReplaceMode}; use PHPForge\Scaffold\Scaffold\PathResolver; use PHPForge\Scaffold\Security\PathValidator; use RuntimeException; use Throwable; +use function file_exists; use function is_file; -use function sprintf; /** - * Re-applies scaffold stubs to the project, optionally overwriting user-modified files. + * Rewrites tracked files from their provider stubs; without `force` it merges `append` and `prepend` files and skips + * ejected, adopted, user-modified and existing `preserve` files; it always skips orphaned files. * - * Framework-free: invoked by both the console controller wrapper and the Symfony Console command. + * @phpstan-import-type LockEntry from LockFile */ final class ReapplyService { /** - * Re-applies scaffold stubs under the given constraints. + * Reapplies the tracked files that match the filters and records their new hashes in `scaffold-lock.json`, or only + * prints what would change with `$dryRun`, ending with a summary line. * - * @param string $projectRoot Absolute path to the project root. - * @param string $vendorDir Absolute path to the Composer vendor directory. - * @param string $file Optional destination path filter (empty string = all). - * @param string $provider Optional provider package name filter (empty string = all). - * @param bool $force When `true`, overwrites user-modified files without prompting. + * @param ProjectContext $context Project to reapply. * @param OutputWriter $out Output sink. + * @param string $file Destination path to reapply, or an empty string for every tracked file. + * @param string $provider Provider package name to reapply, or an empty string for every provider. + * @param bool $force Whether to overwrite every matching file with its stub, including ejected, adopted, + * user-modified, `preserve`, `append` and `prepend` files, and to clear the `ejected` and `adopted` flags. + * @param bool $dryRun Whether to print the diff of every file that would change instead of writing anything. + * @param bool $exitCode Whether a dry run returns `1` when any file would change. + * + * @throws RuntimeException when the lock file cannot be read or written. * - * @return int `0` on success (including no-op), non-zero when a file/provider filter matched nothing. + * @return int `1` when a filter matches no tracked file or an entry was skipped for an error (unsafe entry, + * provider not allowed, missing stub, unknown mode, read, hash or write failure), or with `$dryRun` and `$exitCode` + * when any file would change; `0` otherwise, including user-modified, `preserve`, ejected and orphaned skips. */ public function run( - string $projectRoot, - string $vendorDir, - string $file, - string $provider, - bool $force, + ProjectContext $context, OutputWriter $out, + string $file = '', + string $provider = '', + bool $force = false, + bool $dryRun = false, + bool $exitCode = false, ): int { + $projectRoot = $context->projectRoot; + $lock = new LockFile($projectRoot); $data = $lock->read(); - $hasher = new Hasher(); + $expected = ExpectedState::build($context, $data['providers']); + $validator = new PathValidator(); + $summary = new ReapplySummary(); $updatedFiles = $data['files']; @@ -54,6 +74,9 @@ public function run( $anyMatched = false; foreach ($data['files'] as $destination => $entry) { + // PHP turns integer-like destinations ("123") into integer array keys. + $destination = (string) $destination; + if ($file !== '' && $destination !== $file) { continue; } @@ -64,12 +87,17 @@ public function run( $anyMatched = true; - $resolved = PathResolver::resolveProviderRoot( - $vendorDir, - $entry['provider'], - $data['providers'][$entry['provider']] ?? null, - $projectRoot, - ); + if (!$context->config->isAllowed($entry['provider'])) { + $out->writeStderr( + Message::COMMAND_PROVIDER_NOT_ALLOWED->getMessage($destination, $entry['provider']), + ); + + $summary->errors++; + + continue; + } + + $resolved = $context->providerRoot($entry['provider'], $data['providers'][$entry['provider']] ?? null); $providerRoot = $resolved['root']; @@ -79,129 +107,342 @@ public function run( try { $validator->validateDestination($destination, $projectRoot); - $validator->validateSource($entry['source'], $providerRoot); } catch (RuntimeException $e) { $out->writeStderr( - sprintf('[scaffold] Unsafe lock entry for "%s": %s Skipping.', $destination, $e->getMessage()), + Message::REAPPLY_UNSAFE_ENTRY->getMessage($destination, $e->getMessage()), ); + $summary->errors++; + continue; } - $mode = $entry['mode']; + if (!$force && ($entry['ejected'] ?? false) === true) { + $out->writeStderr( + Message::REAPPLY_EJECTED->getMessage($destination), + ); + $summary->skip('ejected'); + + continue; + } + + if ($expected->mapping($destination) === null && !$expected->hasFailed($entry['provider'])) { + $out->writeStderr( + Message::REAPPLY_ORPHANED->getMessage($destination), + ); + $summary->skip('orphaned'); + + continue; + } - if ($mode === 'append' || $mode === 'prepend') { - $out->writeStdout( - sprintf( - '[scaffold] "%s" uses mode "%s" and cannot be safely reapplied; run composer install instead.', - $destination, - $mode, - ), + try { + // The source is validated after the orphan check: the root of an uninstalled provider does not exist. + $validator->validateSource($entry['source'], $providerRoot); + } catch (RuntimeException $e) { + $out->writeStderr( + Message::REAPPLY_UNSAFE_ENTRY->getMessage($destination, $e->getMessage()), ); + $summary->errors++; + continue; } + $merge = !$force + && ($entry['mode'] === FileMode::Append->value || $entry['mode'] === FileMode::Prepend->value); $destPath = PathResolver::destination($projectRoot, $destination); $stubPath = PathResolver::source($providerRoot, $entry['source']); - if ($mode === 'preserve' && !$force && is_file($destPath)) { - $out->writeStdout( - sprintf('[scaffold] "%s" uses mode "preserve". Use --force to overwrite.', $destination), + if (!$force && $entry['mode'] === FileMode::Preserve->value && is_file($destPath)) { + $out->writeStderr( + Message::REAPPLY_PRESERVE->getMessage($destination), ); + $summary->skip('preserve'); continue; } if (!is_file($stubPath)) { - $out->writeStderr(sprintf('[scaffold] Stub not found: "%s". Skipping.', $stubPath)); + $out->writeStderr( + Message::REAPPLY_STUB_NOT_FOUND->getMessage($stubPath), + ); + + $summary->errors++; continue; } - if (!$force && is_file($destPath)) { - try { - $currentHash = $hasher->hash($destPath); - } catch (Throwable $e) { + try { + $mapping = self::mapping($destination, $entry, $providerRoot, $merge, $out); + + if (!$merge && !$force && self::isUserModified($destPath, $entry)) { $out->writeStderr( - sprintf('[scaffold] Could not hash "%s": %s Skipping.', $destination, $e->getMessage()), + Message::REAPPLY_USER_MODIFIED->getMessage($destination), ); + $summary->skip('user-modified'); continue; } - if (!$hasher->equals($currentHash, $entry['hash'])) { - $out->writeStdout( - sprintf( - '[scaffold] "%s" is user-modified. Use --force to overwrite.', - $destination, - ), - ); + if ($dryRun) { + $preview = $merge + ? (new ApplyPreviewer())->preview($mapping, $projectRoot, $entry) + : self::stubPreview($mapping, $destPath, $stubPath); + + if ((new DiffService())->renderPreview($preview, $out)) { + $summary->written++; + } else { + $summary->unchanged++; + } continue; } - } - $stubContent = file_get_contents($stubPath); + $updated = $merge + ? $this->merge($mapping, $entry, $projectRoot, $stubPath, $summary, $out) + : $this->write($mapping, $entry, $projectRoot, $destPath, $summary, $out); + } catch (Throwable $e) { + $out->writeStderr( + Message::REAPPLY_FAILED->getMessage($destination, $e->getMessage()), + ); - if ($stubContent === false) { - $out->writeStderr(sprintf('[scaffold] Could not read stub "%s". Skipping.', $stubPath)); + $summary->errors++; continue; } - try { - PathResolver::ensureDirectory($destPath); - } catch (RuntimeException $e) { - $out->writeStderr(sprintf('[scaffold] %s Skipping.', $e->getMessage())); - - continue; + if ($updated !== $entry) { + $updatedFiles[$destination] = $updated; + $anyUpdated = true; } + } - if (file_put_contents($destPath, $stubContent) === false) { - $out->writeStderr(sprintf('[scaffold] Could not write "%s". Skipping.', $destPath)); + if (($file !== '' || $provider !== '') && !$anyMatched) { + $out->writeStderr( + Message::REAPPLY_NO_MATCH->getMessage(), + ); - continue; - } + return ExitCode::Error->value; + } - PathResolver::syncPermissions($stubPath, $destPath); + if ($anyUpdated && !$dryRun) { + $lock->write(['providers' => $data['providers'], 'files' => $updatedFiles]); + } - try { - $newHash = $hasher->hash($destPath); - } catch (Throwable $e) { + $out->writeStdout( + $summary->line($dryRun), + ); + + if ($summary->errors > 0) { + return ExitCode::Error->value; + } + + return $dryRun && $exitCode && $summary->written > 0 ? ExitCode::Error->value : ExitCode::Ok->value; + } + + /** + * Returns the entry with new hashes, without `ejected` and `adopted`, keeping `merge`. + * + * @param LockEntry $entry Current lock entry. + * @param string $hash Destination hash after the write. + * @param string $stubHash Provider source hash. + * + * @return LockEntry Updated entry. + */ + private static function entry(array $entry, string $hash, string $stubHash): array + { + $updated = [ + 'hash' => $hash, + 'provider' => $entry['provider'], + 'source' => $entry['source'], + 'mode' => $entry['mode'], + 'stub-hash' => $stubHash, + ]; + + if (isset($entry['merge'])) { + $updated['merge'] = $entry['merge']; + } + + return $updated; + } + + /** + * Returns whether an existing destination is adopted or differs from its recorded hash. + * + * @param string $destPath Absolute path to the destination. + * @param LockEntry $entry Lock entry of the destination. + * + * @throws RuntimeException when the destination cannot be hashed. + * + * @return bool `true` when the destination is a file that is adopted or changed since the last apply, `false` + * otherwise. + */ + private static function isUserModified(string $destPath, array $entry): bool + { + return is_file($destPath) + && (($entry['adopted'] ?? false) === true || Hasher::hash($destPath) !== $entry['hash']); + } + + /** + * Builds the mapping of a lock entry, warning about an unknown recorded merge strategy of a merged entry. + * + * @param string $destination Destination path relative to the project root. + * @param LockEntry $entry Lock entry of the destination. + * @param string $providerRoot Absolute path to the provider root. + * @param bool $merge Whether the entry is merged with its `append` or `prepend` mode. + * @param OutputWriter $out Output sink for the unknown merge strategy warning. + * + * @throws RuntimeException when the recorded mode is unknown. + * + * @return FileMapping Mapping of the entry, without a merge strategy when it is not merged or none or an unknown + * one is recorded. + */ + private static function mapping( + string $destination, + array $entry, + string $providerRoot, + bool $merge, + OutputWriter $out, + ): FileMapping { + $strategy = null; + + if ($merge && isset($entry['merge'])) { + $strategy = MergeStrategyKind::tryFrom($entry['merge']); + + if ($strategy === null) { $out->writeStderr( - sprintf( - '[scaffold] Could not hash written file "%s": %s Skipping lock update.', - $destination, - $e->getMessage(), - ), + Message::REAPPLY_MERGE_STRATEGY_UNKNOWN->getMessage($entry['merge'], $destination), ); - - continue; } + } - $updatedFiles[$destination] = [ - 'hash' => $newHash, - 'provider' => $entry['provider'], - 'source' => $entry['source'], - 'mode' => $entry['mode'], - ]; + return new FileMapping( + $destination, + $entry['source'], + FileMode::tryFrom($entry['mode']) + ?? throw new RuntimeException(ExceptionMessage::LOCK_MODE_UNKNOWN->getMessage($entry['mode'])), + $entry['provider'], + $providerRoot, + $strategy, + ); + } - $anyUpdated = true; + /** + * Runs the `append` or `prepend` mode for a lock entry, reports the outcome, and refreshes the entry `stub-hash`. + * + * @param FileMapping $mapping Mapping of the entry. + * @param LockEntry $entry Lock entry of the destination. + * @param string $projectRoot Absolute path to the project root. + * @param string $stubPath Absolute path to the provider stub. + * @param ReapplySummary $summary Run counters, updated in place. + * @param OutputWriter $out Output sink. + * + * @throws RuntimeException when a file cannot be read, written or hashed, or a directory cannot be created. + * + * @return LockEntry Entry to record. + */ + private function merge( + FileMapping $mapping, + array $entry, + string $projectRoot, + string $stubPath, + ReapplySummary $summary, + OutputWriter $out, + ): array { + $mode = $mapping->mode === FileMode::Append ? new AppendMode() : new PrependMode(); - $out->writeStdout(sprintf('[scaffold] Reapplied "%s".', $destination)); - } + $result = $mode->apply($mapping, $projectRoot, $entry['hash']); + $stubHash = Hasher::hash($stubPath); - if (($file !== '' || $provider !== '') && !$anyMatched) { - $out->writeStderr('[scaffold] No tracked files matched the given filter.'); + if ($result->outcome === ApplyOutcome::Written) { + $out->writeStdout( + Message::REAPPLY_APPLIED->getMessage($mapping->destination), + ); - return ExitCode::Error->value; + $summary->written++; + + return self::entry($entry, $result->newHash, $stubHash); } - if ($anyUpdated) { - $lock->write(['providers' => $data['providers'], 'files' => $updatedFiles]); + $out->writeStdout( + Message::REAPPLY_ALREADY_UP_TO_DATE->getMessage($mapping->destination), + ); + + $summary->unchanged++; + + $updated = $entry; + $updated['stub-hash'] = $stubHash; + + return $updated; + } + + /** + * Returns the preview of a stub write that a dry run skips. + * + * @param FileMapping $mapping Mapping of the entry. + * @param string $destPath Absolute path to the destination. + * @param string $stubPath Absolute path to the provider stub. + * + * @throws RuntimeException when the destination or the stub cannot be read. + * + * @return ApplyPreview Current destination content and the stub content that the write would copy. + */ + private static function stubPreview(FileMapping $mapping, string $destPath, string $stubPath): ApplyPreview + { + $exists = is_file($destPath); + + return new ApplyPreview( + $mapping, + $exists, + $exists + ? Filesystem::read($destPath, ExceptionMessage::SERVICE_CURRENT_FILE_UNREADABLE->getMessage($destPath)) + : '', + Filesystem::read($stubPath, ExceptionMessage::SERVICE_STUB_UNREADABLE->getMessage($stubPath)), + ); + } + + /** + * Overwrites the destination with its stub through the `replace` mode and reports the write. + * + * @param FileMapping $mapping Mapping of the entry. + * @param LockEntry $entry Lock entry of the destination. + * @param string $projectRoot Absolute path to the project root. + * @param string $destPath Absolute path to the destination. + * @param ReapplySummary $summary Run counters, updated in place. + * @param OutputWriter $out Output sink. + * + * @throws RuntimeException when a file cannot be copied or hashed, or a directory cannot be created. + * + * @return LockEntry Entry to record. + */ + private function write( + FileMapping $mapping, + array $entry, + string $projectRoot, + string $destPath, + ReapplySummary $summary, + OutputWriter $out, + ): array { + // The destination is pristine or forced: passing its current hash lets the stub overwrite it without warning. + $result = (new ReplaceMode())->apply( + $mapping, + $projectRoot, + file_exists($destPath) ? Hasher::hash($destPath) : null, + ); + + if ($result->warning !== null) { + $out->writeStderr( + Message::SCAFFOLD_PREFIXED->getMessage($result->warning), + ); } - return ExitCode::Ok->value; + $summary->written++; + + $out->writeStdout( + Message::REAPPLY_APPLIED->getMessage($mapping->destination), + ); + + // The destination is now a copy of the stub, so both hashes are the hash of the stub. + return self::entry($entry, $result->newHash, $result->newHash); } } diff --git a/src/Services/ReapplySummary.php b/src/Services/ReapplySummary.php new file mode 100644 index 0000000..5de74b3 --- /dev/null +++ b/src/Services/ReapplySummary.php @@ -0,0 +1,74 @@ + Number of entries skipped without an error, keyed by reason (`ejected`, `orphaned`, + * `preserve`, `user-modified`), in first-seen order. + */ + public array $skipped = []; + /** + * Number of entries whose destination already matched. + */ + public int $unchanged = 0; + /** + * Number of entries written, or that a dry run would write. + */ + public int $written = 0; + + /** + * Returns the summary line, such as `[scaffold] reapply: 3 written, 7 unchanged, 1 skipped (user-modified), 0 + * errors.`. + * + * @param bool $dryRun Whether the run only previewed the changes. + * + * @return string Summary line prefixed with `[scaffold]`. + */ + public function line(bool $dryRun = false): string + { + $skipped = array_sum($this->skipped); + + $reasons = []; + + foreach ($this->skipped as $reason => $count) { + $reasons[] = $count === $skipped ? $reason : Message::FRAGMENT_COUNT->getMessage($count, $reason); + } + + return Message::REAPPLY_SUMMARY->getMessage( + $dryRun ? Message::FRAGMENT_DRY_RUN->getMessage() : '', + $this->written, + $dryRun ? Message::FRAGMENT_WOULD_BE_WRITTEN->getMessage() : Message::FRAGMENT_WRITTEN->getMessage(), + $this->unchanged, + $skipped, + $reasons === [] ? '' : Message::FRAGMENT_PARENTHESIZED->getMessage(implode(', ', $reasons)), + $this->errors, + Message::plural($this->errors, Message::FRAGMENT_ERROR, Message::FRAGMENT_ERRORS), + ); + } + + /** + * Counts an entry skipped without an error. + * + * @param string $reason Skip reason: `ejected`, `orphaned`, `preserve` or `user-modified`. + */ + public function skip(string $reason): void + { + $this->skipped[$reason] = ($this->skipped[$reason] ?? 0) + 1; + } +} diff --git a/src/Services/StatusService.php b/src/Services/StatusService.php index 9627968..9217f9b 100644 --- a/src/Services/StatusService.php +++ b/src/Services/StatusService.php @@ -4,121 +4,381 @@ namespace PHPForge\Scaffold\Services; -use PHPForge\Scaffold\Console\{ExitCode, OutputWriter}; +use JsonException; +use PHPForge\Scaffold\Config\ProjectContext; +use PHPForge\Scaffold\Console\{ExitCode, Message as ConsoleMessage, OutputWriter, Table}; +use PHPForge\Scaffold\Exception\Message; +use PHPForge\Scaffold\Manifest\{FileMapping, FileMode}; +use PHPForge\Scaffold\Scaffold\ExpectedState; use PHPForge\Scaffold\Scaffold\Lock\{Hasher, LockFile}; use PHPForge\Scaffold\Scaffold\PathResolver; use PHPForge\Scaffold\Security\PathValidator; use RuntimeException; use Throwable; -use function max; -use function sprintf; -use function str_repeat; +use function array_column; +use function array_count_values; +use function array_diff; +use function array_filter; +use function count; +use function file_exists; +use function implode; +use function in_array; +use function is_array; +use function is_string; +use function json_encode; /** - * Computes the sync status of scaffold-tracked files relative to `scaffold-lock.json`. + * Reports the state of each file tracked in `scaffold-lock.json` against the disk and the current provider stubs, and + * the provider files not tracked yet as `pending`. + * + * @phpstan-import-type LockEntry from LockFile */ final class StatusService { /** - * Returns status data for all files tracked in `scaffold-lock.json` under `$projectRoot`. + * Renders the status of all files tracked in `scaffold-lock.json` of the project, as a table followed by a + * summary line or as a JSON document, with notices and provider version drift on stderr. * - * Each entry maps the destination path to a status record containing the provider name, the scaffold mode, and - * one of: `synced`, `modified`, `missing`, or `error`. + * @param ProjectContext $context Project to inspect. + * @param OutputWriter $out Output sink. + * @param bool $json Whether to print only the JSON document on stdout. + * @param bool $exitCode Whether to return `1` when any file is neither `synced` nor `ejected`, `pending` included. * + * @throws RuntimeException when the lock file cannot be read or the JSON document cannot be encoded. + * + * @return int `1` when any file is in the `error` state, or with `$exitCode` when any file is neither `synced` nor + * `ejected`; `0` otherwise. + */ + public function run(ProjectContext $context, OutputWriter $out, bool $json = false, bool $exitCode = false): int + { + $report = $this->evaluate($context); + + foreach ($report['notices'] as $notice) { + $out->writeStderr( + $notice, + ); + } + + $statuses = $report['files']; + $counts = self::count($statuses); + + if ($json) { + $out->writeStdout( + self::encodeJson($statuses, $report['providers'], $counts), + ); + } else { + foreach ($report['providers'] as $name => $versions) { + $drifted = $versions['lock'] !== null + && $versions['installed'] !== null + && $versions['lock'] !== $versions['installed']; + + if ($drifted) { + $out->writeStderr( + ConsoleMessage::STATUS_PROVIDER_DRIFT->getMessage( + $name, + $versions['lock'], + $versions['installed'], + ), + ); + } + } + + $this->renderTable($statuses, $counts, $out); + } + + $states = array_column($statuses, 'status'); + + if (in_array(FileStatus::Error->value, $states, true)) { + return ExitCode::Error->value; + } + + $unclean = array_diff($states, [FileStatus::Synced->value, FileStatus::Ejected->value]); + + return $exitCode && $unclean !== [] ? ExitCode::Error->value : ExitCode::Ok->value; + } + + /** + * Compares an existing destination with its lock entry and the current stub. + * + * @param string $destPath Absolute path to the existing destination. + * @param LockEntry $entry Lock entry of the destination. + * @param FileMapping $mapping Expected mapping of the destination. * @param string $projectRoot Absolute path to the project root. + * @param int $lackingStubHash Number of `replace`/`preserve` entries without `stub-hash`, incremented in place. * - * @return array An associative array of file - * statuses keyed by their destination paths. + * @throws RuntimeException when a file cannot be read or hashed, or the stub is missing. + * + * @return FileStatus `synced`, `outdated`, `modified` or `conflict`. */ - public function getStatuses(string $projectRoot): array + private function compare( + string $destPath, + array $entry, + FileMapping $mapping, + string $projectRoot, + int &$lackingStubHash, + ): FileStatus { + if ($mapping->mode === FileMode::Append || $mapping->mode === FileMode::Prepend) { + return (new ApplyPreviewer()) + ->preview($mapping, $projectRoot, $entry)->changes() + ? FileStatus::Outdated + : FileStatus::Synced; + } + + $stubPath = PathResolver::source($mapping->providerPath, $mapping->source); + + $stubHash = Hasher::hash($stubPath); + $destHash = Hasher::hash($destPath); + $lockMatches = $destHash === $entry['hash']; + + if (isset($entry['stub-hash'])) { + $stubChanged = $stubHash !== $entry['stub-hash']; + } else { + $lackingStubHash++; + + // Without a recorded stub hash, an unmodified replace file is outdated exactly when it differs from the + // current stub. + $stubChanged = $mapping->mode === FileMode::Replace + && $lockMatches + && $destHash !== $stubHash; + } + + if (!$lockMatches) { + return $mapping->mode === FileMode::Replace && $stubChanged ? FileStatus::Conflict : FileStatus::Modified; + } + + return $stubChanged ? FileStatus::Outdated : FileStatus::Synced; + } + + /** + * Returns the number of files in each state, keyed by state value in summary order. + * + * @param array $statuses File statuses. + * + * @return array Counts keyed by state value. + */ + private static function count(array $statuses): array { - $lock = new LockFile($projectRoot); + $tally = array_count_values(array_column($statuses, 'status')); - $data = $lock->read(); + $counts = []; - $hasher = new Hasher(); - $validator = new PathValidator(); + foreach (FileStatus::summaryOrder() as $state) { + $counts[$state->value] = $tally[$state->value] ?? 0; + } + + return $counts; + } - $result = []; + /** + * Encodes the status report as a pretty-printed JSON document. + * + * @param array $statuses File statuses. + * @param array $providers Provider versions. + * @param array $counts Counts keyed by state value. + * + * @throws RuntimeException when the document cannot be encoded. + * + * @return string JSON document with the `files`, `providers` and `summary` sections. + */ + private static function encodeJson(array $statuses, array $providers, array $counts): string + { + try { + return json_encode( + [ + 'files' => (object) $statuses, + 'providers' => (object) $providers, + 'summary' => ['total' => count($statuses), ...$counts], + ], + JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR, + ); + } catch (JsonException $e) { + throw new RuntimeException( + Message::SERVICE_STATUS_ENCODE_FAILED->getMessage($e->getMessage()), + 0, + $e, + ); + } + } + + /** + * Evaluates every lock entry against the disk, the expected provider mappings and the current stubs. + * + * @param ProjectContext $context Project to evaluate. + * + * @return array{ + * files: array, + * providers: array, + * notices: list, + * } File statuses, provider versions from the lock and the installed packages, and stderr notices. + */ + private function evaluate(ProjectContext $context): array + { + $data = (new LockFile($context->projectRoot))->read(); + + $providers = []; + + foreach ($data['providers'] as $name => $info) { + $version = is_array($info) ? ($info['version'] ?? null) : null; + + $providers[$name] = [ + 'lock' => is_string($version) ? $version : null, + 'installed' => $context->installed->version($name), + ]; + } + + $expected = ExpectedState::build($context, $data['providers']); + + $notices = $expected->warnings; + $files = []; + $lackingStubHash = 0; foreach ($data['files'] as $destination => $entry) { - try { - $validator->validateDestination($destination, $projectRoot); - } catch (RuntimeException) { - $result[$destination] = [ - 'provider' => $entry['provider'], - 'mode' => $entry['mode'], - 'status' => 'error', - ]; + // PHP turns integer-like destinations ("123") into integer array keys. + $destination = (string) $destination; - continue; - } + $mapping = $expected->mapping($destination); - $absolutePath = PathResolver::destination($projectRoot, $destination); + $unmapped = $mapping === null && ($entry['ejected'] ?? false) !== true; - if (!file_exists($absolutePath)) { - $status = 'missing'; - } else { - try { - $currentHash = $hasher->hash($absolutePath); - $status = $hasher->equals($currentHash, $entry['hash']) ? 'synced' : 'modified'; - } catch (Throwable) { - $status = 'error'; - } + if ($unmapped && !$context->config->isAllowed($entry['provider'])) { + $notices[] = ConsoleMessage::COMMAND_PROVIDER_NOT_ALLOWED->getMessage($destination, $entry['provider']); } - $result[$destination] = [ + $status = $this->evaluateEntry($destination, $entry, $mapping, $expected, $context, $lackingStubHash); + + $files[$destination] = [ 'provider' => $entry['provider'], 'mode' => $entry['mode'], - 'status' => $status, + 'status' => $status->value, ]; } - return $result; + foreach ($expected->all() as $mapping) { + $destination = $mapping->destination; + + if (!isset($data['files'][$destination])) { + $files[$destination] = [ + 'provider' => $mapping->providerName, + 'mode' => $mapping->mode->value, + 'status' => FileStatus::Pending->value, + ]; + } + } + + if ($lackingStubHash > 0) { + $notices[] = ConsoleMessage::STATUS_STUB_HASH_MISSING->getMessage( + $lackingStubHash, + ConsoleMessage::plural( + $lackingStubHash, + ConsoleMessage::FRAGMENT_ENTRY_LACKS, + ConsoleMessage::FRAGMENT_ENTRIES_LACK, + ), + ); + } + + return [ + 'files' => $files, + 'providers' => $providers, + 'notices' => $notices, + ]; } /** - * Renders the status table for all files tracked in `scaffold-lock.json` under `$projectRoot`. + * Returns the state of one lock entry. * - * @param string $projectRoot Absolute path to the project root directory. - * @param OutputWriter $out Output sink used for stdout writes. + * @param string $destination Destination path as recorded in `scaffold-lock.json`. + * @param LockEntry $entry Lock entry of the destination. + * @param FileMapping|null $mapping Expected mapping of the destination, or `null` when no provider ships it. + * @param ExpectedState $expected Expected mappings, used to tell an orphan from an entry of a failed provider. + * @param ProjectContext $context Project the entry belongs to. + * @param int $lackingStubHash Number of `replace`/`preserve` entries without `stub-hash`, incremented in place. * - * @return int `0` on success. + * @return FileStatus State of the entry; never `pending`. */ - public function run(string $projectRoot, OutputWriter $out): int - { - $statuses = $this->getStatuses($projectRoot); + private function evaluateEntry( + string $destination, + array $entry, + FileMapping|null $mapping, + ExpectedState $expected, + ProjectContext $context, + int &$lackingStubHash, + ): FileStatus { + if (($entry['ejected'] ?? false) === true) { + return FileStatus::Ejected; + } - if ($statuses === []) { - $out->writeStdout('[scaffold] No files tracked in scaffold-lock.json.'); + $validator = new PathValidator(); + + try { + // An unsafe destination is an error before anything else, including the orphan check. + $validator->validateDestination($destination, $context->projectRoot); - return ExitCode::Ok->value; + if ($mapping === null) { + return $expected->hasFailed($entry['provider']) ? FileStatus::Error : FileStatus::Orphan; + } + + $validator->validateSource($mapping->source, $mapping->providerPath); + } catch (RuntimeException) { + return FileStatus::Error; } - $colFile = max(4, max(array_map(strlen(...), array_keys($statuses)))); - $colProvider = max(8, max(array_map(strlen(...), array_column($statuses, 'provider')))); - $colMode = max(4, max(array_map(strlen(...), array_column($statuses, 'mode')))); - $colStatus = max(6, max(array_map(strlen(...), array_column($statuses, 'status')))); - $separator = str_repeat('-', $colFile + $colProvider + $colMode + $colStatus + 6); + $destPath = PathResolver::destination($context->projectRoot, $destination); - $out->writeStdout( - sprintf("%-{$colFile}s %-{$colProvider}s %-{$colMode}s %s", 'File', 'Provider', 'Mode', 'Status'), - ); - $out->writeStdout($separator); + if (!file_exists($destPath)) { + return FileStatus::Missing; + } + + try { + return $this->compare($destPath, $entry, $mapping, $context->projectRoot, $lackingStubHash); + } catch (Throwable) { + return FileStatus::Error; + } + } + + /** + * Writes the status table and the summary line, or the empty-lock message. + * + * @param array $statuses File statuses. + * @param array $counts Counts keyed by state value. + * @param OutputWriter $out Output sink. + */ + private function renderTable(array $statuses, array $counts, OutputWriter $out): void + { + if ($statuses === []) { + $out->writeStdout( + ConsoleMessage::STATUS_NO_FILES->getMessage(), + ); + + return; + } + + $rows = []; foreach ($statuses as $destination => $info) { + $rows[] = [(string) $destination, $info['provider'], $info['mode'], $info['status']]; + } + + foreach (Table::render(['File', 'Provider', 'Mode', 'Status'], $rows) as $line) { $out->writeStdout( - sprintf( - "%-{$colFile}s %-{$colProvider}s %-{$colMode}s %s", - $destination, - $info['provider'], - $info['mode'], - $info['status'], - ), + $line, ); } - return ExitCode::Ok->value; + $parts = []; + + foreach (array_filter($counts, static fn(int $number): bool => $number > 0) as $state => $number) { + $parts[] = ConsoleMessage::FRAGMENT_COUNT->getMessage($number, $state); + } + + $total = count($statuses); + + $out->writeStdout( + ConsoleMessage::STATUS_SUMMARY->getMessage( + $total, + ConsoleMessage::plural($total, ConsoleMessage::FRAGMENT_FILE, ConsoleMessage::FRAGMENT_FILES), + implode(', ', $parts), + ), + ); } } diff --git a/src/Services/SyncService.php b/src/Services/SyncService.php new file mode 100644 index 0000000..dd38ef0 --- /dev/null +++ b/src/Services/SyncService.php @@ -0,0 +1,210 @@ +config->allowedPackages === []) { + $out->writeStdout( + Message::SYNC_NO_ALLOWED_PACKAGES->getMessage(), + ); + + return ExitCode::Ok->value; + } + + $lock = new LockFile($context->projectRoot); + + $data = $lock->read(); + + if ($dryRun) { + return $this->preview($context, $data, $out, $exitCode, $force, $decorated); + } + + $resolved = $context->providers($data['providers']); + + foreach ($resolved['warnings'] as $warning) { + $out->writeStderr( + $warning, + ); + } + + $summary = new ScaffoldSummary(); + + $runner = new ScaffoldRunner( + new ManifestLoader(new ManifestSchema(), new ManifestExpander()), + new FileApplier($context->config, new PathValidator(), $out), + $lock, + $out, + $summary, + ); + + try { + $runner->run($context->config, $resolved['providers'], $context->projectRoot, $force); + } catch (ScaffoldException) { + // The runner already wrote the message and counted the error. + } catch (RuntimeException $e) { + $out->writeStderr( + Message::SYNC_ABORTED->getMessage($e->getMessage()), + ); + + $summary->errors++; + } + + $out->writeStdout( + $summary->format('sync'), + ); + + return $summary->errors > 0 ? ExitCode::Error->value : ExitCode::Ok->value; + } + + /** + * Prints the change applying every expected mapping would make and the orphan list, without writing anything. + * + * @param ProjectContext $context Project to preview. + * @param array{providers: array, files: array} $data Lock data. + * @param OutputWriter $out Output sink. + * @param bool $exitCode Whether to return `1` when applying would write a file or record a new entry. + * @param bool $force Whether to preview user-modified and adopted `replace` files as overwritten. + * @param bool $decorated Whether to color the diffs. + * + * @return int `1` when a manifest or file cannot be read, or with `$exitCode` when something would change. + */ + private function preview( + ProjectContext $context, + array $data, + OutputWriter $out, + bool $exitCode, + bool $force, + bool $decorated, + ): int { + $expected = ExpectedState::build($context, $data['providers']); + + foreach ($expected->warnings as $warning) { + $out->writeStderr( + $warning, + ); + } + + foreach ($context->config->allowedPackages as $name) { + if (!$context->isInstalled($name, $data['providers'][$name] ?? null)) { + $out->writeStderr( + Message::SCAFFOLD_PROVIDER_NOT_INSTALLED->getMessage($name), + ); + } + } + + $errors = count($expected->failedProviders()); + $changes = 0; + $unchanged = 0; + + $validator = new PathValidator(); + $previewer = new ApplyPreviewer(); + $renderer = new DiffService(); + + foreach ($expected->all() as $key => $mapping) { + // PHP turns integer-like destinations ("123") into integer array keys. + $destination = (string) $key; + + $entry = $data['files'][$destination] ?? null; + + if (($entry['ejected'] ?? false) === true) { + continue; + } + + try { + $validator->validateDestination($destination, $context->projectRoot); + $validator->validateSource($mapping->source, $mapping->providerPath); + + $preview = $previewer->preview($mapping, $context->projectRoot, $entry); + } catch (RuntimeException $e) { + $out->writeStderr( + Message::COMMAND_FILE_ERROR->getMessage($destination, $e->getMessage()), + ); + + $errors++; + + continue; + } + + if ($force && $preview->userModified) { + $preview = new ApplyPreview($mapping, $preview->exists, $preview->current, $preview->proposed); + } + + $renderer->renderPreview($preview, $out, $decorated); + + $writes = $preview->changes() && !$preview->informational && !$preview->userModified; + + if ($writes || $entry === null) { + $changes++; + } else { + $unchanged++; + } + } + + $orphans = $expected->orphanReport($data['files']); + + foreach ($orphans as $line) { + $out->writeStderr($line); + } + + $out->writeStdout( + Message::SYNC_DRY_RUN_SUMMARY->getMessage( + $changes, + Message::plural($changes, Message::FRAGMENT_FILE, Message::FRAGMENT_FILES), + $unchanged, + count($expected->orphans($data['files'])), + $errors, + Message::plural($errors, Message::FRAGMENT_ERROR, Message::FRAGMENT_ERRORS), + ), + ); + + if ($errors > 0) { + return ExitCode::Error->value; + } + + return $exitCode && $changes > 0 ? ExitCode::Error->value : ExitCode::Ok->value; + } +} diff --git a/testo.php b/testo.php new file mode 100644 index 0000000..7567d41 --- /dev/null +++ b/testo.php @@ -0,0 +1,21 @@ +workspace = $this->tempDir; + $this->project = "{$this->tempDir}/project"; + + mkdir($this->project); + } + + /** + * Asserts that `$output` contains `$needle`, showing the whole output when it does not. + * + * @param string $output Captured output of a process. + * @param string $needle Expected text. + * @param string $message Failure message. + */ + protected static function assertOutputContains(string $output, string $needle, string $message): void + { + Assert::same( + str_contains($output, $needle) + ? $needle + : $output, + $needle, + $message, + ); + } + + /** + * Asserts that `$output` does not contain `$needle`, showing the whole output when it does. + * + * @param string $output Captured output of a process. + * @param string $needle Unexpected text. + * @param string $message Failure message. + */ + protected static function assertOutputLacks(string $output, string $needle, string $message): void + { + Assert::same( + str_contains($output, $needle) + ? $output + : '', + '', + $message + ); + } + + /** + * Runs Composer in `$cwd`, the project by default, and returns its result. + * + * @param list $arguments Composer arguments, such as `['install']`. + * @param string|null $cwd Working directory, or `null` for the project. + */ + protected function composer(array $arguments, string|null $cwd = null): ProcessResult + { + return RealComposer::run($arguments, $cwd ?? $this->project, "{$this->workspace}/home"); + } + + /** + * Returns the decoded `scaffold-lock.json` of the project. + * + * @return array{providers: array, files: array} + */ + protected function lock(): array + { + return (new LockFile($this->project))->read(); + } + + /** + * Returns the absolute path of a project file. + */ + protected function path(string $relative): string + { + return "{$this->project}/{$relative}"; + } + + /** + * Returns the repositories that install the plugin snapshot of this test and the provider fixture + * `$providerVersion`, writing the snapshot on first use. + * + * @param string $providerVersion Provider fixture release: `1.0.0` or `2.0.0`. + * + * @return list> + */ + protected function repositories(string $providerVersion = '1.0.0'): array + { + $plugin = "{$this->workspace}/plugin"; + + if (!is_dir($plugin)) { + RealComposer::snapshot($plugin); + } + + return RealComposer::repositories($plugin, $providerVersion); + } + + /** + * Runs `vendor/bin/scaffold` of the project and returns its result. + * + * @param list $arguments Command name followed by its arguments and options. + * @param string $binDir Composer bin directory relative to the project. + */ + protected function scaffold(array $arguments, string $binDir = 'vendor/bin'): ProcessResult + { + return RealComposer::runPhp( + ["{$this->project}/{$binDir}/scaffold", ...$arguments], + $this->project, + ); + } + + /** + * Writes the project `composer.json` requiring the plugin and the provider fixture, skipping the test when Composer + * is not available. + * + * @param array $scaffold Settings merged into `extra.scaffold`. + * @param array $config Settings merged into `config`. + * @param string $providerVersion Provider fixture release: `1.0.0` or `2.0.0`. + */ + protected function writeComposerJson( + array $scaffold = [], + array $config = [], + string $providerVersion = '1.0.0', + ): void { + RealComposer::requireCommand(); + + file_put_contents( + "{$this->project}/composer.json", + json_encode( + [ + 'name' => 'fixture/consumer', + 'type' => 'project', + 'repositories' => $this->repositories($providerVersion), + 'require' => [ + ...RealComposer::requirements(), + 'fixture/provider' => '*', + ], + 'config' => [ + 'allow-plugins' => ['php-forge/scaffold' => true], + ...$config, + ], + 'extra' => ['scaffold' => ['allowed-packages' => ['fixture/provider'], ...$scaffold]], + ], + JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR, + ) . "\n", + ); + } +} diff --git a/tests/Composer/CreateProjectTest.php b/tests/Composer/CreateProjectTest.php new file mode 100644 index 0000000..437f48b --- /dev/null +++ b/tests/Composer/CreateProjectTest.php @@ -0,0 +1,104 @@ +workspace}/template"; + + $fixture = dirname(__DIR__) . '/Fixtures/composer/template'; + + mkdir($template); + copy("{$fixture}/prepend.txt", "{$template}/prepend.txt"); + copy("{$fixture}/gitignore", "{$template}/.gitignore"); + file_put_contents( + "{$template}/composer.json", + json_encode( + [ + 'name' => 'fixture/template', + 'type' => 'project', + 'repositories' => $this->repositories(), + 'require' => [...RealComposer::requirements(), 'fixture/provider' => '*'], + 'config' => ['allow-plugins' => ['php-forge/scaffold' => true]], + 'extra' => ['scaffold' => ['allowed-packages' => ['fixture/provider']]], + ], + JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR, + ), + ); + rmdir($this->project); + + $result = $this->composer( + [ + 'create-project', + 'fixture/template', + 'project', + '--repository=' . json_encode( + [ + 'type' => 'path', + 'url' => $template, + 'options' => ['symlink' => false, 'versions' => ['fixture/template' => '1.0.0']], + ], + JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR, + ), + ], + $this->workspace, + ); + + Assert::same( + $result->status(), + '0', + "Create-project must exit with '0'.", + ); + FileAssert::contentSame( + $this->path('prepend.txt'), + "HEADER\nbody\n", + 'Prepend block must be added once.', + ); + FileAssert::contentSame( + $this->path('.gitignore'), + "/mine\n\n# Dependencies\n/vendor\n", + 'Template entries must stay first and the provider block must be merged once.', + ); + Assert::same( + substr_count( + $result->stdout, + Message::SCAFFOLD_PREFIXED->getMessage( + Message::FRAGMENT_COUNT_WRITTEN->getMessage(6, Message::FRAGMENT_FILES->getMessage()), + ), + ), + 1, + "The workflow must run exactly '1' time.", + ); + FileAssert::fileExists( + $this->path('scaffold-lock.json'), + 'Lock must be written.', + ); + } +} diff --git a/tests/Composer/InstallTest.php b/tests/Composer/InstallTest.php new file mode 100644 index 0000000..734ccf8 --- /dev/null +++ b/tests/Composer/InstallTest.php @@ -0,0 +1,163 @@ +writeComposerJson(config: ['vendor-dir' => 'lib/vendor']); + + Assert::same( + $this->composer(['install'])->status(), + '0', + "Install must exit with '0'.", + ); + FileAssert::contentSame( + $this->path('replace.txt'), + "replace v1\n", + 'Files must be written.', + ); + Assert::same( + $this->lock()['providers']['fixture/provider'] ?? null, + ['version' => '1.0.0', 'path' => 'lib/vendor/fixture/provider'], + "Provider path must follow the vendor dir 'lib/vendor'.", + ); + + $status = $this->scaffold(['status', '--exit-code'], 'lib/vendor/bin'); + + Assert::same( + $status->status(), + '0', + "Status must exit with '0'.", + ); + + self::assertOutputContains( + $status->stdout, + Message::STATUS_SUMMARY->getMessage( + 6, + Message::FRAGMENT_FILES->getMessage(), + Message::FRAGMENT_COUNT->getMessage(6, 'synced'), + ), + "CLI must report every file as 'synced'.", + ); + } + + /** + * Ensures the first install applies every mode and records the provider, and a second install is a silent no-op. + */ + public function firstInstallScaffoldsEveryModeAndSecondInstallIsNoop(): void + { + $this->writeComposerJson(); + + $first = $this->composer(['install']); + + Assert::same( + $first->status(), + '0', + "First install must exit with '0'.", + ); + + self::assertOutputContains( + $first->stdout, + ExpectedSummary::line(6, 0), + 'Summary must count six written files.', + ); + + Assert::same( + [ + 'replace.txt' => file_get_contents($this->path('replace.txt')), + 'config/preserve.txt' => file_get_contents($this->path('config/preserve.txt')), + '.gitignore' => file_get_contents($this->path('.gitignore')), + 'prepend.txt' => file_get_contents($this->path('prepend.txt')), + ], + [ + 'replace.txt' => "replace v1\n", + 'config/preserve.txt' => "preserve v1\n", + '.gitignore' => "# Dependencies\n/vendor\n", + 'prepend.txt' => "HEADER\n", + ], + 'Each mode must write its file.', + ); + Assert::same( + $this->lock()['providers']['fixture/provider'] ?? null, + ['version' => '1.0.0', 'path' => 'vendor/fixture/provider'], + "Provider must be recorded at 'vendor/fixture/provider'.", + ); + + $lock = file_get_contents($this->path('scaffold-lock.json')); + + $second = $this->composer(['install']); + + Assert::same( + $second->status(), + '0', + "Second install must exit with '0'.", + ); + + self::assertOutputLacks( + $second->stdout . $second->stderr, + Message::SCAFFOLD_PREFIXED->getMessage(''), + "A no-op run must write no '[scaffold]' line.", + ); + + FileAssert::contentSame( + $this->path('scaffold-lock.json'), + (string) $lock, + 'Lock must be byte-identical.', + ); + } + + /** + * Ensures `--no-plugins` writes nothing and the next plain install catches up. + */ + public function noPluginsSkipsScaffoldingUntilThePlainInstall(): void + { + $this->writeComposerJson(); + + Assert::same( + $this->composer(['install', '--no-plugins'])->status(), + '0', + "Install must exit with '0'.", + ); + FileAssert::fileDoesNotExist( + $this->path('replace.txt'), + 'Plugins disabled: nothing may be written.', + ); + FileAssert::fileDoesNotExist( + $this->path('scaffold-lock.json'), + 'Plugins disabled: no lock may be written.', + ); + Assert::same( + $this->composer(['install'])->status(), + '0', + "Plain install must exit with '0'.", + ); + FileAssert::contentSame( + $this->path('replace.txt'), + "replace v1\n", + 'Plain install must write the files.', + ); + FileAssert::fileExists( + $this->path('scaffold-lock.json'), + 'Plain install must write the lock.', + ); + } +} diff --git a/tests/Composer/LifecycleTest.php b/tests/Composer/LifecycleTest.php new file mode 100644 index 0000000..e335d0d --- /dev/null +++ b/tests/Composer/LifecycleTest.php @@ -0,0 +1,211 @@ +writeComposerJson(['auto' => false]); + + $install = $this->composer(['install']); + + Assert::same( + $install->status(), + '0', + "Install must exit with '0'.", + ); + + self::assertOutputContains( + $install->stdout, + Message::SCAFFOLD_AUTO_DISABLED->getMessage(), + 'Hook must announce the opt-out.', + ); + + FileAssert::fileDoesNotExist( + $this->path('scaffold-lock.json'), + 'Composer may write nothing.', + ); + FileAssert::directoryDoesNotExist( + $this->path('vendor/composer/composer'), + "The consumer must not install 'composer/composer'.", + ); + + $pending = $this->scaffold(['status', '--exit-code']); + + Assert::same( + $pending->status(1), + '1', + "Status must exit with '1'.", + ); + + self::assertOutputContains( + $pending->stdout, + Message::STATUS_SUMMARY->getMessage( + 6, + Message::FRAGMENT_FILES->getMessage(), + Message::FRAGMENT_COUNT->getMessage(6, 'pending'), + ), + "Every file must be 'pending'.", + ); + + $sync = $this->scaffold(['sync']); + + Assert::same( + $sync->status(), + '0', + "Sync must exit with '0'.", + ); + + self::assertOutputContains( + $sync->stdout, + ExpectedSummary::withCommand('sync', 6, 0), + 'Summary must count six written files.', + ); + + FileAssert::contentSame( + $this->path('replace.txt'), + "replace v1\n", + 'Sync must write the files.', + ); + Assert::same( + $this->scaffold(['status', '--exit-code'])->status(), + '0', + "Status must exit with '0'.", + ); + Assert::same( + $this->scaffold(['sync', '--dry-run', '--exit-code'])->status(), + '0', + "Sync preview must exit with '0'.", + ); + } + + /** + * Ensures a provider update applies each mode and reports the orphan, which `prune` then removes. + */ + public function providerBumpUpdatesEachModeAndPruneRemovesTheOrphan(): void + { + $this->writeComposerJson(); + + Assert::same( + $this->composer(['install'])->status(), + '0', + "First install must exit with '0'.", + ); + + file_put_contents($this->path('edited.txt'), "mine\n"); + + $this->writeComposerJson(providerVersion: '2.0.0'); + + $update = $this->composer(['update', 'fixture/provider']); + + Assert::same( + $update->status(), + '0', + "Update must exit with '0'.", + ); + Assert::same( + [ + 'replace.txt' => file_get_contents($this->path('replace.txt')), + 'edited.txt' => file_get_contents($this->path('edited.txt')), + 'config/preserve.txt' => file_get_contents($this->path('config/preserve.txt')), + '.gitignore' => file_get_contents($this->path('.gitignore')), + 'prepend.txt' => file_get_contents($this->path('prepend.txt')), + 'added.txt' => file_get_contents($this->path('added.txt')), + 'docs/old/dropped.txt' => file_get_contents($this->path('docs/old/dropped.txt')), + ], + [ + 'replace.txt' => "replace v2\n", + 'edited.txt' => "mine\n", + 'config/preserve.txt' => "preserve v1\n", + '.gitignore' => "# Dependencies\n/vendor\n/node_modules\n", + 'prepend.txt' => "HEADER\n", + 'added.txt' => "added v2\n", + 'docs/old/dropped.txt' => "dropped v1\n", + ], + 'Each mode must apply the bump; the user edit and the orphan must stay.', + ); + + self::assertOutputContains( + $update->stderr, + Message::SCAFFOLD_CONFLICTS->getMessage(1, Message::FRAGMENT_CONFLICT_FILE->getMessage()), + 'Conflict hint must be printed.', + ); + self::assertOutputContains( + $update->stderr, + Message::SCAFFOLD_ORPHAN_HEADER->getMessage(1, Message::FRAGMENT_FILE->getMessage()), + 'Orphan warning must be printed.', + ); + self::assertOutputContains( + $update->stderr, + Message::SCAFFOLD_ORPHAN_ENTRY->getMessage('docs/old/dropped.txt', 'fixture/provider'), + "Orphan 'docs/old/dropped.txt' must be named.", + ); + self::assertOutputContains( + $update->stdout, + ExpectedSummary::line( + 3, + 2, + ExpectedSummary::part(1, Message::FRAGMENT_OUTDATED), + ExpectedSummary::part(1, Message::FRAGMENT_CONFLICT), + ExpectedSummary::part(1, Message::FRAGMENT_ORPHAN), + ExpectedSummary::part(1, Message::FRAGMENT_WARNING), + ), + 'Summary must count every state.', + ); + + $preview = $this->scaffold(['prune', '--exit-code']); + + Assert::same( + $preview->status(1), + '1', + "Prune preview must exit with '1'.", + ); + + self::assertOutputContains( + $preview->stdout, + 'docs/old/dropped.txt fixture/provider unmodified delete', + 'Preview must list the orphan.', + ); + + $prune = $this->scaffold(['prune', '--force']); + + Assert::same( + $prune->status(), + '0', + "Prune must exit with '0'.", + ); + + self::assertOutputContains( + $prune->stdout, + Message::PRUNE_SUMMARY->getMessage(1, 0, 0, Message::FRAGMENT_ERRORS->getMessage()), + 'Summary must count the removal.', + ); + + FileAssert::directoryDoesNotExist( + $this->path('docs'), + 'Empty parent directories must be removed.', + ); + Assert::false( + isset($this->lock()['files']['docs/old/dropped.txt']), + "Entry 'docs/old/dropped.txt' must leave the lock.", + ); + } +} diff --git a/tests/ComposerFreeRuntimeTest.php b/tests/ComposerFreeRuntimeTest.php new file mode 100644 index 0000000..6793374 --- /dev/null +++ b/tests/ComposerFreeRuntimeTest.php @@ -0,0 +1,142 @@ +tempDir)) + ->composer(['p/a']) + ->installed(['p/a' => '1.0.0']) + ->provider('p/a', ['a.txt' => "a\n", '.gitignore' => "/vendor\n"], ['.gitignore' => 'append']); + + $result = RealComposer::runPhp( + [ + __DIR__ . '/Fixtures/runtime/guarded-cli.php', + dirname(__DIR__) . '/vendor/autoload.php', + $project->root, + ], + $this->tempDir, + ); + + Assert::same( + $result->exitCode, + 0, + "Exit code must be '0'; a loaded Composer class exits with '97': {$result->stderr}", + ); + Assert::same( + $result->stdout, + '0,0,0,0,0', + "Every command must exit with '0'.", + ); + FileAssert::contentSame( + "{$this->tempDir}/a.txt", + "a\n", + 'Sync must have applied the provider.', + ); + } + + /** + * Ensures no file outside the Composer adapters references Composer runtime or adapter classes. + */ + #[DataProvider(ComposerFreeRuntimeProvider::class . '::adapterOnlyReferences')] + public function onlyTheComposerAdaptersMatch(string $pattern): void + { + $offenders = []; + + foreach ($this->sourceFiles() as $relative => $content) { + if (in_array($relative, self::ADAPTERS, true)) { + continue; + } + + preg_match_all($pattern, $content, $matches); + + foreach ($matches[0] ?? throw new LogicException("Pattern '{$pattern}' must compile.") as $symbol) { + $offenders[] = "{$relative}: {$symbol}"; + } + } + + Assert::same( + $offenders, + [], + 'No file outside the Composer adapters may match the pattern.', + ); + } + + /** + * Returns the contents of every PHP file under `src/`, keyed by path relative to `src/` with forward slashes. + * + * @return array + */ + private function sourceFiles(): array + { + $root = dirname(__DIR__) . '/src/'; + $files = []; + + $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($root, FilesystemIterator::SKIP_DOTS)); + + /** @var SplFileInfo $file */ + foreach ($iterator as $file) { + if ($file->getExtension() !== 'php') { + continue; + } + + $relative = str_replace('\\', '/', substr($file->getPathname(), strlen($root))); + + $files[$relative] = (string) file_get_contents($file->getPathname()); + } + + Assert::notSame( + $files, + [], + 'Source files must be found.', + ); + + return $files; + } +} diff --git a/tests/Config/InstalledPackagesTest.php b/tests/Config/InstalledPackagesTest.php new file mode 100644 index 0000000..1912939 --- /dev/null +++ b/tests/Config/InstalledPackagesTest.php @@ -0,0 +1,156 @@ +tempDir)) + ->provider('p/a', ['a.txt' => "a\n"]) + ->installed(['p/a' => '1.2.3']); + + $installed = InstalledPackages::detect("{$this->tempDir}/vendor", $this->tempDir); + + Assert::true( + $installed->isKnown(), + 'Installed data must be known.', + ); + Assert::true( + $installed->has('p/a'), + 'Listed package must be installed.', + ); + Assert::false( + $installed->has('p/b'), + 'Unlisted package must not be installed.', + ); + Assert::same( + $installed->version('p/a'), + '1.2.3', + 'Pretty version must be read.', + ); + Assert::same( + $installed->installPath('p/a'), + realpath("{$this->tempDir}/vendor/p/a"), + 'Install path must be canonical.', + ); + } + + /** + * Ensures the runtime installed data is used when its root is the inspected project. + */ + public function detectUsesRuntimeDataWhenItsRootIsTheProject(): void + { + $root = dirname(__DIR__, 2); + + $installed = InstalledPackages::detect("{$this->tempDir}/missing-vendor", $root); + + Assert::true( + $installed->isKnown(), + 'Runtime data of this project must be used.', + ); + Assert::true( + $installed->has('symfony/console'), + "Runtime packages must list 'symfony/console'.", + ); + Assert::notNull( + $installed->installPath('symfony/console'), + "Runtime install path of 'symfony/console' must be known.", + ); + } + + /** + * Ensures another project without `installed.php` yields an unknown list. + */ + public function detectYieldsUnknownListForAnotherProjectWithoutInstalledPhp(): void + { + $installed = InstalledPackages::detect("{$this->tempDir}/vendor", $this->tempDir); + + Assert::false( + $installed->isKnown(), + 'Runtime data of another root must be ignored.', + ); + Assert::false( + $installed->has('symfony/console'), + "Unknown list must not hold 'symfony/console'.", + ); + Assert::null( + $installed->version('symfony/console'), + "Unknown list must not hold a version of 'symfony/console'.", + ); + } + + /** + * Ensures replaced packages and metapackages are skipped and later entries are still read. + */ + public function fromRawDataSkipsEntriesWithoutInstallPath(): void + { + $installed = InstalledPackages::fromRawData( + [ + 'versions' => [ + 'p/a' => ['pretty_version' => '1.0.0', 'install_path' => $this->tempDir], + 'p/replaced' => ['replaced' => ['1.0.0']], + 'p/meta' => ['pretty_version' => '2.0.0', 'install_path' => null], + 'p/no-version' => ['install_path' => $this->tempDir], + ], + ], + ); + + Assert::true( + $installed->has('p/a'), + 'Package with a path is installed.', + ); + Assert::false( + $installed->has('p/replaced'), + 'Replaced package has no install path.', + ); + Assert::false( + $installed->has('p/meta'), + 'Metapackage has no install path.', + ); + Assert::true( + $installed->has('p/no-version'), + 'Entries after a skipped one must be read.', + ); + Assert::null( + $installed->version('p/no-version'), + "Missing version yields 'null'.", + ); + } + + /** + * Ensures raw data without a `versions` map yields an unknown list. + */ + public function fromRawDataWithoutVersionsMapIsUnknown(): void + { + Assert::false( + InstalledPackages::fromRawData(1)->isKnown(), + 'A non-array yields an unknown list.', + ); + Assert::false( + InstalledPackages::fromRawData(['root' => []])->isKnown(), + 'Missing versions is unknown.', + ); + } +} diff --git a/tests/Config/ProjectConfigTest.php b/tests/Config/ProjectConfigTest.php new file mode 100644 index 0000000..1b2ffc5 --- /dev/null +++ b/tests/Config/ProjectConfigTest.php @@ -0,0 +1,196 @@ + $extra Root package `extra` block. + */ + #[DataSet([[], true], 'missing block')] + #[DataSet([['scaffold' => ['auto' => 0]], true], 'integer zero')] + #[DataSet([['scaffold' => ['auto' => false]], false], 'explicit false')] + public function autoIsDisabledOnlyByExplicitFalse(array $extra, bool $expected): void + { + Assert::same( + ProjectConfig::fromExtra($extra)->auto, + $expected, + "Only 'false' may disable auto.", + ); + } + + /** + * Ensures the allowed packages are read from `composer.json` in their declared order. + */ + public function fromComposerJsonReadsAllowedPackages(): void + { + file_put_contents( + "{$this->tempDir}/composer.json", + '{"extra": {"scaffold": {"allowed-packages": ["p/a", "p/b"]}}}', + ); + + $config = ProjectConfig::fromComposerJson("{$this->tempDir}/composer.json"); + + Assert::same( + $config->allowedPackages, + ['p/a', 'p/b'], + 'Allowed packages must keep their order.', + ); + Assert::true( + $config->isAllowed('p/b'), + 'Listed package must be allowed.', + ); + Assert::false( + $config->isAllowed('p/c'), + 'Unlisted package must not be allowed.', + ); + } + + /** + * Ensures only a non-empty string `config.vendor-dir` is kept as written. + */ + #[DataSet(['{"config": {"vendor-dir": "lib/vendor"}}', 'lib/vendor'], 'non-empty string')] + #[DataSet(['{"config": {"vendor-dir": ""}}', null], 'empty string')] + #[DataSet(['{"config": "x"}', null], 'non-object config')] + public function fromComposerJsonReadsTheVendorDirSetting(string $manifest, string|null $expected): void + { + file_put_contents( + "{$this->tempDir}/composer.json", + $manifest, + ); + + Assert::same( + ProjectConfig::fromComposerJson("{$this->tempDir}/composer.json")->vendorDir, + $expected, + 'Vendor directory setting must match.', + ); + } + + /** + * Ensures a manifest without a usable `extra` block allows no package. + */ + public function fromComposerJsonWithoutExtraAllowsNothing(): void + { + file_put_contents( + "{$this->tempDir}/composer.json", + '{"name": "a/b", "extra": "x"}', + ); + + Assert::same( + ProjectConfig::fromComposerJson("{$this->tempDir}/composer.json")->allowedPackages, + [], + 'Allowlist must be empty.', + ); + } + + /** + * Ensures non-string allowlist entries are dropped and counted. + */ + public function nonStringEntriesAreCountedAndIgnored(): void + { + $config = ProjectConfig::fromExtra(['scaffold' => ['allowed-packages' => ['p/a', 42, null]]]); + + Assert::same( + $config->allowedPackages, + ['p/a'], + 'Only string entries are kept.', + ); + Assert::same( + $config->ignoredEntries, + 2, + 'Every non-string entry is counted.', + ); + } + + /** + * Ensures an unreadable `composer.json` throws with the PHP warning as the reason. + */ + public function throwRuntimeExceptionWhenComposerJsonCannotBeRead(): void + { + $path = "{$this->tempDir}/composer.json"; + + file_put_contents( + $path, + '{}', + ); + + $this->restrictFileAccess($path, 0o000); + + Expect::exception(RuntimeException::class) + ->withMessage( + Message::FILESYSTEM_FAILED->getMessage( + Message::CONFIG_MANIFEST_UNREADABLE->getMessage($path), + "file_get_contents({$path}): Failed to open stream: Permission denied", + ), + ); + + ProjectConfig::fromComposerJson($path); + } + + /** + * Ensures an invalid JSON manifest throws with the decoder error. + */ + public function throwRuntimeExceptionWhenComposerJsonIsInvalidJson(): void + { + file_put_contents("{$this->tempDir}/composer.json", '{not json'); + + Expect::exception(RuntimeException::class) + ->withMessage( + Message::CONFIG_MANIFEST_INVALID_JSON->getMessage("{$this->tempDir}/composer.json", 'Syntax error'), + ) + ->withCode(0); + + ProjectConfig::fromComposerJson("{$this->tempDir}/composer.json"); + } + + /** + * Ensures a missing `composer.json` throws. + */ + public function throwRuntimeExceptionWhenComposerJsonIsMissing(): void + { + Expect::exception(RuntimeException::class) + ->withMessage( + Message::CONFIG_MANIFEST_NOT_FOUND->getMessage("{$this->tempDir}/composer.json"), + ); + + ProjectConfig::fromComposerJson("{$this->tempDir}/composer.json"); + } + + /** + * Ensures a manifest whose root is not a JSON object throws. + */ + public function throwRuntimeExceptionWhenComposerJsonIsNotAnObject(): void + { + file_put_contents("{$this->tempDir}/composer.json", '"text"'); + + Expect::exception(RuntimeException::class) + ->withMessage( + Message::CONFIG_MANIFEST_NOT_OBJECT->getMessage("{$this->tempDir}/composer.json"), + ); + + ProjectConfig::fromComposerJson("{$this->tempDir}/composer.json"); + } +} diff --git a/tests/Config/ProjectContextTest.php b/tests/Config/ProjectContextTest.php new file mode 100644 index 0000000..a4d6ae9 --- /dev/null +++ b/tests/Config/ProjectContextTest.php @@ -0,0 +1,158 @@ +tempDir}/packages/p-a", 0o777, true); + + $context = new ProjectContext( + $this->tempDir, + "{$this->tempDir}/vendor", + new ProjectConfig(['p/a']), + new InstalledPackages(['p/a' => ['version' => '1.0.0', 'path' => "{$this->tempDir}/packages/p-a"]]), + ); + + Assert::same( + $context->providerRoot('p/a', ['path' => 'vendor/p/a']), + ['root' => "{$this->tempDir}/packages/p-a", 'warning' => null], + 'Composer install path must win over the lock path.', + ); + Assert::true( + $context->isInstalled('p/a'), + 'Listed package is installed.', + ); + Assert::false( + $context->isInstalled('p/b'), + 'Unlisted package is not installed.', + ); + } + + /** + * Ensures a known installed list decides alone, whatever the provider directories on disk. + */ + public function knownInstalledListDecidesWithoutTheDirectory(): void + { + mkdir("{$this->tempDir}/vendor/p/b", 0o777, true); + + $context = new ProjectContext( + $this->tempDir, + "{$this->tempDir}/vendor", + new ProjectConfig(['p/a', 'p/b']), + new InstalledPackages(['p/a' => ['version' => '1.0.0', 'path' => "{$this->tempDir}/vendor/p/a"]]), + ); + + Assert::same( + [$context->isInstalled('p/a'), $context->isInstalled('p/b')], + [true, false], + 'Listed package without a directory is installed; unlisted package with one is not.', + ); + } + + /** + * Ensures allowed packages that are not installed are left out of the providers. + */ + public function providersSkipAllowedPackagesThatAreNotInstalled(): void + { + mkdir("{$this->tempDir}/vendor/p/a", 0o777, true); + + $context = new ProjectContext( + $this->tempDir, + "{$this->tempDir}/vendor", + new ProjectConfig(['p/missing', 'p/a']), + InstalledPackages::fromRawData( + [ + 'versions' => [ + 'p/a' => ['pretty_version' => '1.2.0', 'install_path' => "{$this->tempDir}/vendor/p/a"], + ], + ], + ), + ); + + $providers = $context->providers([])['providers']; + + Assert::same( + array_keys($providers), + ['p/a'], + 'Only the installed provider must be listed.', + ); + Assert::same( + ($providers['p/a'] ?? null)?->prettyVersion, + '1.2.0', + 'Installed version must be used.', + ); + } + + /** + * Ensures a symlinked path repository resolves to its target through `installed.php`. + */ + public function symlinkedPathRepositoryResolvesThroughInstalledPhp(): void + { + mkdir("{$this->tempDir}/packages/p-a", 0o777, true); + mkdir("{$this->tempDir}/vendor/p", 0o777, true); + symlink("{$this->tempDir}/packages/p-a", "{$this->tempDir}/vendor/p/a"); + + $project = (new InspectionProject($this->tempDir)) + ->composer(['p/a'])->installed(['p/a' => 'dev-main']); + + Assert::same( + $project->context()->providerRoot('p/a', ['path' => 'packages/p-a']), + ['root' => realpath("{$this->tempDir}/packages/p-a"), 'warning' => null], + 'Symlink target outside vendor must resolve without warning.', + ); + } + + /** + * Ensures an unknown installed list falls back to the lock path and the existing directory. + */ + public function unknownInstalledListFallsBackToLockPathAndDirectory(): void + { + mkdir("{$this->tempDir}/vendor/p/a", 0o777, true); + + $context = new ProjectContext( + $this->tempDir, + "{$this->tempDir}/vendor", + new ProjectConfig(['p/a']), + new InstalledPackages(null), + ); + + Assert::same( + $context->providerRoot('p/a', ['path' => 'vendor/p/a'])['root'], + realpath("{$this->tempDir}/vendor/p/a"), + 'Lock path must be used.', + ); + Assert::true( + $context->isInstalled('p/a'), + 'Existing root directory counts as installed.', + ); + Assert::false( + $context->isInstalled('p/b'), + 'Missing root directory is not installed.', + ); + } +} diff --git a/tests/Config/ProjectRootFinderTest.php b/tests/Config/ProjectRootFinderTest.php new file mode 100644 index 0000000..d899be5 --- /dev/null +++ b/tests/Config/ProjectRootFinderTest.php @@ -0,0 +1,126 @@ +tempDir}/app/src", 0o777, true); + file_put_contents( + "{$this->tempDir}/app/custom.json", + '{}', + ); + + try { + putenv("COMPOSER={$this->tempDir}/app/custom.json"); + + $existing = ProjectRootFinder::find("{$this->tempDir}/app/src"); + + putenv("COMPOSER={$this->tempDir}/app/missing.json"); + + $missing = ProjectRootFinder::find("{$this->tempDir}/app/src"); + } finally { + putenv('COMPOSER'); + } + + Assert::same( + $existing, + "{$this->tempDir}/app", + 'Absolute manifest must root the project at its directory.', + ); + Assert::null( + $missing, + "Missing absolute manifest yields 'null'.", + ); + } + + /** + * @param string $start Start directory relative to the project root, with a trailing separator. + */ + #[DataSet(['/src/deep/'], 'nested directory')] + #[DataSet(['/'], 'project root')] + public function findsTheNearestManifestWithoutTrailingSeparator(string $start): void + { + file_put_contents( + "{$this->tempDir}/composer.json", + '{}', + ); + mkdir("{$this->tempDir}/src/deep", 0o777, true); + + Assert::same( + ProjectRootFinder::find($this->tempDir . $start), + $this->tempDir, + 'Search must stop at the manifest and drop the trailing separator.', + ); + } + + public function honorsComposerEnvironmentVariable(): void + { + file_put_contents( + "{$this->tempDir}/composer.json", + '{}', + ); + mkdir("{$this->tempDir}/app", 0o777, true); + file_put_contents( + "{$this->tempDir}/app/custom.json", + '{}', + ); + + putenv('COMPOSER=custom.json'); + + try { + $root = ProjectRootFinder::find("{$this->tempDir}/app"); + } finally { + putenv('COMPOSER'); + } + + Assert::same( + $root, + "{$this->tempDir}/app", + "Manifest named by 'COMPOSER' must be searched.", + ); + } + + public function returnsNullWhenFilesystemRootIsReached(): void + { + mkdir("{$this->tempDir}/a", 0o777, true); + putenv('COMPOSER=scaffold-root-finder-never-exists.json'); + + try { + $fromProject = ProjectRootFinder::find("{$this->tempDir}/a"); + $fromRoot = ProjectRootFinder::find('/'); + } finally { + putenv('COMPOSER'); + } + + Assert::null( + $fromProject, + "Missing manifest yields 'null'.", + ); + Assert::null( + $fromRoot, + "Filesystem root without manifest yields 'null'.", + ); + } +} diff --git a/tests/Config/VendorDirResolverTest.php b/tests/Config/VendorDirResolverTest.php new file mode 100644 index 0000000..91792d9 --- /dev/null +++ b/tests/Config/VendorDirResolverTest.php @@ -0,0 +1,165 @@ +tempDir}/composer.json", + json_encode(['config' => ['vendor-dir' => 'wrong']]), + ); + file_put_contents( + "{$this->tempDir}/app.json", + json_encode(['config' => ['vendor-dir' => 'lib/vendor']]), + ); + + putenv('COMPOSER=app.json'); + + try { + $vendorDir = ProjectContext::create($this->tempDir)->vendorDir; + $manifestName = VendorDirResolver::manifestName(); + } finally { + putenv('COMPOSER'); + } + + Assert::same( + $vendorDir, + "{$this->tempDir}/lib/vendor", + "The manifest named by 'COMPOSER' must be read.", + ); + Assert::same( + $manifestName, + 'app.json', + "Manifest name must follow 'COMPOSER'.", + ); + Assert::same( + VendorDirResolver::manifestName(), + 'composer.json', + "Manifest name must default to 'composer.json'.", + ); + } + + /** + * Ensures the default vendor directory drops the trailing separator of the project root. + */ + public function defaultFallbackStripsTrailingSeparatorFromProjectRoot(): void + { + Assert::same( + VendorDirResolver::resolve("{$this->tempDir}/"), + "{$this->tempDir}/vendor", + "Default vendor directory must not hold '//vendor'.", + ); + } + + /** + * Ensures `COMPOSER_VENDOR_DIR` wins over `config.vendor-dir`. + */ + public function environmentTakesPriorityOverComposerJson(): void + { + file_put_contents( + "{$this->tempDir}/composer.json", + json_encode(['config' => ['vendor-dir' => 'ignored']]), + ); + putenv('COMPOSER_VENDOR_DIR=/absolute/env-vendor'); + + Assert::same( + ProjectContext::create($this->tempDir)->vendorDir, + '/absolute/env-vendor', + "'COMPOSER_VENDOR_DIR' must win over 'config.vendor-dir'.", + ); + } + + /** + * Ensures each `COMPOSER_VENDOR_DIR` value resolves to the expected absolute path. + */ + #[DataProvider(VendorDirResolverProvider::class . '::environmentValues')] + public function resolvesEnvironmentValue(string $value, string $expected): void + { + putenv("COMPOSER_VENDOR_DIR={$value}"); + + Assert::same( + VendorDirResolver::resolve($this->tempDir), + str_replace('{root}', $this->tempDir, $expected), + "Resolved path of 'COMPOSER_VENDOR_DIR' must match.", + ); + } + + /** + * Ensures each `config.vendor-dir` setting resolves to the expected absolute path. + * + * @param array $manifest Content of `composer.json`. + * @param string $rootSuffix Suffix appended to the project root, such as a trailing separator. + */ + #[DataProvider(VendorDirResolverProvider::class . '::manifestSettings')] + public function resolvesManifestSetting(array $manifest, string $rootSuffix, string $expected): void + { + file_put_contents( + "{$this->tempDir}/composer.json", + json_encode($manifest), + ); + + Assert::same( + ProjectContext::create($this->tempDir . $rootSuffix)->vendorDir, + str_replace('{root}', $this->tempDir, $expected), + "Resolved path of 'config.vendor-dir' must match.", + ); + } + + /** + * Restores `COMPOSER_VENDOR_DIR` to its value before the test. + */ + #[AfterTest] + public function restoreEnvironment(): void + { + putenv($this->originalEnv === false ? 'COMPOSER_VENDOR_DIR' : "COMPOSER_VENDOR_DIR={$this->originalEnv}"); + } + + /** + * Saves and clears `COMPOSER_VENDOR_DIR`, so the environment of the runner never leaks into a test. + */ + #[BeforeTest] + public function saveEnvironment(): void + { + $this->originalEnv = getenv('COMPOSER_VENDOR_DIR'); + + putenv('COMPOSER_VENDOR_DIR'); + } +} diff --git a/tests/Console/ApplicationRunTest.php b/tests/Console/ApplicationRunTest.php new file mode 100644 index 0000000..882887d --- /dev/null +++ b/tests/Console/ApplicationRunTest.php @@ -0,0 +1,370 @@ + $input Command input. + */ + #[DataProvider(ApplicationRunProvider::class . '::commandsSkippingADeniedProvider')] + public function commandSkipsAProviderMissingFromTheAllowlist(array $input, int $exitCode): void + { + $this + ->project() + ->provider('p/denied', ['d.txt' => "d\n"]) + ->file('d.txt', "x\n") + ->track('d.txt', 'p/denied'); + + $tester = $this->runApplication($input); + + Assert::same( + $tester->getStatusCode(), + $exitCode, + "Exit code must be '{$exitCode}'.", + ); + Assert::same( + $tester->getErrorOutput(), + ConsoleMessage::COMMAND_PROVIDER_NOT_ALLOWED->getMessage('d.txt', 'p/denied') . PHP_EOL, + "Error output must hold only the 'p/denied' rejection.", + ); + FileAssert::contentSame( + "{$this->tempDir}/d.txt", + "x\n", + "File 'd.txt' must never be written.", + ); + } + + /** + * @param array $input Command input. + */ + #[DataProvider(ApplicationRunProvider::class . '::commandsReadingTheLock')] + public function corruptLockIsReportedAsScaffoldError(array $input): void + { + $this->project()->file('scaffold-lock.json', '{not json'); + + $tester = $this->runApplication($input); + + Assert::same( + $tester->getStatusCode(), + 1, + "Exit code must be '1'.", + ); + Assert::same( + $tester->getErrorOutput(), + ConsoleMessage::SCAFFOLD_PREFIXED->getMessage( + Message::LOCK_INVALID_JSON->getMessage((new LockFile($this->tempDir))->getPath(), 'Syntax error'), + ) + . PHP_EOL, + 'Error output must hold only the lock error.', + ); + Assert::same( + $tester->getDisplay(), + '', + 'Output must stay empty.', + ); + } + + /** + * @param array $input Command input. + */ + #[DataSet([['command' => 'diff']], 'no target')] + #[DataSet([['command' => 'diff', 'file' => 'a.txt', '--all' => true]], 'both targets')] + #[DataSet([['command' => 'diff', '--all' => 0]], 'falsy all option')] + public function diffRequiresExactlyOneOfFileOrAll(array $input): void + { + $this + ->project() + ->provider('p/a', ['a.txt' => "a\n"]) + ->file('a.txt', "a\n") + ->track('a.txt', 'p/a'); + + $tester = $this->runApplication($input); + + Assert::same( + $tester->getStatusCode(), + 2, + "Exit code must be '2'.", + ); + Assert::same( + $tester->getErrorOutput(), + ConsoleMessage::DIFF_TARGET_AMBIGUOUS->getMessage() . PHP_EOL, + 'Error output must hold only the usage message.', + ); + } + + public function diffWithExitCodeAndAll(): void + { + $this + ->project() + ->provider('p/a', ['a.txt' => "a\n", 'b.txt' => "b\n"]) + ->file('a.txt', "a\n") + ->file('b.txt', "b\n") + ->track('a.txt', 'p/a') + ->track('b.txt', 'p/a'); + + Assert::same( + $this->runApplication(['command' => 'diff', '--all' => true, '--exit-code' => true])->getStatusCode(), + 0, + "Exit code of a clean project must be '0'.", + ); + + $this->project()->stub('p/a', 'b.txt', "b2\n"); + + $tester = $this->runApplication(['command' => 'diff', '--all' => true, '--exit-code' => true]); + + Assert::same( + $tester->getStatusCode(), + 1, + "Exit code of a pending change with '--exit-code' must be '1'.", + ); + Assert::string($tester->getDisplay())->startsWith( + ConsoleMessage::DIFF_NO_CHANGES->getMessage('a.txt') . PHP_EOL + . ConsoleMessage::DIFF_PREVIEW_HEADER->getMessage('b.txt', 'replace', 'p/a', ''), + 'Files must be listed in lock order.', + ); + } + + public function missingComposerJsonIsReportedOnStderr(): void + { + putenv('COMPOSER=scaffold-application-run-missing.json'); + + try { + $tester = $this->runApplication(['command' => 'status']); + } finally { + putenv('COMPOSER'); + } + + Assert::same( + $tester->getStatusCode(), + 1, + "Exit code must be '1'.", + ); + Assert::same( + $tester->getErrorOutput(), + ConsoleMessage::COMMAND_MANIFEST_NOT_FOUND->getMessage( + 'scaffold-application-run-missing.json', + $this->tempDir, + ) + . PHP_EOL, + 'Error must name the search start.', + ); + Assert::same( + $tester->getDisplay(), + '', + 'Output must stay empty.', + ); + } + + public function missingWorkingDirectoryFails(): void + { + $tester = $this->runApplication(['command' => 'status', '-d' => "{$this->tempDir}/nope"]); + + Assert::same( + $tester->getStatusCode(), + 1, + "Exit code must be '1'.", + ); + Assert::same( + $tester->getErrorOutput(), + ConsoleMessage::COMMAND_WORKING_DIR_NOT_FOUND->getMessage("{$this->tempDir}/nope") . PHP_EOL, + 'Error output must hold only the missing directory error.', + ); + } + + public function reapplyDryRunWritesNothing(): void + { + $this + ->project() + ->provider('p/a', ['a.txt' => "a\n"]) + ->file('a.txt', "a\n") + ->track('a.txt', 'p/a') + ->stub('p/a', 'a.txt', "a2\n"); + + $tester = $this->runApplication(['command' => 'reapply', '--dry-run' => true, '--exit-code' => true]); + + Assert::same( + $tester->getStatusCode(), + 1, + "Exit code of a pending write with '--exit-code' must be '1'.", + ); + Assert::string($tester->getDisplay()) + ->contains( + '+a2', + "Diff must print the '+a2' line.", + ); + FileAssert::contentSame( + "{$this->tempDir}/a.txt", + "a\n", + 'Nothing may be written.', + ); + } + + /** + * Restores the working directory of the runner. + */ + #[AfterTest] + public function restoreWorkingDirectory(): void + { + if ($this->originalCwd !== '' && is_dir($this->originalCwd)) { + chdir($this->originalCwd); + } + } + + /** + * Saves the working directory, writes the project manifest and enters the project root. + */ + #[BeforeTest(priority: -10)] + public function setUpProject(): void + { + $this->originalCwd = (string) getcwd(); + + $this->project()->composer(['p/a']); + + chdir($this->tempDir); + } + + /** + * @param string $cwd Working directory of the run. + * @param array $input Command input. + */ + #[DataProvider(ApplicationRunProvider::class . '::projectRootStarts')] + public function statusFindsTheProjectRoot(string $cwd, array $input): void + { + $this + ->project() + ->provider('p/a', ['a.txt' => "a\n"]) + ->file('a.txt', "a\n") + ->track('a.txt', 'p/a'); + + mkdir("{$this->tempDir}/src/deep", 0o777, true); + chdir(str_replace('{root}', $this->tempDir, $cwd)); + + $tester = $this->runApplication( + array_map( + fn(bool|string $value): bool|string => is_string($value) + ? str_replace('{root}', $this->tempDir, $value) + : $value, + $input, + ), + ); + + Assert::same( + $tester->getStatusCode(), + 0, + "Exit code must be '0'.", + ); + Assert::string($tester->getDisplay())->endsWith( + ConsoleMessage::STATUS_SUMMARY->getMessage( + 1, + ConsoleMessage::FRAGMENT_FILE->getMessage(), + ConsoleMessage::FRAGMENT_COUNT->getMessage(1, 'synced'), + ) + . PHP_EOL, + 'Summary must report the one synced file of the root.', + ); + } + + public function statusJsonFormatAndExitCode(): void + { + $this + ->project() + ->provider('p/a', ['a.txt' => "a\n"]) + ->file('a.txt', "a\n") + ->track('a.txt', 'p/a') + ->file('a.txt', "mine\n"); + + $json = $this->runApplication(['command' => 'status', '--format' => 'json']); + $exit = $this->runApplication(['command' => 'status', '--exit-code' => true]); + $invalid = $this->runApplication(['command' => 'status', '--format' => 'xml']); + + Assert::same( + $json->getStatusCode(), + 0, + "Exit code of JSON without '--exit-code' must be '0'.", + ); + Assert::string($json->getDisplay())->contains( + "\"a.txt\": {\n \"provider\": \"p/a\",\n \"mode\": \"replace\",\n" + . ' "status": "modified"', + "JSON must carry the 'modified' state.", + ); + Assert::same( + $exit->getStatusCode(), + 1, + "Exit code of a modified file with '--exit-code' must be '1'.", + ); + Assert::same( + $invalid->getStatusCode(), + 2, + "Exit code of an unknown format must be '2'.", + ); + Assert::same( + $invalid->getErrorOutput(), + ConsoleMessage::STATUS_FORMAT_UNKNOWN->getMessage('xml') . PHP_EOL, + 'Error output must hold only the usage message.', + ); + } + + /** + * Returns the builder of the temporary project. + */ + private function project(): InspectionProject + { + return new InspectionProject($this->tempDir); + } + + /** + * Runs the application with the error output captured separately. + * + * @param array $input Command input. + */ + private function runApplication(array $input): ApplicationTester + { + $application = new Application(); + + $application->setAutoExit(false); + + $tester = new ApplicationTester($application); + + $tester->run($input, ['capture_stderr_separately' => true, 'decorated' => false]); + + return $tester; + } +} diff --git a/tests/Console/ApplicationTest.php b/tests/Console/ApplicationTest.php index 43ec8a8..5891eb9 100644 --- a/tests/Console/ApplicationTest.php +++ b/tests/Console/ApplicationTest.php @@ -6,83 +6,101 @@ use Composer\InstalledVersions; use PHPForge\Scaffold\Console\Application; -use PHPForge\Scaffold\Console\Command\{DiffCommand, EjectCommand, ProvidersCommand, ReapplyCommand, StatusCommand}; -use PHPUnit\Framework\Attributes\Group; -use PHPUnit\Framework\TestCase; +use PHPForge\Scaffold\Console\Command\{ + DiffCommand, + EjectCommand, + ProvidersCommand, + PruneCommand, + ReapplyCommand, + StatusCommand, + SyncCommand, +}; +use Symfony\Component\Console\Command\{Command, CompleteCommand, DumpCompletionCommand, HelpCommand, ListCommand}; +use Testo\Assert; +use Testo\Codecov\Covers; +use Testo\Test; -use function sprintf; +use function array_map; +use function ksort; /** * Unit tests for {@see Application} verifying command registration, name stability, and the runtime-derived * version lookup via Composer metadata. */ -#[Group('scaffold')] -#[Group('console')] -final class ApplicationTest extends TestCase +#[Test] +#[Covers(Application::class)] +final class ApplicationTest { - public function testApplicationNameIsStable(): void + /** + * Ensures the application name is the fixed package name. + */ + public function nameIsStable(): void { - self::assertSame( - Application::NAME, + Assert::same( (new Application())->getName(), - "'Application::getName()' must return the fixed 'Application::NAME'.", + Application::NAME, + "Name must be 'Application::NAME'.", ); } - public function testApplicationRegistersTheFiveScaffoldCommands(): void + /** + * Pins the full command list of the application, the seven scaffold commands plus the Symfony built-ins. + */ + public function registersEveryCommand(): void { - $app = new Application(); - - $commands = [ - 'status' => StatusCommand::class, - 'providers' => ProvidersCommand::class, - 'diff' => DiffCommand::class, - 'eject' => EjectCommand::class, - 'reapply' => ReapplyCommand::class, - ]; + $commands = array_map( + static fn(Command $command): string => $command::class, + (new Application())->all(), + ); - foreach ($commands as $name => $expectedClass) { - self::assertTrue( - $app->has($name), - sprintf("Application must register a '%s' command.", $name), - ); - self::assertInstanceOf( - $expectedClass, - $app->get($name), - sprintf("Command '%s' must resolve to '%s'.", $name, $expectedClass), - ); - } - } + ksort($commands); - public function testApplicationVersionIsNonEmptyAtRuntime(): void - { - self::assertNotEmpty( - (new Application())->getVersion(), - "'Application::getVersion()' must always return a non-empty string for 'vendor/bin/scaffold --version'.", + Assert::same( + $commands, + [ + '_complete' => CompleteCommand::class, + 'completion' => DumpCompletionCommand::class, + 'diff' => DiffCommand::class, + 'eject' => EjectCommand::class, + 'help' => HelpCommand::class, + 'list' => ListCommand::class, + 'providers' => ProvidersCommand::class, + 'prune' => PruneCommand::class, + 'reapply' => ReapplyCommand::class, + 'status' => StatusCommand::class, + 'sync' => SyncCommand::class, + ], + 'Every command must be registered under its name.', ); } - public function testResolveVersionFallsBackWhenPackageIsNotInstalled(): void + /** + * Ensures an unknown Composer package falls back to the fixed version. + */ + public function resolveVersionFallsBackWhenPackageIsNotInstalled(): void { - self::assertSame( - Application::FALLBACK_VERSION, + Assert::same( Application::resolveVersion('definitely/not-a-real-package-for-tests'), - "Unknown Composer packages must fall back to 'Application::FALLBACK_VERSION' so the CLI stays runnable.", + Application::FALLBACK_VERSION, + "Unknown package must yield 'Application::FALLBACK_VERSION'.", ); } - public function testResolveVersionReturnsComposerPrettyVersionWhenPackageIsInstalled(): void + /** + * Ensures the application version is the Composer pretty version of the installed package. + */ + public function versionIsTheInstalledPrettyVersion(): void { $prettyVersion = InstalledVersions::getPrettyVersion(Application::NAME); - self::assertIsString( + Assert::notNull( $prettyVersion, - "Pre-condition: Composer must report a 'pretty_version' for 'Application::NAME' in the test environment.", + "Precondition: Composer must report a 'pretty_version' for 'Application::NAME'.", ); - self::assertSame( + Assert::same( + (new Application())->getVersion(), $prettyVersion, - Application::resolveVersion(Application::NAME), - "'Application::resolveVersion()' must return the Composer 'pretty_version' for an installed package.", + "Version must be the Composer 'pretty_version'.", ); } } diff --git a/tests/Console/Command/DiffCommandTest.php b/tests/Console/Command/DiffCommandTest.php index 650795e..79a415a 100644 --- a/tests/Console/Command/DiffCommandTest.php +++ b/tests/Console/Command/DiffCommandTest.php @@ -5,224 +5,89 @@ namespace PHPForge\Scaffold\Tests\Console\Command; use PHPForge\Scaffold\Console\Command\DiffCommand; -use PHPForge\Scaffold\Scaffold\Lock\{Hasher, LockFile}; -use PHPForge\Scaffold\Tests\Support\TempDirectoryTrait; -use PHPUnit\Framework\Attributes\Group; -use PHPUnit\Framework\TestCase; -use Symfony\Component\Console\Command\Command; +use PHPForge\Scaffold\Tests\Support\{InspectionProject, TempDirectoryTrait}; use Symfony\Component\Console\Tester\CommandTester; -use Xepozz\InternalMocker\MockerState; +use Testo\Assert; +use Testo\Data\DataSet; +use Testo\Lifecycle\{AfterTest, BeforeTest}; +use Testo\Test; use function chdir; use function getcwd; use function is_dir; +use function str_contains; /** - * Unit tests for the Symfony Console {@see DiffCommand} covering identical-content, divergent-content, and - * untracked-file scenarios. + * Functional tests for the Symfony Console {@see DiffCommand} wiring the `file` argument and the output decoration + * to the diff service. */ -#[Group('scaffold')] -#[Group('console-command')] -final class DiffCommandTest extends TestCase +#[Test] +final class DiffCommandTest { use TempDirectoryTrait; + /** + * Working directory before the test, restored after it. + */ private string $originalCwd = ''; - public function testExecutePrintsAnsiColorsWhenOutputIsDecorated(): void + /** + * Ensures the diff of the named file is colored only when the output is decorated. + */ + #[DataSet([true], 'decorated')] + #[DataSet([false], 'not decorated')] + public function colorsFollowTheOutputDecoration(bool $decorated): void { - $this->seedProviderAndFile( - destination: 'config/params.php', - sourceContent: "return ['a' => 1];\n", - currentContent: "return ['a' => 2];\n", - ); - - $tester = new CommandTester(new DiffCommand()); - - $tester->execute(['file' => 'config/params.php'], ['decorated' => true]); - - self::assertStringContainsString( - "\e[31m", - $tester->getDisplay(), - 'Decorated output must colorize removed lines in red.', - ); - } - - public function testExecutePrintsDiffWhenContentsDiverge(): void - { - $this->seedProviderAndFile( - destination: 'config/params.php', - sourceContent: "return ['a' => 1];\n", - currentContent: "return ['a' => 2];\n", - ); - $tester = new CommandTester(new DiffCommand()); - $exitCode = $tester->execute(['file' => 'config/params.php']); + $exitCode = $tester->execute(['file' => 'config/params.php'], ['decorated' => $decorated]); - self::assertSame( - 0, + Assert::same( $exitCode, - 'Diff command must return success exit code even when differences are found.', - ); - - $display = $tester->getDisplay(); - - self::assertStringContainsString( - "-return ['a' => 1];", - $display, - "Diff output must contain removed line prefixed with '-'.", - ); - self::assertStringContainsString( - "+return ['a' => 2];", - $display, - "Diff output must contain added line prefixed with '+'.", - ); - } - - public function testExecutePrintsPlainDiffWhenOutputIsNotDecorated(): void - { - $this->seedProviderAndFile( - destination: 'config/params.php', - sourceContent: "return ['a' => 1];\n", - currentContent: "return ['a' => 2];\n", - ); - - $tester = new CommandTester(new DiffCommand()); - - $tester->execute(['file' => 'config/params.php']); - - self::assertStringNotContainsString( - "\e[", - $tester->getDisplay(), - 'Undecorated output must contain no ANSI escape codes.', - ); - } - - public function testExecuteReportsNoDifferencesWhenStubAndCurrentMatch(): void - { - $this->seedProviderAndFile( - destination: 'config/params.php', - sourceContent: "return [];\n", - currentContent: "return [];\n", - ); - - $tester = new CommandTester(new DiffCommand()); - - $exitCode = $tester->execute(['file' => 'config/params.php']); - - self::assertSame( 0, - $exitCode, - 'Diff command must return success exit code when no differences are found.', + "Exit code must be '0'.", ); - self::assertStringContainsString( - 'No differences found', - $tester->getDisplay(), - 'Diff command must indicate when no differences are found.', + Assert::same( + str_contains($tester->getDisplay(), "\e["), + $decorated, + 'Output must hold ANSI codes only when decorated.', ); - } - - public function testExecuteReturnsErrorWhenFileIsNotTracked(): void - { - (new LockFile($this->tempDir))->write(['providers' => [], 'files' => []]); - - $tester = new CommandTester(new DiffCommand()); - - $exitCode = $tester->execute( - ['file' => 'missing.php'], - ['capture_stderr_separately' => true], - ); - - self::assertSame( - 1, - $exitCode, - 'Diff command must return error exit code when file is not tracked.', - ); - self::assertStringContainsString( - 'not tracked', - $tester->getErrorOutput(), - 'Diff command must indicate when file is not tracked.', + Assert::string($tester->getDisplay())->ignoringAnsi()->contains( + "-return ['a' => 2];\n+return ['a' => 1];", + "Output must hold the diff of 'config/params.php'.", + )->notContains( + 'config/other.php', + "Output must not hold the diff of 'config/other.php'.", ); } - public function testExecuteReturnsFailureWhenGetcwdFails(): void - { - MockerState::addCondition( - 'PHPForge\\Scaffold\\Console\\Command', - 'getcwd', - [], - false, - default: true, - ); - - $tester = new CommandTester(new DiffCommand()); - - self::assertSame( - Command::FAILURE, - $tester->execute(['file' => 'config/params.php']), - 'Diff command must return failure exit code when getcwd fails.', - ); - self::assertStringContainsString( - 'Unable to determine current working directory', - $tester->getDisplay(), - 'Diff command must indicate when the current working directory cannot be determined.', - ); - } - - protected function setUp(): void - { - $this->originalCwd = (string) getcwd(); - - $this->setUpTempDirectory(); - - chdir($this->tempDir); - } - - protected function tearDown(): void + /** + * Restores the working directory of the runner. + */ + #[AfterTest] + public function restoreWorkingDirectory(): void { if ($this->originalCwd !== '' && is_dir($this->originalCwd)) { chdir($this->originalCwd); } - - $this->tearDownTempDirectory(); } - private function seedProviderAndFile(string $destination, string $sourceContent, string $currentContent): void + /** + * Saves the working directory, seeds two tracked files that diverge from their stubs and enters the project root. + */ + #[BeforeTest(priority: -10)] + public function setUpProject(): void { - $providerRoot = "{$this->tempDir}/vendor/pkg/name"; - $stubRelative = "stubs/{$destination}"; - $stubPath = "{$providerRoot}/{$stubRelative}"; - - $this->ensureTestDirectory(dirname($stubPath)); - - file_put_contents($stubPath, $sourceContent); - - $destAbsolute = "{$this->tempDir}/{$destination}"; - - $this->ensureTestDirectory(dirname($destAbsolute)); - - file_put_contents($destAbsolute, $currentContent); + $this->originalCwd = (string) getcwd(); - $hash = (new Hasher())->hash($destAbsolute); + (new InspectionProject($this->tempDir)) + ->composer(['pkg/name']) + ->provider('pkg/name', ['config/params.php' => "return ['a' => 1];\n", 'config/other.php' => "b\n"]) + ->file('config/params.php', "return ['a' => 2];\n") + ->file('config/other.php', "c\n") + ->track('config/params.php', 'pkg/name') + ->track('config/other.php', 'pkg/name'); - (new LockFile($this->tempDir))->write( - [ - 'providers' => [ - 'pkg/name' => [ - 'version' => '0.1.x-dev', - 'path' => 'vendor/pkg/name', - ], - ], - 'files' => [ - $destination => [ - 'hash' => $hash, - 'provider' => 'pkg/name', - 'source' => $stubRelative, - 'mode' => 'replace', - ], - ], - ], - ); + chdir($this->tempDir); } } diff --git a/tests/Console/Command/EjectCommandTest.php b/tests/Console/Command/EjectCommandTest.php index 6d7231d..f292e92 100644 --- a/tests/Console/Command/EjectCommandTest.php +++ b/tests/Console/Command/EjectCommandTest.php @@ -5,164 +5,88 @@ namespace PHPForge\Scaffold\Tests\Console\Command; use PHPForge\Scaffold\Console\Command\EjectCommand; -use PHPForge\Scaffold\Scaffold\Lock\LockFile; -use PHPForge\Scaffold\Tests\Support\TempDirectoryTrait; -use PHPUnit\Framework\Attributes\Group; -use PHPUnit\Framework\TestCase; -use Symfony\Component\Console\Command\Command; +use PHPForge\Scaffold\Tests\Support\{InspectionProject, TempDirectoryTrait}; use Symfony\Component\Console\Tester\CommandTester; -use Xepozz\InternalMocker\MockerState; +use Testo\Assert; +use Testo\Data\DataSet; +use Testo\Lifecycle\{AfterTest, BeforeTest}; +use Testo\Test; use function chdir; use function getcwd; use function is_dir; /** - * Unit tests for the Symfony Console {@see EjectCommand} verifying dry-run, confirmed-removal, and not-tracked paths. + * Functional tests for the Symfony Console {@see EjectCommand} wiring the `file` argument and the `--yes` option to + * the eject service. */ -#[Group('scaffold')] -#[Group('console-command')] -final class EjectCommandTest extends TestCase +#[Test] +final class EjectCommandTest { use TempDirectoryTrait; + /** + * Working directory before the test, restored after it. + */ private string $originalCwd = ''; - public function testExecuteOnlyPreviewsWithoutYesFlag(): void + /** + * Restores the working directory of the runner. + */ + #[AfterTest] + public function restoreWorkingDirectory(): void { - $this->seedTrackedFile('config/params.php'); - - $tester = new CommandTester(new EjectCommand()); - - $exitCode = $tester->execute(['file' => 'config/params.php']); - - self::assertSame( - 0, - $exitCode, - 'Eject command must return success exit code when only previewing removal.', - ); - self::assertStringContainsString( - 'Would remove', - $tester->getDisplay(), - 'Eject command must indicate when it is only previewing removal.', - ); - - $data = (new LockFile($this->tempDir))->read(); - - self::assertArrayHasKey( - 'config/params.php', - $data['files'], - "Without '--yes' the lock file must remain untouched (dry-run).", - ); + if ($this->originalCwd !== '' && is_dir($this->originalCwd)) { + chdir($this->originalCwd); + } } - public function testExecuteRemovesEntryWhenConfirmedWithYesFlag(): void + /** + * Saves the working directory, seeds a tracked file and enters the project root. + */ + #[BeforeTest(priority: -10)] + public function setUpProject(): void { - $this->seedTrackedFile('config/params.php'); - - $tester = new CommandTester(new EjectCommand()); - - $exitCode = $tester->execute(['file' => 'config/params.php', '--yes' => true]); - - self::assertSame( - 0, - $exitCode, - 'Eject command must return success exit code when confirmed removal.', - ); - self::assertStringContainsString( - 'Removed', - $tester->getDisplay(), - 'Eject command must indicate when a file has been removed.', - ); + $this->originalCwd = (string) getcwd(); - $data = (new LockFile($this->tempDir))->read(); + (new InspectionProject($this->tempDir)) + ->composer(['pkg/name']) + ->provider('pkg/name', ['config/params.php' => "file('config/params.php', "track('config/params.php', 'pkg/name'); - self::assertArrayNotHasKey( - 'config/params.php', - $data['files'], - "With '--yes' the tracked entry must be removed from 'scaffold-lock.json'.", - ); + chdir($this->tempDir); } - public function testExecuteReturnsErrorWhenFileIsNotTracked(): void + /** + * Ensures only `--yes` marks the named lock entry as ejected; without it the lock is left untouched. + * + * @param array $options Command options. + */ + #[DataSet([[], false], 'without yes')] + #[DataSet([['--yes' => true], true], 'with yes')] + public function yesOptionConfirmsTheEjection(array $options, bool $ejected): void { - (new LockFile($this->tempDir))->write(['providers' => [], 'files' => []]); - $tester = new CommandTester(new EjectCommand()); - $exitCode = $tester->execute( - ['file' => 'missing.php', '--yes' => true], - ['capture_stderr_separately' => true], - ); + $exitCode = $tester->execute(['file' => 'config/params.php', ...$options]); - self::assertSame( - 1, + Assert::same( $exitCode, - 'Eject command must return error exit code when file is not tracked.', - ); - self::assertStringContainsString( - 'not tracked', - $tester->getErrorOutput(), - 'Eject of an untracked file must surface an error diagnostic on stderr.', + 0, + "Exit code must be '0'.", ); - } - public function testExecuteReturnsFailureWhenGetcwdFails(): void - { - MockerState::addCondition( - 'PHPForge\\Scaffold\\Console\\Command', - 'getcwd', - [], - false, - default: true, - ); + $entry = (new InspectionProject($this->tempDir))->lock()->read()['files']['config/params.php'] ?? null; - $tester = new CommandTester(new EjectCommand()); - - self::assertSame( - Command::FAILURE, - $tester->execute(['file' => 'config/params.php']), - 'Eject command must return failure exit code when getcwd fails.', - ); - self::assertStringContainsString( - 'Unable to determine current working directory', - $tester->getDisplay(), - 'Eject command must indicate when the current working directory cannot be determined.', + Assert::notNull( + $entry, + "Lock entry of 'config/params.php' must be kept.", ); - } - - protected function setUp(): void - { - $this->originalCwd = (string) getcwd(); - - $this->setUpTempDirectory(); - - chdir($this->tempDir); - } - - protected function tearDown(): void - { - if ($this->originalCwd !== '' && is_dir($this->originalCwd)) { - chdir($this->originalCwd); - } - - $this->tearDownTempDirectory(); - } - - private function seedTrackedFile(string $destination): void - { - (new LockFile($this->tempDir))->write( - [ - 'providers' => [], - 'files' => [ - $destination => [ - 'hash' => 'sha256:abc', - 'provider' => 'pkg/name', - 'source' => 'stubs/' . $destination, - 'mode' => 'replace', - ], - ], - ], + Assert::same( + $entry['ejected'] ?? false, + $ejected, + "Lock entry must be marked 'ejected' only with '--yes'.", ); } } diff --git a/tests/Console/Command/ProvidersCommandTest.php b/tests/Console/Command/ProvidersCommandTest.php index 40b84e5..ecc6891 100644 --- a/tests/Console/Command/ProvidersCommandTest.php +++ b/tests/Console/Command/ProvidersCommandTest.php @@ -5,138 +5,87 @@ namespace PHPForge\Scaffold\Tests\Console\Command; use PHPForge\Scaffold\Console\Command\ProvidersCommand; -use PHPForge\Scaffold\Scaffold\Lock\LockFile; -use PHPForge\Scaffold\Tests\Support\TempDirectoryTrait; -use PHPUnit\Framework\Attributes\Group; -use PHPUnit\Framework\TestCase; -use Symfony\Component\Console\Command\Command; +use PHPForge\Scaffold\Services\ProvidersService; +use PHPForge\Scaffold\Tests\Support\{BufferedOutputWriter, InspectionProject, TempDirectoryTrait}; use Symfony\Component\Console\Tester\CommandTester; -use Xepozz\InternalMocker\MockerState; +use Testo\Assert; +use Testo\Lifecycle\{AfterTest, BeforeTest}; +use Testo\Test; use function chdir; use function getcwd; use function is_dir; +use function mkdir; /** - * Unit tests for the Symfony Console {@see ProvidersCommand} verifying the provider summary output. + * Functional tests for the Symfony Console {@see ProvidersCommand} running the providers service on the project root. */ -#[Group('scaffold')] -#[Group('console-command')] -final class ProvidersCommandTest extends TestCase +#[Test] +final class ProvidersCommandTest { use TempDirectoryTrait; + /** + * Working directory before the test, restored after it. + */ private string $originalCwd = ''; - public function testExecuteListsProvidersWithFileCounts(): void + /** + * Ensures the command prints the provider summary of the project root and exits with `0`. + */ + public function printsTheProviderSummaryOfTheProjectRoot(): void { - (new LockFile($this->tempDir))->write( - [ - 'providers' => [], - 'files' => [ - 'a.txt' => [ - 'hash' => 'sha256:a', - 'provider' => 'pkg/a', - 'source' => 'stubs/a.txt', - 'mode' => 'replace', - ], - 'b.txt' => [ - 'hash' => 'sha256:b', - 'provider' => 'pkg/a', - 'source' => 'stubs/b.txt', - 'mode' => 'replace', - ], - 'c.txt' => [ - 'hash' => 'sha256:c', - 'provider' => 'pkg/b', - 'source' => 'stubs/c.txt', - 'mode' => 'preserve', - ], - ], - ], - ); + $expected = new BufferedOutputWriter(); - $tester = new CommandTester(new ProvidersCommand()); - - $exitCode = $tester->execute([]); - $display = $tester->getDisplay(); - - self::assertSame( - 0, - $exitCode, - 'Providers command must return a success exit code when providers are tracked.', - ); - self::assertMatchesRegularExpression( - '#pkg/a\s+2\b#', - $display, - "Provider 'pkg/a' must be rendered with its file count of '2' on the same row.", - ); - self::assertMatchesRegularExpression( - '#pkg/b\s+1\b#', - $display, - "Provider 'pkg/b' must be rendered with its file count of '1' on the same row.", - ); - } - - public function testExecutePrintsEmptyMessageWhenNoProvidersTracked(): void - { - (new LockFile($this->tempDir))->write(['providers' => [], 'files' => []]); + (new ProvidersService())->run($this->tempDir, $expected); $tester = new CommandTester(new ProvidersCommand()); $exitCode = $tester->execute([]); - self::assertSame( - 0, + Assert::same( $exitCode, - 'Providers command must return success exit code when no providers are tracked.', + 0, + "Exit code must be '0'.", ); - self::assertStringContainsString( - 'No providers tracked in scaffold-lock.json', + Assert::same( $tester->getDisplay(), - 'Providers command must indicate when no providers are tracked.', + $expected->stdoutBuffer, + 'Output must be the provider summary of the project root.', ); } - public function testExecuteReturnsFailureWhenGetcwdFails(): void + /** + * Restores the working directory of the runner. + */ + #[AfterTest] + public function restoreWorkingDirectory(): void { - MockerState::addCondition( - 'PHPForge\\Scaffold\\Console\\Command', - 'getcwd', - [], - false, - default: true, - ); - - $tester = new CommandTester(new ProvidersCommand()); - - self::assertSame( - Command::FAILURE, - $tester->execute([]), - 'Providers command must return failure exit code when getcwd fails.', - ); - self::assertStringContainsString( - 'Unable to determine current working directory', - $tester->getDisplay(), - 'Providers command must indicate when it cannot determine the current working directory.', - ); + if ($this->originalCwd !== '' && is_dir($this->originalCwd)) { + chdir($this->originalCwd); + } } - protected function setUp(): void + /** + * Saves the working directory, seeds files of two providers and enters a directory below the project root. + */ + #[BeforeTest(priority: -10)] + public function setUpProject(): void { $this->originalCwd = (string) getcwd(); - $this->setUpTempDirectory(); - - chdir($this->tempDir); - } - - protected function tearDown(): void - { - if ($this->originalCwd !== '' && is_dir($this->originalCwd)) { - chdir($this->originalCwd); - } - - $this->tearDownTempDirectory(); + (new InspectionProject($this->tempDir)) + ->composer(['pkg/a', 'pkg/b']) + ->provider('pkg/a', ['a.txt' => "a\n", 'b.txt' => "b\n"]) + ->provider('pkg/b', ['c.txt' => "c\n"]) + ->file('a.txt', "a\n") + ->file('b.txt', "b\n") + ->file('c.txt', "c\n") + ->track('a.txt', 'pkg/a') + ->track('b.txt', 'pkg/a') + ->track('c.txt', 'pkg/b', 'preserve'); + + mkdir("{$this->tempDir}/src"); + chdir("{$this->tempDir}/src"); } } diff --git a/tests/Console/Command/PruneCommandTest.php b/tests/Console/Command/PruneCommandTest.php new file mode 100644 index 0000000..ddc0343 --- /dev/null +++ b/tests/Console/Command/PruneCommandTest.php @@ -0,0 +1,108 @@ +execute(['--delete-modified' => true]); + + Assert::string($tester->getDisplay())->contains( + 'edited.txt p/a modified delete (modified)', + "Preview must announce 'delete (modified)' for 'edited.txt'.", + ); + } + + /** + * Ensures `--force`, `--delete-modified` and `--exit-code` decide the exit code and which orphans are deleted. + * + * @param array $options Command options. + * @param array{'old.txt': bool, 'edited.txt': bool} $kept Whether each orphan is kept. + */ + #[DataProvider(PruneCommandProvider::class . '::options')] + public function optionsDecideWhatIsPruned(array $options, int $exitCode, array $kept): void + { + $tester = new CommandTester(new PruneCommand()); + + Assert::same( + $tester->execute($options), + $exitCode, + "Exit code must be '{$exitCode}'.", + ); + Assert::same( + [ + 'old.txt' => is_file("{$this->tempDir}/old.txt"), + 'edited.txt' => is_file("{$this->tempDir}/edited.txt"), + ], + $kept, + 'Kept orphans must match.', + ); + } + + /** + * Restores the working directory of the runner. + */ + #[AfterTest] + public function restoreWorkingDirectory(): void + { + if ($this->originalCwd !== '' && is_dir($this->originalCwd)) { + chdir($this->originalCwd); + } + } + + /** + * Saves the working directory, seeds an unmodified and a modified orphan and enters the project root. + */ + #[BeforeTest(priority: -10)] + public function setUpProject(): void + { + $this->originalCwd = (string) getcwd(); + + (new InspectionProject($this->tempDir)) + ->composer(['p/a']) + ->installed(['p/a' => '1.0.0']) + ->provider('p/a', ['kept.txt' => "kept\n"]) + ->file('old.txt', "old\n") + ->track('old.txt', 'p/a') + ->file('edited.txt', "provider\n") + ->track('edited.txt', 'p/a') + ->file('edited.txt', "mine\n"); + + chdir($this->tempDir); + } +} diff --git a/tests/Console/Command/ReapplyCommandTest.php b/tests/Console/Command/ReapplyCommandTest.php index 3ffa5e3..10cce6e 100644 --- a/tests/Console/Command/ReapplyCommandTest.php +++ b/tests/Console/Command/ReapplyCommandTest.php @@ -5,215 +5,82 @@ namespace PHPForge\Scaffold\Tests\Console\Command; use PHPForge\Scaffold\Console\Command\ReapplyCommand; -use PHPForge\Scaffold\Scaffold\Lock\{Hasher, LockFile}; -use PHPForge\Scaffold\Tests\Support\TempDirectoryTrait; -use PHPUnit\Framework\Attributes\Group; -use PHPUnit\Framework\TestCase; -use Symfony\Component\Console\Command\Command; +use PHPForge\Scaffold\Tests\Provider\ReapplyCommandProvider; +use PHPForge\Scaffold\Tests\Support\{FileAssert, InspectionProject, TempDirectoryTrait}; use Symfony\Component\Console\Tester\CommandTester; -use Xepozz\InternalMocker\MockerState; +use Testo\Assert; +use Testo\Data\DataProvider; +use Testo\Lifecycle\{AfterTest, BeforeTest}; +use Testo\Test; use function chdir; use function getcwd; use function is_dir; /** - * Unit tests for the Symfony Console {@see ReapplyCommand} covering single-file reapply, filter-mismatch error, and - * the `--force` flag. + * Functional tests for the Symfony Console {@see ReapplyCommand} wiring the `file` argument and the `--force`, + * `--provider` and `--dry-run` options to the reapply service. + * + * {@see ReapplyCommandProvider} for test case data providers. */ -#[Group('scaffold')] -#[Group('console-command')] -final class ReapplyCommandTest extends TestCase +#[Test] +final class ReapplyCommandTest { use TempDirectoryTrait; + /** + * Working directory before the test, restored after it. + */ private string $originalCwd = ''; - public function testExecuteOverwritesUserModifiedFileWithForce(): void + /** + * Ensures the input decides the exit code and whether the user-modified file is overwritten with its stub. + * + * @param array $input Command input. + */ + #[DataProvider(ReapplyCommandProvider::class . '::inputs')] + public function inputDecidesWhatIsReapplied(array $input, int $exitCode, string $content): void { - $this->seedTracked( - destination: 'config/params.php', - stubContent: "original\n", - currentContent: "user-edited\n", - lockHashOf: "original\n", - ); - - $tester = new CommandTester(new ReapplyCommand()); - - $exitCode = $tester->execute(['file' => 'config/params.php', '--force' => true]); - - self::assertSame( - 0, - $exitCode, - "Reapply command must return success exit code when file is reapplied with '--force'.", - ); - self::assertStringContainsString( - 'Reapplied', - $tester->getDisplay(), - 'Reapply command must indicate when a file is reapplied.', - ); - self::assertSame( - "original\n", - (string) file_get_contents($this->tempDir . '/config/params.php'), - "'--force' must overwrite the user's content with the stub.", - ); - } - - public function testExecuteReappliesUnmodifiedFileAndReportsSuccess(): void - { - $stub = "return ['key' => 'value'];\n"; - - $this->seedTracked(destination: 'config/params.php', stubContent: $stub, currentContent: $stub); - - $tester = new CommandTester(new ReapplyCommand()); - - $exitCode = $tester->execute(['file' => 'config/params.php']); - - self::assertSame( - 0, - $exitCode, - 'Reapply command must return success exit code when file is reapplied.', - ); - self::assertStringContainsString( - 'Reapplied', - $tester->getDisplay(), - 'Reapply command must indicate when a file is reapplied.', - ); - } - - public function testExecuteReturnsErrorWhenFileFilterMatchesNothing(): void - { - (new LockFile($this->tempDir))->write(['providers' => [], 'files' => []]); - - $tester = new CommandTester(new ReapplyCommand()); - - $exitCode = $tester->execute( - ['file' => 'nonexistent.php'], - ['capture_stderr_separately' => true], - ); - - self::assertSame( - 1, - $exitCode, - 'Reapply command must return error exit code when file filter matches nothing.', - ); - self::assertStringContainsString( - 'No tracked files matched', - $tester->getErrorOutput(), - 'Reapply command must indicate when no tracked files match the filter.', - ); - } - - public function testExecuteReturnsFailureWhenGetcwdFails(): void - { - MockerState::addCondition( - 'PHPForge\\Scaffold\\Console\\Command', - 'getcwd', - [], - false, - default: true, - ); - - $tester = new CommandTester(new ReapplyCommand()); - - self::assertSame( - Command::FAILURE, - $tester->execute([]), - 'Reapply command must return failure exit code when getcwd fails.', - ); - self::assertStringContainsString( - 'Unable to determine current working directory', - $tester->getDisplay(), - 'Reapply command must indicate when it cannot determine the current working directory.', - ); - } - - public function testExecuteSkipsUserModifiedFileWithoutForce(): void - { - $this->seedTracked( - destination: 'config/params.php', - stubContent: "original\n", - currentContent: "user-edited\n", - lockHashOf: "original\n", - ); - $tester = new CommandTester(new ReapplyCommand()); - $exitCode = $tester->execute(['file' => 'config/params.php']); - - self::assertSame( - 0, + Assert::same( + $tester->execute($input), $exitCode, - 'Reapply command must return success exit code when user-modified file is skipped without force.', + "Exit code must be '{$exitCode}'.", ); - self::assertStringContainsString( - 'user-modified', - $tester->getDisplay(), - 'Reapply command must indicate when a user-modified file is skipped without force.', + FileAssert::contentSame( + "{$this->tempDir}/config/params.php", + $content, + "Content of 'config/params.php' must match.", ); } - protected function setUp(): void - { - $this->originalCwd = (string) getcwd(); - - $this->setUpTempDirectory(); - - chdir($this->tempDir); - } - - protected function tearDown(): void + /** + * Restores the working directory of the runner. + */ + #[AfterTest] + public function restoreWorkingDirectory(): void { if ($this->originalCwd !== '' && is_dir($this->originalCwd)) { chdir($this->originalCwd); } - - $this->tearDownTempDirectory(); } - private function seedTracked( - string $destination, - string $stubContent, - string $currentContent, - string|null $lockHashOf = null, - ): void { - $providerRoot = "{$this->tempDir}/vendor/pkg/name"; - $stubRelative = "stubs/{$destination}"; - $stubPath = "{$providerRoot}/{$stubRelative}"; - - $this->ensureTestDirectory(dirname($stubPath)); - - file_put_contents($stubPath, $stubContent); - - $destAbsolute = "{$this->tempDir}/{$destination}"; - - $this->ensureTestDirectory(dirname($destAbsolute)); - - file_put_contents($destAbsolute, $currentContent); - - $hasher = new Hasher(); + /** + * Saves the working directory, seeds a tracked file the user modified and enters the project root. + */ + #[BeforeTest(priority: -10)] + public function setUpProject(): void + { + $this->originalCwd = (string) getcwd(); - $lockHash = $lockHashOf !== null - ? 'sha256:' . hash('sha256', $lockHashOf) - : $hasher->hash($destAbsolute); + (new InspectionProject($this->tempDir)) + ->composer(['pkg/name']) + ->provider('pkg/name', ['config/params.php' => "original\n"]) + ->file('config/params.php', "original\n") + ->track('config/params.php', 'pkg/name') + ->file('config/params.php', "user-edited\n"); - (new LockFile($this->tempDir))->write( - [ - 'providers' => [ - 'pkg/name' => [ - 'version' => '0.1.x-dev', - 'path' => 'vendor/pkg/name', - ], - ], - 'files' => [ - $destination => [ - 'hash' => $lockHash, - 'provider' => 'pkg/name', - 'source' => $stubRelative, - 'mode' => 'replace', - ], - ], - ], - ); + chdir($this->tempDir); } } diff --git a/tests/Console/Command/StatusCommandTest.php b/tests/Console/Command/StatusCommandTest.php index 96673e7..131ddf4 100644 --- a/tests/Console/Command/StatusCommandTest.php +++ b/tests/Console/Command/StatusCommandTest.php @@ -4,157 +4,81 @@ namespace PHPForge\Scaffold\Tests\Console\Command; -use PHPForge\Scaffold\Console\Command\StatusCommand; -use PHPForge\Scaffold\Scaffold\Lock\{Hasher, LockFile}; +use PHPForge\Scaffold\Console\Command\{AbstractScaffoldCommand, StatusCommand}; +use PHPForge\Scaffold\Console\Message; use PHPForge\Scaffold\Tests\Support\TempDirectoryTrait; -use PHPUnit\Framework\Attributes\Group; -use PHPUnit\Framework\TestCase; -use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Tester\CommandTester; -use Xepozz\InternalMocker\MockerState; +use Testo\Assert; +use Testo\Core\Exception\SkipTest; +use Testo\Lifecycle\{AfterTest, BeforeTest}; +use Testo\Test; use function chdir; use function getcwd; use function is_dir; +use function mkdir; +use function rmdir; /** - * Unit tests for the Symfony Console {@see StatusCommand} verifying the status listing against a real - * `scaffold-lock.json` written to a temporary project root. + * Functional tests for the Symfony Console {@see StatusCommand} covering the project root resolution of + * {@see AbstractScaffoldCommand} when the current working directory is gone. */ -#[Group('scaffold')] -#[Group('console-command')] -final class StatusCommandTest extends TestCase +#[Test] +final class StatusCommandTest { use TempDirectoryTrait; + /** + * Working directory before the test, restored after it. + */ private string $originalCwd = ''; - public function testExecutePrintsEmptyMessageWhenNoFilesTracked(): void + /** + * Restores the working directory of the runner. + */ + #[AfterTest] + public function restoreWorkingDirectory(): void { - (new LockFile($this->tempDir))->write(['providers' => [], 'files' => []]); - - $tester = new CommandTester(new StatusCommand()); - - $exitCode = $tester->execute([]); - - self::assertSame( - 0, - $exitCode, - 'Empty-lock status must still return a success exit code.', - ); - self::assertStringContainsString( - 'No files tracked in scaffold-lock.json', - $tester->getDisplay(), - 'Empty-lock case must emit the user-facing no-files message instead of a blank table.', - ); + if ($this->originalCwd !== '' && is_dir($this->originalCwd)) { + chdir($this->originalCwd); + } } - public function testExecutePrintsHeaderAndRowsForTrackedFiles(): void + /** + * Ensures a removed current working directory fails with the unresolvable working directory error. + */ + public function returnsFailureWhenTheWorkingDirectoryIsGone(): void { - $filePath = "{$this->tempDir}/output.txt"; - - file_put_contents($filePath, 'stub content'); + if (DIRECTORY_SEPARATOR === '\\') { + throw new SkipTest('Windows does not remove the current working directory.'); + } - $hash = (new Hasher())->hash($filePath); + $removed = "{$this->tempDir}/removed"; - (new LockFile($this->tempDir))->write( - [ - 'providers' => [], - 'files' => [ - 'output.txt' => [ - 'hash' => $hash, - 'provider' => 'pkg/name', - 'source' => 'stubs/output.txt', - 'mode' => 'replace', - ], - ], - ], - ); + mkdir($removed); + chdir($removed); + rmdir($removed); $tester = new CommandTester(new StatusCommand()); - $exitCode = $tester->execute([]); - - $display = $tester->getDisplay(); - - self::assertSame( - 0, - $exitCode, - 'Status command must return success exit code when files are tracked.', - ); - self::assertStringContainsString( - 'File', - $display, - 'Status output must include a header with a "File" column.', - ); - self::assertStringContainsString( - 'Provider', - $display, - 'Status output must include a header with a "Provider" column.', - ); - self::assertStringContainsString( - 'Mode', - $display, - 'Status output must include a header with a "Mode" column.', - ); - self::assertStringContainsString( - 'Status', - $display, - 'Status output must include a header with a "Status" column.', - ); - self::assertStringContainsString( - 'output.txt', - $display, - 'Status output must include the tracked file name.', + Assert::same( + $tester->execute([]), + 1, + "Exit code must be '1'.", ); - self::assertStringContainsString( - 'synced', - $display, - 'Status output must indicate the file is synced.', - ); - } - - public function testExecuteReturnsFailureWhenGetcwdFails(): void - { - MockerState::addCondition( - 'PHPForge\\Scaffold\\Console\\Command', - 'getcwd', - [], - false, - default: true, - ); - - $tester = new CommandTester(new StatusCommand()); - - $exitCode = $tester->execute([]); - - self::assertSame( - Command::FAILURE, - $exitCode, - "When 'getcwd()' returns 'false', the command must fail fast instead of propagating an empty project root.", - ); - self::assertStringContainsString( - 'Unable to determine current working directory', + Assert::same( $tester->getDisplay(), - 'A clear diagnostic must be written to output when the CWD cannot be determined.', + Message::COMMAND_CWD_UNRESOLVABLE->getMessage() . PHP_EOL, + 'Output must hold only the unresolvable working directory error.', ); } - protected function setUp(): void + /** + * Saves the working directory of the runner. + */ + #[BeforeTest] + public function saveWorkingDirectory(): void { $this->originalCwd = (string) getcwd(); - - $this->setUpTempDirectory(); - - chdir($this->tempDir); - } - - protected function tearDown(): void - { - if ($this->originalCwd !== '' && is_dir($this->originalCwd)) { - chdir($this->originalCwd); - } - - $this->tearDownTempDirectory(); } } diff --git a/tests/Console/Command/SyncCommandTest.php b/tests/Console/Command/SyncCommandTest.php new file mode 100644 index 0000000..3527c62 --- /dev/null +++ b/tests/Console/Command/SyncCommandTest.php @@ -0,0 +1,129 @@ +execute(['--dry-run' => true, '--exit-code' => true]), + 1, + "Exit code must be '1'.", + ); + FileAssert::fileDoesNotExist( + "{$this->tempDir}/a.txt", + "Dry run must not write 'a.txt'.", + ); + FileAssert::fileDoesNotExist( + "{$this->tempDir}/scaffold-lock.json", + 'Dry run must not write the lock.', + ); + } + + /** + * Ensures only `--force` overwrites a user edit of a synced file with its stub. + * + * @param array $options Command options. + */ + #[DataSet([[], "mine\n"], 'without force')] + #[DataSet([['--force' => true], "a\n"], 'with force')] + public function forceOptionDecidesWhetherUserEditsAreOverwritten(array $options, string $content): void + { + (new CommandTester(new SyncCommand()))->execute([]); + + file_put_contents("{$this->tempDir}/a.txt", "mine\n"); + + Assert::same( + (new CommandTester(new SyncCommand()))->execute($options), + 0, + "Exit code must be '0'.", + ); + FileAssert::contentSame( + "{$this->tempDir}/a.txt", + $content, + "Content of 'a.txt' must match.", + ); + } + + /** + * Restores the working directory of the runner. + */ + #[AfterTest] + public function restoreWorkingDirectory(): void + { + if ($this->originalCwd !== '' && is_dir($this->originalCwd)) { + chdir($this->originalCwd); + } + } + + /** + * Saves the working directory, seeds an installed provider and enters the project root. + */ + #[BeforeTest(priority: -10)] + public function setUpProject(): void + { + $this->originalCwd = (string) getcwd(); + + (new InspectionProject($this->tempDir)) + ->composer(['p/a']) + ->installed(['p/a' => '1.0.0']) + ->provider('p/a', ['a.txt' => "a\n"]); + + chdir($this->tempDir); + } + + /** + * Ensures a sync writes the provider files and creates the lock. + */ + public function syncWritesTheProviderFilesAndTheLock(): void + { + $tester = new CommandTester(new SyncCommand()); + + Assert::same( + $tester->execute([]), + 0, + "Exit code must be '0'.", + ); + FileAssert::contentSame( + "{$this->tempDir}/a.txt", + "a\n", + "File 'a.txt' must be written.", + ); + FileAssert::fileExists( + "{$this->tempDir}/scaffold-lock.json", + 'Lock must be created.', + ); + } +} diff --git a/tests/Console/ComposerIoWriterTest.php b/tests/Console/ComposerIoWriterTest.php new file mode 100644 index 0000000..beb341b --- /dev/null +++ b/tests/Console/ComposerIoWriterTest.php @@ -0,0 +1,75 @@ +errors))->write($messages, $newline); + } + }; + + $writer = new ComposerIoWriter($io); + + $writer->writeStdout('[scaffold] out'); + $writer->writeStderr('[scaffold] err'); + + rewind($errors); + + Assert::same( + $io->getOutput(), + '[scaffold] out' . PHP_EOL, + "Stdout must reach 'write()'.", + ); + Assert::same( + stream_get_contents($errors), + '[scaffold] err' . PHP_EOL, + "Stderr must reach 'writeError()'.", + ); + } +} diff --git a/tests/Console/DiffColorizerTest.php b/tests/Console/DiffColorizerTest.php index dfa363f..93cf268 100644 --- a/tests/Console/DiffColorizerTest.php +++ b/tests/Console/DiffColorizerTest.php @@ -5,116 +5,31 @@ namespace PHPForge\Scaffold\Tests\Console; use PHPForge\Scaffold\Console\DiffColorizer; -use PHPUnit\Framework\Attributes\Group; -use PHPUnit\Framework\TestCase; - -use function explode; +use PHPForge\Scaffold\Tests\Provider\DiffColorizerProvider; +use Testo\Assert; +use Testo\Codecov\Covers; +use Testo\Data\DataProvider; +use Testo\Test; /** * Unit tests for {@see DiffColorizer} ANSI styling of unified diff lines. + * + * {@see DiffColorizerProvider} for test case data providers. */ -#[Group('scaffold')] -#[Group('console')] -final class DiffColorizerTest extends TestCase +#[Test] +#[Covers(DiffColorizer::class)] +final class DiffColorizerTest { - public function testColorizeLeavesContextLinesUnstyled(): void - { - self::assertSame( - ' context', - self::colorizedLine(self::sampleDiff(), 3), - 'Context lines must carry no escape codes.', - ); - } - - public function testColorizeLeavesNoNewlineMarkerUnstyled(): void - { - self::assertSame( - '\\ No newline at end of file', - self::colorizedLine(self::sampleDiff(), 6), - 'The backslash marker must carry no escape codes.', - ); - } - - public function testColorizeStylesRemovedLineStartingWithDashesAsRemoved(): void - { - $diff = "--- a/notes.md\n+++ b/notes.md\n@@ -1 +1 @@\n--- section marker\n+updated"; - - self::assertSame( - "\e[31m--- section marker\e[0m", - self::colorizedLine($diff, 3), - 'A body line rendering as three dashes must be red, not bold.', - ); - } - - public function testColorizeWrapsAddedLinesInGreen(): void - { - self::assertSame( - "\e[32m+new\e[0m", - self::colorizedLine(self::sampleDiff(), 5), - 'Added lines must be wrapped in green.', - ); - } - - public function testColorizeWrapsFileHeaderLinesInBold(): void - { - self::assertSame( - "\e[1m--- a/config/params.php\e[0m", - self::colorizedLine(self::sampleDiff(), 0), - "The 'a/' header must be wrapped in bold.", - ); - self::assertSame( - "\e[1m+++ b/config/params.php\e[0m", - self::colorizedLine(self::sampleDiff(), 1), - "The 'b/' header must be wrapped in bold.", - ); - } - - public function testColorizeWrapsHunkHeadersInCyan(): void - { - self::assertSame( - "\e[36m@@ -1,2 +1,2 @@\e[0m", - self::colorizedLine(self::sampleDiff(), 2), - 'Hunk headers must be wrapped in cyan.', - ); - } - - public function testColorizeWrapsRemovedLinesInRed(): void - { - self::assertSame( - "\e[31m-old\e[0m", - self::colorizedLine(self::sampleDiff(), 4), - 'Removed lines must be wrapped in red.', - ); - } - /** - * Colorizes `$diff` and returns the line at `$index`. - * - * @param string $diff Unified diff to colorize. - * @param int $index Zero-based line position within the colorized output. - * - * @return string Colorized line at the requested position, or an empty string when out of range. + * Ensures each line kind gets its style: bold headers, cyan hunks, green additions, red removals, plain others. */ - private static function colorizedLine(string $diff, int $index): string + #[DataProvider(DiffColorizerProvider::class . '::lines')] + public function stylesEachLineKind(string $diff, string $expected): void { - $lines = explode("\n", (new DiffColorizer())->colorize($diff)); - - return $lines[$index] ?? ''; - } - - /** - * Builds a representative unified diff covering every line kind the colorizer styles. - * - * @return string Unified diff with headers, hunk, context, removed, added, and no-newline marker lines. - */ - private static function sampleDiff(): string - { - return "--- a/config/params.php\n" - . "+++ b/config/params.php\n" - . "@@ -1,2 +1,2 @@\n" - . " context\n" - . "-old\n" - . "+new\n" - . '\\ No newline at end of file'; + Assert::same( + (new DiffColorizer())->colorize($diff), + $expected, + 'Colorized diff must match the expected styling.', + ); } } diff --git a/tests/Console/MessageTest.php b/tests/Console/MessageTest.php new file mode 100644 index 0000000..4f867f4 --- /dev/null +++ b/tests/Console/MessageTest.php @@ -0,0 +1,37 @@ + $arguments + */ + #[DataProvider(ConsoleMessageProvider::class . '::cases')] + public function rendersThePinnedLiteral(Message $case, array $arguments, string $expected): void + { + Assert::same( + $case->getMessage(...$arguments), + $expected, + 'Rendered message must match the pinned literal.', + ); + } +} diff --git a/tests/Console/SymfonyOutputWriterTest.php b/tests/Console/SymfonyOutputWriterTest.php index 90ded4b..35b7ac2 100644 --- a/tests/Console/SymfonyOutputWriterTest.php +++ b/tests/Console/SymfonyOutputWriterTest.php @@ -5,92 +5,54 @@ namespace PHPForge\Scaffold\Tests\Console; use PHPForge\Scaffold\Console\SymfonyOutputWriter; -use PHPUnit\Framework\Attributes\Group; -use PHPUnit\Framework\TestCase; -use Symfony\Component\Console\Output\BufferedOutput; -use Symfony\Component\Console\Output\ConsoleOutput; -use Symfony\Component\Console\Output\OutputInterface; +use PHPForge\Scaffold\Tests\Provider\SymfonyOutputWriterProvider; +use Symfony\Component\Console\Output\{BufferedOutput, ConsoleOutput, OutputInterface}; +use Testo\Assert; +use Testo\Codecov\Covers; +use Testo\Data\DataProvider; +use Testo\Test; /** - * Unit tests for {@see SymfonyOutputWriter} verifying that stdout / stderr writes bypass Symfony's output formatter so - * pre-formatted service messages (for example, diffs that contain angle-bracket tokens) land verbatim. + * Unit tests for {@see SymfonyOutputWriter} verifying that stdout and stderr writes bypass Symfony's output formatter, + * so pre-formatted service messages (for example, diffs that contain angle-bracket tokens) land verbatim. + * + * {@see SymfonyOutputWriterProvider} for test case data providers. */ -#[Group('scaffold')] -#[Group('console')] -final class SymfonyOutputWriterTest extends TestCase +#[Test] +#[Covers(SymfonyOutputWriter::class)] +final class SymfonyOutputWriterTest { - public function testWriteStderrFallsBackToPrimaryOutputWhenNotConsoleOutputInterface(): void - { - $output = new BufferedOutput(); - - (new SymfonyOutputWriter($output))->writeStderr('plain fallback'); - - self::assertSame( - 'plain fallback' . PHP_EOL, - $output->fetch(), - "Without 'ConsoleOutputInterface', stderr writes must fall back to the primary output with a trailing newline.", - ); - } - - public function testWriteStderrRoutesThroughErrorOutputOfConsoleOutputInterface(): void + /** + * Ensures the message lands verbatim with one trailing newline on the stream of the write method. + * + * @param string $method Write method under test, `writeStdout` or `writeStderr`. + * @param bool $console Whether the writer wraps a console output whose error output is the buffer. + * @param bool $decorated Whether the buffer is decorated. + */ + #[DataProvider(SymfonyOutputWriterProvider::class . '::writes')] + public function writesTheMessageVerbatim(string $method, bool $console, bool $decorated, string $message): void { - $console = new ConsoleOutput(); + $buffer = new BufferedOutput(OutputInterface::VERBOSITY_NORMAL, $decorated); - self::assertInstanceOf( - BufferedOutput::class, - $this->overrideErrorOutput($console), - 'Test setup: the error output must be swapped for a BufferedOutput so we can read it back.', - ); + $output = $buffer; - (new SymfonyOutputWriter($console))->writeStderr('error line'); + if ($console) { + $output = new ConsoleOutput(); - /** @var BufferedOutput $swapped */ - $swapped = $console->getErrorOutput(); + $output->setErrorOutput($buffer); + } - self::assertSame( - 'error line' . PHP_EOL, - $swapped->fetch(), - "'writeStderr' must route through 'getErrorOutput()' and preserve angle-bracket tokens verbatim.", - ); - } - public function testWriteStdoutEmitsAngleBracketTokensVerbatimWithoutFormatterInterpretation(): void - { - $output = new BufferedOutput(); + $writer = new SymfonyOutputWriter($output); - (new SymfonyOutputWriter($output))->writeStdout(''); + match ($method) { + 'writeStderr' => $writer->writeStderr($message), + default => $writer->writeStdout($message), + }; - self::assertSame( - '' . PHP_EOL, - $output->fetch(), - 'Angle-bracket tokens inside a stdout write must survive verbatim without Symfony formatter interpretation.', + Assert::same( + $buffer->fetch(), + $message . PHP_EOL, + "Message must land verbatim on the '{$method}' stream.", ); } - - public function testWriteStdoutEmitsSymfonyStyleTagsLiterallyWithoutApplyingAnsi(): void - { - $output = new BufferedOutput(OutputInterface::VERBOSITY_NORMAL, decorated: true); - - (new SymfonyOutputWriter($output))->writeStdout('hello'); - - self::assertSame( - 'hello' . PHP_EOL, - $output->fetch(), - 'Symfony-style tags must be written literally (no ANSI codes) even when decoration is enabled.', - ); - } - - /** - * Overrides the error output of a ConsoleOutput instance with a BufferedOutput for testing purposes. - * - * @param ConsoleOutput $console ConsoleOutput instance to modify. - * - * @return BufferedOutput BufferedOutput instance used as the new error output. - */ - private function overrideErrorOutput(ConsoleOutput $console): BufferedOutput - { - $buffered = new BufferedOutput(); - $console->setErrorOutput($buffered); - - return $buffered; - } } diff --git a/tests/Console/TableTest.php b/tests/Console/TableTest.php new file mode 100644 index 0000000..4eb966f --- /dev/null +++ b/tests/Console/TableTest.php @@ -0,0 +1,35 @@ +tempDir), - "Absolute 'COMPOSER_VENDOR_DIR' must have its trailing separator stripped.", - ); - } - - public function testAbsolutePosixPathEndingInDriveRootSubstringIsNotMisclassifiedAsDriveRoot(): void - { - putenv('COMPOSER_VENDOR_DIR=/foo/C:/'); - - self::assertSame( - '/foo/C:', - VendorDirResolver::resolve($this->tempDir), - "An absolute POSIX path ending in 'X:/' must not be preserved by the drive-root short-circuit.", - ); - } - - public function testComposerJsonAbsoluteVendorDirIsHonored(): void - { - file_put_contents( - $this->tempDir . '/composer.json', - json_encode(['config' => ['vendor-dir' => '/opt/shared-vendor']]), - ); - - self::assertSame( - '/opt/shared-vendor', - VendorDirResolver::resolve($this->tempDir), - "Absolute 'config.vendor-dir' paths must be used verbatim.", - ); - } - - public function testComposerJsonConfigVendorDirIsHonored(): void - { - file_put_contents( - $this->tempDir . '/composer.json', - json_encode(['config' => ['vendor-dir' => 'third-party']]), - ); - - self::assertSame( - $this->tempDir . '/third-party', - VendorDirResolver::resolve($this->tempDir), - "Relative 'config.vendor-dir' must resolve against the project root.", - ); - } - - public function testDefaultVendorFallbackStripsTrailingSeparatorFromProjectRoot(): void - { - self::assertSame( - $this->tempDir . '/vendor', - VendorDirResolver::resolve($this->tempDir . '/'), - "Default vendor fallback must strip trailing '/' from 'projectRoot' to avoid '//vendor'.", - ); - } - - public function testDriveLetterInMiddleOfRelativePathDoesNotTriggerAbsoluteBranch(): void - { - putenv('COMPOSER_VENDOR_DIR=prefix/C:/suffix'); - - self::assertSame( - $this->tempDir . '/prefix/C:/suffix', - VendorDirResolver::resolve($this->tempDir), - "A drive-letter substring mid-path ('C:/') must not trigger the absolute branch.", - ); - } - - public function testEnvVariableRelativePathResolvedAgainstProjectRoot(): void - { - putenv('COMPOSER_VENDOR_DIR=custom-vendor'); - - self::assertSame( - $this->tempDir . '/custom-vendor', - VendorDirResolver::resolve($this->tempDir), - 'A relative env value must be anchored to the project root.', - ); - } - - public function testEnvVariableTakesPriorityOverComposerJson(): void - { - file_put_contents( - $this->tempDir . '/composer.json', - json_encode(['config' => ['vendor-dir' => 'ignored']]), - ); - - putenv('COMPOSER_VENDOR_DIR=/absolute/env-vendor'); - - self::assertSame( - '/absolute/env-vendor', - VendorDirResolver::resolve($this->tempDir), - "'COMPOSER_VENDOR_DIR' environment variable must take priority over 'composer.json'.", - ); - } - - public function testFallsBackToDefaultWhenComposerJsonHasNoVendorDirConfig(): void - { - file_put_contents( - $this->tempDir . '/composer.json', - json_encode(['name' => 'test/no-vendor-dir-config']), - ); - - self::assertSame( - $this->tempDir . '/vendor', - VendorDirResolver::resolve($this->tempDir), - "When 'composer.json' has no 'config.vendor-dir' entry, the default must be returned.", - ); - } - - public function testFallsBackToDefaultWhenComposerJsonIsInvalidJson(): void - { - file_put_contents($this->tempDir . '/composer.json', '{ invalid json '); - - self::assertSame( - $this->tempDir . '/vendor', - VendorDirResolver::resolve($this->tempDir), - "Malformed 'composer.json' must degrade gracefully to the default vendor directory.", - ); - } - - public function testFallsBackToDefaultWhenComposerJsonVendorDirIsEmptyString(): void - { - file_put_contents( - $this->tempDir . '/composer.json', - json_encode(['config' => ['vendor-dir' => '']]), - ); - - self::assertSame( - $this->tempDir . '/vendor', - VendorDirResolver::resolve($this->tempDir), - "An empty 'config.vendor-dir' must be treated as unset.", - ); - } - - public function testFallsBackToDefaultWhenNoComposerJsonExists(): void - { - self::assertSame( - $this->tempDir . '/vendor', - VendorDirResolver::resolve($this->tempDir), - "When no 'composer.json' is present, the default '/vendor' must be returned.", - ); - } - - public function testTrimsTrailingSeparatorFromProjectRootAndVendorDir(): void - { - file_put_contents( - $this->tempDir . '/composer.json', - json_encode(['config' => ['vendor-dir' => 'custom/']]), - ); - - self::assertSame( - $this->tempDir . '/custom', - VendorDirResolver::resolve($this->tempDir . '/'), - 'Trailing separators in project root and vendor-dir must not produce a double separator.', - ); - } - - public function testWindowsAbsoluteDrivePathIsHonoredVerbatim(): void - { - putenv('COMPOSER_VENDOR_DIR=C:\\opt\\vendor'); - - self::assertSame( - 'C:\\opt\\vendor', - VendorDirResolver::resolve($this->tempDir), - "An absolute Windows path ('C:\\\\opt\\\\vendor') must be used verbatim without joining to the project root.", - ); - } - - public function testWindowsDriveRelativePathIsTreatedAsRelativeAndJoinedWithProjectRoot(): void - { - putenv('COMPOSER_VENDOR_DIR=C:vendor'); - - self::assertSame( - $this->tempDir . '/C:vendor', - VendorDirResolver::resolve($this->tempDir), - "Windows drive-relative 'C:vendor' (no separator after the drive letter) must be resolved under the root.", - ); - } - - public function testWindowsDriveRootPreservesTrailingSeparator(): void - { - putenv('COMPOSER_VENDOR_DIR=C:\\'); - - self::assertSame( - 'C:\\', - VendorDirResolver::resolve($this->tempDir), - "The drive root 'C:\\\\' must keep its trailing separator to stay absolute (not drive-relative 'C:').", - ); - } - - public function testWindowsDriveRootWithForwardSlashPreservesTrailingSeparator(): void - { - putenv('COMPOSER_VENDOR_DIR=D:/'); - - self::assertSame( - 'D:/', - VendorDirResolver::resolve($this->tempDir), - 'Forward-slash drive roots must also keep their trailing separator intact for the same reason.', - ); - } - - protected function setUp(): void - { - $this->setUpTempDirectory(); - - $this->originalEnv = getenv('COMPOSER_VENDOR_DIR'); - - putenv('COMPOSER_VENDOR_DIR'); - } - - protected function tearDown(): void - { - if ($this->originalEnv === false) { - putenv('COMPOSER_VENDOR_DIR'); - } else { - putenv('COMPOSER_VENDOR_DIR=' . $this->originalEnv); - } - - $this->tearDownTempDirectory(); - } -} diff --git a/tests/EventSubscriberTest.php b/tests/EventSubscriberTest.php index fbafde5..17f88c3 100644 --- a/tests/EventSubscriberTest.php +++ b/tests/EventSubscriberTest.php @@ -7,204 +7,169 @@ use Composer\Composer; use Composer\Config; use Composer\IO\BufferIO; -use Composer\Package\RootPackageInterface; +use Composer\Package\RootPackage; use Composer\Script\Event as ScriptEvent; use Composer\Script\ScriptEvents; +use PHPForge\Scaffold\Console\Message; use PHPForge\Scaffold\EventSubscriber; -use PHPUnit\Framework\Attributes\Group; -use PHPUnit\Framework\TestCase; -use ReflectionClass; +use PHPForge\Scaffold\Tests\Provider\EventSubscriberProvider; +use ReflectionProperty; +use Testo\Assert; +use Testo\Codecov\Covers; +use Testo\Data\DataProvider; +use Testo\Lifecycle\{AfterTest, BeforeTest}; +use Testo\Test; /** - * Unit tests for {@see EventSubscriber} event registration. + * Unit tests for {@see EventSubscriber} event registration, the `extra.scaffold.auto` guard, the vendor directory + * guard, and the single run per Composer process. + * + * Every Composer instance has an empty `vendor-dir`, so a run that passes the `auto` guard stops at the vendor + * directory guard with an error. + * + * {@see EventSubscriberProvider} for test case data providers. */ -#[Group('scaffold')] -final class EventSubscriberTest extends TestCase +#[Test] +#[Covers(EventSubscriber::class)] +final class EventSubscriberTest { - public function testOnPostCreateProjectShortCircuitsWhenInstallScaffoldRanIsTrue(): void + /** + * Ensures `auto: false` skips the run and writes only the notice. + */ + public function autoFalseSkipsTheRunWithANotice(): void { - $reflection = new ReflectionClass(EventSubscriber::class); - - $property = $reflection->getProperty('installScaffoldRan'); - - $property->setValue(null, true); - $io = new BufferIO(); - $config = self::createStub(Config::class); - - // An empty 'vendor-dir' would cause 'runScaffold' to write the 'Unable to resolve vendor-dir' error message. - // The early return must prevent 'runScaffold' from being reached, so the buffer must remain empty. - $config->method('get')->willReturn(''); - - $composer = self::createStub(Composer::class); - - $composer->method('getConfig')->willReturn($config); - - (new EventSubscriber())->onPostCreateProject( - new ScriptEvent(ScriptEvents::POST_CREATE_PROJECT_CMD, $composer, $io, true), + (new EventSubscriber())->onPostInstall( + self::event(ScriptEvents::POST_INSTALL_CMD, ['scaffold' => ['auto' => false]], $io), ); - self::assertSame( - '', + Assert::same( $io->getOutput(), - "'onPostCreateProject' must short-circuit silently when 'installScaffoldRan' is 'true'.", - ); - } - public function testRegistersPostCreateProjectCmd(): void - { - self::assertArrayHasKey( - ScriptEvents::POST_CREATE_PROJECT_CMD, - EventSubscriber::getSubscribedEvents(), - 'Event subscriber does not register for the post-create-project-cmd event.', - ); - } - - public function testRegistersPostInstallCmd(): void - { - self::assertArrayHasKey( - ScriptEvents::POST_INSTALL_CMD, - EventSubscriber::getSubscribedEvents(), - 'Event subscriber does not register for the post-install-cmd event.', + Message::SCAFFOLD_AUTO_DISABLED->getMessage() . PHP_EOL, + 'Only the auto-disabled notice may be written.', ); } - public function testRegistersPostUpdateCmd(): void - { - self::assertArrayHasKey( - ScriptEvents::POST_UPDATE_CMD, - EventSubscriber::getSubscribedEvents(), - 'Event subscriber does not register for the post-update-cmd event.', - ); - } - - public function testRunScaffoldAbortsWhenVendorDirIsEmpty(): void + /** + * Ensures `post-create-project-cmd` runs when no install or update ran before it. + */ + public function postCreateProjectRunsWhenNoInstallOrUpdateRan(): void { $io = new BufferIO(); - $config = self::createStub(Config::class); - - $config->method('get')->willReturn(''); - - $composer = self::createStub(Composer::class); - - $composer->method('getConfig')->willReturn($config); - - (new EventSubscriber())->onPostInstall( - new ScriptEvent(ScriptEvents::POST_INSTALL_CMD, $composer, $io, true), - ); + (new EventSubscriber())->onPostCreateProject(self::event(ScriptEvents::POST_CREATE_PROJECT_CMD, [], $io)); - self::assertStringContainsString( - 'Unable to resolve vendor-dir', + Assert::same( $io->getOutput(), - 'An empty vendor-dir must short-circuit the scaffold run with a clear error on stderr.', + Message::SCAFFOLD_VENDOR_DIR_UNRESOLVABLE->getMessage() . PHP_EOL, + 'The run must reach the vendor directory guard.', ); } - public function testRunScaffoldProceedsWhenScaffoldExtraIsNotArray(): void + /** + * Ensures `post-create-project-cmd` writes nothing after `post-install-cmd` ran. + */ + public function postCreateProjectSkipsTheRunAfterPostInstall(): void { - // 'extra.scaffold' set to a non-array value must default to auto-enabled, so the run proceeds and the - // vendor-dir guard fires its error (proving the auto check did not short-circuit). + $subscriber = new EventSubscriber(); $io = new BufferIO(); - $config = self::createStub(Config::class); - - $config->method('get')->willReturn(''); + $subscriber->onPostInstall(self::event(ScriptEvents::POST_INSTALL_CMD, [], new BufferIO())); + $subscriber->onPostCreateProject(self::event(ScriptEvents::POST_CREATE_PROJECT_CMD, [], $io)); - $package = self::createStub(RootPackageInterface::class); - - $package->method('getExtra')->willReturn(['scaffold' => 'not-an-array']); - - $composer = self::createStub(Composer::class); - - $composer->method('getConfig')->willReturn($config); - $composer->method('getPackage')->willReturn($package); - - (new EventSubscriber())->onPostInstall( - new ScriptEvent(ScriptEvents::POST_INSTALL_CMD, $composer, $io, true), - ); - - self::assertStringContainsString( - 'Unable to resolve vendor-dir', + Assert::same( $io->getOutput(), - 'Non-array "extra.scaffold" must be treated as auto-enabled and let the run proceed past the auto guard.', + '', + 'The second run must write nothing.', ); } - public function testRunScaffoldRespectsAutoFalseFlag(): void + /** + * Ensures `post-create-project-cmd` writes nothing after `post-update-cmd` ran. + */ + public function postCreateProjectSkipsTheRunAfterPostUpdate(): void { + $subscriber = new EventSubscriber(); $io = new BufferIO(); - $config = self::createStub(Config::class); - - // Empty 'vendor-dir' would emit the resolve error if reached; the auto guard must fire first. - $config->method('get')->willReturn(''); - - $package = self::createStub(RootPackageInterface::class); - - $package->method('getExtra')->willReturn(['scaffold' => ['auto' => false]]); - - $composer = self::createStub(Composer::class); - - $composer->method('getConfig')->willReturn($config); - $composer->method('getPackage')->willReturn($package); + $subscriber->onPostUpdate(self::event(ScriptEvents::POST_UPDATE_CMD, [], new BufferIO())); + $subscriber->onPostCreateProject(self::event(ScriptEvents::POST_CREATE_PROJECT_CMD, [], $io)); - (new EventSubscriber())->onPostInstall( - new ScriptEvent(ScriptEvents::POST_INSTALL_CMD, $composer, $io, true), - ); - - self::assertStringContainsString( - 'Auto-scaffold disabled', - $io->getOutput(), - 'Explicit "extra.scaffold.auto = false" must short-circuit auto-trigger with a clear notice.', - ); - self::assertStringNotContainsString( - 'Unable to resolve vendor-dir', + Assert::same( $io->getOutput(), - 'When auto is disabled, the run must return BEFORE the vendor-dir guard.', + '', + 'The second run must write nothing.', ); } - public function testRunScaffoldRunsWhenAutoFlagIsExplicitlyTrue(): void + /** + * Clears the process-wide run flag, so no test depends on the handlers that ran before it. + */ + #[BeforeTest] + #[AfterTest] + public function resetScaffoldRanFlag(): void { - // Explicit 'auto: true' must behave identical to the default and let the run proceed; we assert via the - // vendor-dir guard which fires further down the runScaffold pipeline. - $io = new BufferIO(); - - $config = self::createStub(Config::class); - - $config->method('get')->willReturn(''); - - $package = self::createStub(RootPackageInterface::class); - - $package->method('getExtra')->willReturn(['scaffold' => ['auto' => true]]); + (new ReflectionProperty(EventSubscriber::class, 'scaffoldRan'))->setValue(null, false); + } - $composer = self::createStub(Composer::class); + /** + * Ensures any `extra` block without `auto: false` passes the `auto` guard. + * + * @param array $extra Root package `extra` block. + */ + #[DataProvider(EventSubscriberProvider::class . '::autoEnabledExtra')] + public function runPassesTheAutoGuardWhenAutoIsNotFalse(array $extra): void + { + $io = new BufferIO(); - $composer->method('getConfig')->willReturn($config); - $composer->method('getPackage')->willReturn($package); + (new EventSubscriber())->onPostInstall(self::event(ScriptEvents::POST_INSTALL_CMD, $extra, $io)); - (new EventSubscriber())->onPostInstall( - new ScriptEvent(ScriptEvents::POST_INSTALL_CMD, $composer, $io, true), + Assert::same( + $io->getOutput(), + Message::SCAFFOLD_VENDOR_DIR_UNRESOLVABLE->getMessage() . PHP_EOL, + 'The run must reach the vendor directory guard.', ); + } - self::assertStringContainsString( - 'Unable to resolve vendor-dir', - $io->getOutput(), - 'Explicit "auto: true" must let the run proceed past the auto guard.', + /** + * Ensures each subscribed script event maps to its handler. + */ + public function subscribesTheThreeScriptEvents(): void + { + Assert::same( + EventSubscriber::getSubscribedEvents(), + [ + ScriptEvents::POST_CREATE_PROJECT_CMD => 'onPostCreateProject', + ScriptEvents::POST_INSTALL_CMD => 'onPostInstall', + ScriptEvents::POST_UPDATE_CMD => 'onPostUpdate', + ], + 'Each script event must map to its handler.', ); } /** - * Resets {@see EventSubscriber::$installScaffoldRan} so each test starts with a clean lifecycle slate; keeps the - * suite order-independent regardless of which event handlers previous tests invoked. + * Returns a script event for a Composer instance with an empty `vendor-dir` and a root package holding `$extra`. + * + * @param string $name Script event name. + * @param array $extra Root package `extra` block. + * @param BufferIO $io IO bound to the event. */ - protected function setUp(): void + private static function event(string $name, array $extra, BufferIO $io): ScriptEvent { - $reflection = new ReflectionClass(EventSubscriber::class); + $config = new Config(false); + + $config->merge(['config' => ['vendor-dir' => '']]); + + $package = new RootPackage('fixture/root', '1.0.0.0', '1.0.0'); + + $package->setExtra($extra); + + $composer = new Composer(); - $property = $reflection->getProperty('installScaffoldRan'); + $composer->setConfig($config); + $composer->setPackage($package); - $property->setValue(null, false); + return new ScriptEvent($name, $composer, $io, true); } } diff --git a/tests/Exception/MessageTest.php b/tests/Exception/MessageTest.php new file mode 100644 index 0000000..3332b47 --- /dev/null +++ b/tests/Exception/MessageTest.php @@ -0,0 +1,65 @@ + $row[0]->name, + array_values(MessageProvider::cases()), + ); + $declared = array_map( + static fn(Message $message): string => $message->name, + Message::cases(), + ); + + sort($pinned); + sort($declared); + + Assert::same( + $pinned, + $declared, + 'Every case needs exactly one provider row.', + ); + } + + /** + * Ensures each case renders its pinned literal. + * + * @param list $arguments + */ + #[DataProvider(MessageProvider::class . '::cases')] + public function rendersThePinnedLiteral(Message $case, array $arguments, string $expected): void + { + Assert::same( + $case->getMessage(...$arguments), + $expected, + 'Rendered message must match the pinned literal.', + ); + } +} diff --git a/tests/FilesystemTest.php b/tests/FilesystemTest.php new file mode 100644 index 0000000..e5e9b7f --- /dev/null +++ b/tests/FilesystemTest.php @@ -0,0 +1,450 @@ +tempDir}/source.txt", "content\n"); + + Filesystem::copy("{$this->tempDir}/source.txt", "{$this->tempDir}/copy.txt", self::FAILURE); + + FileAssert::contentSame( + "{$this->tempDir}/copy.txt", + "content\n", + 'Copy must hold the source content.', + ); + } + + public function copyPermissionsAppliesTheSourceBitsMaskedByTheUmask(): void + { + if (DIRECTORY_SEPARATOR === '\\') { + throw new SkipTest('POSIX permissions do not apply to NTFS.'); + } + + file_put_contents("{$this->tempDir}/source.sh", 'x'); + file_put_contents("{$this->tempDir}/copy.sh", 'x'); + chmod("{$this->tempDir}/source.sh", 0o765); + chmod("{$this->tempDir}/copy.sh", 0o600); + + $umask = umask(0o022); + + try { + Filesystem::copyPermissions("{$this->tempDir}/source.sh", "{$this->tempDir}/copy.sh", self::FAILURE); + } finally { + umask($umask); + } + + Assert::same( + fileperms("{$this->tempDir}/copy.sh") & 0o777, + 0o745, + "Permissions must be '0765' masked by the '0022' umask.", + ); + } + + public function errorHandlerIsRestoredAndNeverReachedWhenTheCallFails(): void + { + $calls = 0; + + $handler = static function () use (&$calls): bool { + $calls++; + + return true; + }; + + error_clear_last(); + set_error_handler($handler); + + try { + try { + Filesystem::read("{$this->tempDir}/missing.txt", self::FAILURE); + } catch (RuntimeException) { + // The failure itself is covered by the read tests. + } + + $current = set_error_handler(null); + + restore_error_handler(); + } finally { + restore_error_handler(); + } + + Assert::same( + $current, + $handler, + 'The previous error handler must be restored after a failed call.', + ); + Assert::same( + $calls, + 0, + 'The PHP warning of a failed call must never reach the previous error handler.', + ); + Assert::null( + error_get_last(), + 'The PHP warning must be captured, not raised.', + ); + } + + public function errorHandlerIsRestoredWhenTheCallSucceeds(): void + { + file_put_contents("{$this->tempDir}/a.txt", 'a'); + + $handler = static fn(): bool => true; + + set_error_handler($handler); + + try { + Filesystem::read("{$this->tempDir}/a.txt", self::FAILURE); + + $current = set_error_handler(null); + + restore_error_handler(); + } finally { + restore_error_handler(); + } + + Assert::same( + $current, + $handler, + 'The previous error handler must be restored after a successful call.', + ); + } + + public function hashReturnsTheSha256OfTheContent(): void + { + file_put_contents("{$this->tempDir}/a.txt", "content\n"); + + Assert::same( + Filesystem::hash("{$this->tempDir}/a.txt", self::FAILURE), + hash('sha256', "content\n"), + 'Hash must be the hexadecimal SHA-256 of the content.', + ); + } + + public function isEmptyDirectoryReportsWhetherTheDirectoryHoldsEntries(): void + { + mkdir("{$this->tempDir}/empty"); + mkdir("{$this->tempDir}/full"); + file_put_contents("{$this->tempDir}/full/a.txt", 'a'); + + Assert::true( + Filesystem::isEmptyDirectory("{$this->tempDir}/empty", self::FAILURE), + 'A directory without entries must be empty.', + ); + Assert::false( + Filesystem::isEmptyDirectory("{$this->tempDir}/full", self::FAILURE), + 'A directory with one entry must not be empty.', + ); + } + + public function mkdirAppliesFullPermissionsMaskedByTheUmask(): void + { + if (DIRECTORY_SEPARATOR === '\\') { + throw new SkipTest('POSIX permissions do not apply to NTFS.'); + } + + $umask = umask(0o022); + + try { + Filesystem::mkdir("{$this->tempDir}/a/b", self::FAILURE); + } finally { + umask($umask); + } + + Assert::same( + [fileperms("{$this->tempDir}/a") & 0o777, fileperms("{$this->tempDir}/a/b") & 0o777], + [0o755, 0o755], + "Permissions must be '0777' masked by the '0022' umask.", + ); + } + + public function mkdirCreatesMissingParents(): void + { + Filesystem::mkdir("{$this->tempDir}/a/b/c", self::FAILURE); + + FileAssert::directoryExists( + "{$this->tempDir}/a/b/c", + 'Every missing parent must be created.', + ); + } + + public function readLinkReturnsTheStoredTarget(): void + { + if (DIRECTORY_SEPARATOR === '\\') { + throw new SkipTest('Creating symbolic links needs extra privileges on Windows.'); + } + + symlink('target.txt', "{$this->tempDir}/link"); + + Assert::same( + Filesystem::readLink("{$this->tempDir}/link", self::FAILURE), + 'target.txt', + 'The relative target must be returned as stored.', + ); + } + + public function readReturnsTheContent(): void + { + file_put_contents("{$this->tempDir}/a.txt", "content\n"); + + Assert::same( + Filesystem::read("{$this->tempDir}/a.txt", self::FAILURE), + "content\n", + 'Read must return the file content.', + ); + } + + public function removeDeletesTheFile(): void + { + file_put_contents("{$this->tempDir}/a.txt", 'a'); + + Filesystem::remove("{$this->tempDir}/a.txt", self::FAILURE); + + FileAssert::fileDoesNotExist( + "{$this->tempDir}/a.txt", + 'The file must be deleted.', + ); + } + + public function removeDirectoryRemovesAnEmptyDirectory(): void + { + mkdir("{$this->tempDir}/empty"); + + Filesystem::removeDirectory("{$this->tempDir}/empty", self::FAILURE); + + FileAssert::directoryDoesNotExist( + "{$this->tempDir}/empty", + 'The empty directory must be removed.', + ); + } + + public function throwRuntimeExceptionWhenCopyPermissionsSourceIsMissing(): void + { + file_put_contents("{$this->tempDir}/copy.sh", 'x'); + + Expect::exception(RuntimeException::class) + ->withMessage( + Message::FILESYSTEM_FAILED->getMessage( + self::FAILURE, + "fileperms(): stat failed for {$this->tempDir}/missing.sh", + ), + ); + + Filesystem::copyPermissions("{$this->tempDir}/missing.sh", "{$this->tempDir}/copy.sh", self::FAILURE); + } + + public function throwRuntimeExceptionWhenCopySourceIsMissing(): void + { + $source = "{$this->tempDir}/missing.txt"; + + Expect::exception(RuntimeException::class) + ->withMessage( + Message::FILESYSTEM_FAILED->getMessage( + self::FAILURE, + "copy({$source}): Failed to open stream: No such file or directory", + ), + ); + + Filesystem::copy($source, "{$this->tempDir}/copy.txt", self::FAILURE); + } + + public function throwRuntimeExceptionWhenHashedFileIsMissing(): void + { + $path = "{$this->tempDir}/missing.txt"; + + Expect::exception(RuntimeException::class) + ->withMessage( + Message::FILESYSTEM_FAILED->getMessage( + self::FAILURE, + "hash_file({$path}): Failed to open stream: No such file or directory", + ), + ); + + Filesystem::hash($path, self::FAILURE); + } + + public function throwRuntimeExceptionWhenListedDirectoryIsARegularFile(): void + { + $path = "{$this->tempDir}/a.txt"; + + file_put_contents($path, 'a'); + + Expect::exception(RuntimeException::class) + ->withMessageMatchingRegex( + self::failurePattern("scandir({$path}): "), + ); + + Filesystem::isEmptyDirectory($path, self::FAILURE); + } + + public function throwRuntimeExceptionWhenMkdirParentIsARegularFile(): void + { + file_put_contents("{$this->tempDir}/blocker", 'x'); + + Expect::exception(RuntimeException::class) + ->withMessageMatchingRegex( + self::failurePattern('mkdir(): '), + ); + + Filesystem::mkdir("{$this->tempDir}/blocker/sub", self::FAILURE); + } + + public function throwRuntimeExceptionWhenReadFileIsMissing(): void + { + $path = "{$this->tempDir}/missing.txt"; + + Expect::exception(RuntimeException::class) + ->withMessage( + Message::FILESYSTEM_FAILED->getMessage( + self::FAILURE, + "file_get_contents({$path}): Failed to open stream: No such file or directory", + ), + ); + + Filesystem::read($path, self::FAILURE); + } + + public function throwRuntimeExceptionWhenReadLinkTargetIsMissing(): void + { + Expect::exception(RuntimeException::class) + ->withMessageMatchingRegex( + self::failurePattern('readlink(): '), + ); + + Filesystem::readLink("{$this->tempDir}/missing.txt", self::FAILURE); + } + + public function throwRuntimeExceptionWhenReadPathIsADirectory(): void + { + Expect::exception(RuntimeException::class) + ->withMessageContaining( + self::FAILURE . ' Reason: file_get_contents(', + ); + + // A directory reads as an empty string with a PHP notice, which counts as a failure. + Filesystem::read($this->tempDir, self::FAILURE); + } + + public function throwRuntimeExceptionWhenRemovedDirectoryIsNotEmpty(): void + { + mkdir("{$this->tempDir}/full"); + file_put_contents("{$this->tempDir}/full/a.txt", 'a'); + + Expect::exception(RuntimeException::class) + ->withMessage( + Message::FILESYSTEM_FAILED->getMessage( + self::FAILURE, + "rmdir({$this->tempDir}/full): Directory not empty", + ), + ); + + Filesystem::removeDirectory("{$this->tempDir}/full", self::FAILURE); + } + + public function throwRuntimeExceptionWhenRemovedFileIsADirectory(): void + { + mkdir("{$this->tempDir}/dir"); + + Expect::exception(RuntimeException::class) + ->withMessageMatchingRegex( + self::failurePattern("unlink({$this->tempDir}/dir): "), + ); + + Filesystem::remove("{$this->tempDir}/dir", self::FAILURE); + } + + public function throwRuntimeExceptionWhenWrittenPathIsADirectory(): void + { + mkdir("{$this->tempDir}/dir"); + + Expect::exception(RuntimeException::class) + ->withMessageMatchingRegex( + self::failurePattern("file_put_contents({$this->tempDir}/dir): Failed to open stream: "), + ); + + Filesystem::write("{$this->tempDir}/dir", 'x', self::FAILURE); + } + + public function writeAtomicReplacesTheFileWithoutLeavingTemporaryFiles(): void + { + file_put_contents("{$this->tempDir}/a.json", 'old'); + + Filesystem::writeAtomic("{$this->tempDir}/a.json", 'new', self::FAILURE); + + FileAssert::contentSame( + "{$this->tempDir}/a.json", + 'new', + 'The file must hold the new content.', + ); + Assert::same( + glob("{$this->tempDir}/a.json*"), + ["{$this->tempDir}/a.json"], + 'No temporary file may remain after a successful write.', + ); + } + + public function writeCreatesOrTruncatesTheFile(): void + { + file_put_contents("{$this->tempDir}/a.txt", 'longer old content'); + + Filesystem::write("{$this->tempDir}/a.txt", 'new', self::FAILURE); + + FileAssert::contentSame( + "{$this->tempDir}/a.txt", + 'new', + 'The file must hold only the new content.', + ); + } + + /** + * Returns the pattern of a failure message whose reason starts with `$reasonPrefix` and ends with an error text that + * depends on the platform. + * + * @param string $reasonPrefix Start of the PHP warning, up to the error text. + * + * @return non-empty-string Regular expression that matches the whole message. + */ + private static function failurePattern(string $reasonPrefix): string + { + return '/\A' . preg_quote(self::FAILURE . " Reason: {$reasonPrefix}", '/') . '.+\.\z/'; + } +} diff --git a/tests/Fixtures/composer/providers/provider-v1/composer.json b/tests/Fixtures/composer/providers/provider-v1/composer.json new file mode 100644 index 0000000..921ed31 --- /dev/null +++ b/tests/Fixtures/composer/providers/provider-v1/composer.json @@ -0,0 +1,23 @@ +{ + "name": "fixture/provider", + "description": "Scaffold provider fixture, first release.", + "type": "library", + "license": "BSD-3-Clause", + "extra": { + "scaffold": { + "copy": [ + {"from": "stubs/replace.txt", "to": "replace.txt"}, + {"from": "stubs/edited.txt", "to": "edited.txt"}, + {"from": "stubs/preserve.txt", "to": "config/preserve.txt"}, + {"from": "stubs/gitignore", "to": ".gitignore"}, + {"from": "stubs/prepend.txt", "to": "prepend.txt"}, + {"from": "stubs/dropped.txt", "to": "docs/old/dropped.txt"} + ], + "modes": { + "config/preserve.txt": "preserve", + ".gitignore": "append", + "prepend.txt": "prepend" + } + } + } +} diff --git a/tests/Fixtures/composer/providers/provider-v1/stubs/dropped.txt b/tests/Fixtures/composer/providers/provider-v1/stubs/dropped.txt new file mode 100644 index 0000000..f7b4879 --- /dev/null +++ b/tests/Fixtures/composer/providers/provider-v1/stubs/dropped.txt @@ -0,0 +1 @@ +dropped v1 diff --git a/tests/Fixtures/composer/providers/provider-v1/stubs/edited.txt b/tests/Fixtures/composer/providers/provider-v1/stubs/edited.txt new file mode 100644 index 0000000..ea1ae5e --- /dev/null +++ b/tests/Fixtures/composer/providers/provider-v1/stubs/edited.txt @@ -0,0 +1 @@ +edited v1 diff --git a/tests/Fixtures/composer/providers/provider-v1/stubs/gitignore b/tests/Fixtures/composer/providers/provider-v1/stubs/gitignore new file mode 100644 index 0000000..a0be10f --- /dev/null +++ b/tests/Fixtures/composer/providers/provider-v1/stubs/gitignore @@ -0,0 +1,2 @@ +# Dependencies +/vendor diff --git a/tests/Fixtures/composer/providers/provider-v1/stubs/prepend.txt b/tests/Fixtures/composer/providers/provider-v1/stubs/prepend.txt new file mode 100644 index 0000000..a5bcc79 --- /dev/null +++ b/tests/Fixtures/composer/providers/provider-v1/stubs/prepend.txt @@ -0,0 +1 @@ +HEADER diff --git a/tests/Fixtures/composer/providers/provider-v1/stubs/preserve.txt b/tests/Fixtures/composer/providers/provider-v1/stubs/preserve.txt new file mode 100644 index 0000000..f4615ec --- /dev/null +++ b/tests/Fixtures/composer/providers/provider-v1/stubs/preserve.txt @@ -0,0 +1 @@ +preserve v1 diff --git a/tests/Fixtures/composer/providers/provider-v1/stubs/replace.txt b/tests/Fixtures/composer/providers/provider-v1/stubs/replace.txt new file mode 100644 index 0000000..0d0643c --- /dev/null +++ b/tests/Fixtures/composer/providers/provider-v1/stubs/replace.txt @@ -0,0 +1 @@ +replace v1 diff --git a/tests/Fixtures/composer/providers/provider-v2/composer.json b/tests/Fixtures/composer/providers/provider-v2/composer.json new file mode 100644 index 0000000..a01343c --- /dev/null +++ b/tests/Fixtures/composer/providers/provider-v2/composer.json @@ -0,0 +1,23 @@ +{ + "name": "fixture/provider", + "description": "Scaffold provider fixture, second release.", + "type": "library", + "license": "BSD-3-Clause", + "extra": { + "scaffold": { + "copy": [ + {"from": "stubs/replace.txt", "to": "replace.txt"}, + {"from": "stubs/edited.txt", "to": "edited.txt"}, + {"from": "stubs/preserve.txt", "to": "config/preserve.txt"}, + {"from": "stubs/gitignore", "to": ".gitignore"}, + {"from": "stubs/prepend.txt", "to": "prepend.txt"}, + {"from": "stubs/added.txt", "to": "added.txt"} + ], + "modes": { + "config/preserve.txt": "preserve", + ".gitignore": "append", + "prepend.txt": "prepend" + } + } + } +} diff --git a/tests/Fixtures/composer/providers/provider-v2/stubs/added.txt b/tests/Fixtures/composer/providers/provider-v2/stubs/added.txt new file mode 100644 index 0000000..89bb406 --- /dev/null +++ b/tests/Fixtures/composer/providers/provider-v2/stubs/added.txt @@ -0,0 +1 @@ +added v2 diff --git a/tests/Fixtures/composer/providers/provider-v2/stubs/edited.txt b/tests/Fixtures/composer/providers/provider-v2/stubs/edited.txt new file mode 100644 index 0000000..95add50 --- /dev/null +++ b/tests/Fixtures/composer/providers/provider-v2/stubs/edited.txt @@ -0,0 +1 @@ +edited v2 diff --git a/tests/Fixtures/composer/providers/provider-v2/stubs/gitignore b/tests/Fixtures/composer/providers/provider-v2/stubs/gitignore new file mode 100644 index 0000000..8b5966b --- /dev/null +++ b/tests/Fixtures/composer/providers/provider-v2/stubs/gitignore @@ -0,0 +1,3 @@ +# Dependencies +/vendor +/node_modules diff --git a/tests/Fixtures/composer/providers/provider-v2/stubs/prepend.txt b/tests/Fixtures/composer/providers/provider-v2/stubs/prepend.txt new file mode 100644 index 0000000..a5bcc79 --- /dev/null +++ b/tests/Fixtures/composer/providers/provider-v2/stubs/prepend.txt @@ -0,0 +1 @@ +HEADER diff --git a/tests/Fixtures/composer/providers/provider-v2/stubs/preserve.txt b/tests/Fixtures/composer/providers/provider-v2/stubs/preserve.txt new file mode 100644 index 0000000..70e20bc --- /dev/null +++ b/tests/Fixtures/composer/providers/provider-v2/stubs/preserve.txt @@ -0,0 +1 @@ +preserve v2 diff --git a/tests/Fixtures/composer/providers/provider-v2/stubs/replace.txt b/tests/Fixtures/composer/providers/provider-v2/stubs/replace.txt new file mode 100644 index 0000000..2cb1518 --- /dev/null +++ b/tests/Fixtures/composer/providers/provider-v2/stubs/replace.txt @@ -0,0 +1 @@ +replace v2 diff --git a/tests/Fixtures/composer/template/gitignore b/tests/Fixtures/composer/template/gitignore new file mode 100644 index 0000000..6c09981 --- /dev/null +++ b/tests/Fixtures/composer/template/gitignore @@ -0,0 +1 @@ +/mine diff --git a/tests/Fixtures/composer/template/prepend.txt b/tests/Fixtures/composer/template/prepend.txt new file mode 100644 index 0000000..273a402 --- /dev/null +++ b/tests/Fixtures/composer/template/prepend.txt @@ -0,0 +1 @@ +body diff --git a/tests/Fixtures/merge/ini/consumer-app-inertia-react.expected.txt b/tests/Fixtures/merge/ini/consumer-app-inertia-react.expected.txt new file mode 100644 index 0000000..6ba6de1 --- /dev/null +++ b/tests/Fixtures/merge/ini/consumer-app-inertia-react.expected.txt @@ -0,0 +1,50 @@ +# editorconfig.org + +root = true + +[*] +charset = utf-8 +end_of_line = lf +insert_final_newline = true +indent_style = space +indent_size = 4 +trim_trailing_whitespace = true + +[*.{js,jsx,ts,tsx,css,scss,html}] +indent_size = 2 + +[*.md] +indent_size = unset +trim_trailing_whitespace = false + +[*.php] +ij_php_space_before_short_closure_left_parenthesis = false +ij_php_space_after_type_cast = true + +[*.yaml] +indent_size = 2 + +[*.yml] +indent_size = 2 + +[*.xml.dist] +indent_size = 2 + +[LICENSE*] +indent_style = unset +indent_size = unset + +[*.js] +indent_size = 2 + +[*.scss] +indent_size = 2 + +[*.css] +indent_size = 2 + +[package.json] +indent_size = 2 + +[package-lock.json] +indent_size = 2 diff --git a/tests/Fixtures/merge/ini/consumer-app-inertia-react.txt b/tests/Fixtures/merge/ini/consumer-app-inertia-react.txt new file mode 100644 index 0000000..1054c62 --- /dev/null +++ b/tests/Fixtures/merge/ini/consumer-app-inertia-react.txt @@ -0,0 +1,35 @@ +# editorconfig.org + +root = true + +[*] +charset = utf-8 +end_of_line = lf +insert_final_newline = true +indent_style = space +indent_size = 4 +trim_trailing_whitespace = true + +[*.{js,jsx,ts,tsx,css,scss,html}] +indent_size = 2 + +[*.md] +indent_size = unset +trim_trailing_whitespace = false + +[*.php] +ij_php_space_before_short_closure_left_parenthesis = false +ij_php_space_after_type_cast = true + +[*.yaml] +indent_size = 2 + +[*.yml] +indent_size = 2 + +[*.xml.dist] +indent_size = 2 + +[LICENSE*] +indent_style = unset +indent_size = unset diff --git a/tests/Fixtures/merge/ini/consumer-custom-sections.expected.txt b/tests/Fixtures/merge/ini/consumer-custom-sections.expected.txt new file mode 100644 index 0000000..20a3b93 --- /dev/null +++ b/tests/Fixtures/merge/ini/consumer-custom-sections.expected.txt @@ -0,0 +1,48 @@ +root = true + +[*] +indent_size = 3 +charset = utf-8 +end_of_line = lf +insert_final_newline = true +indent_style = space +trim_trailing_whitespace = true + +[src/assets/dist/**] +indent_size = unset + +[*.js] +indent_size = 2 + +[*.scss] +indent_size = 2 + +[*.css] +indent_size = 2 + +[package.json] +indent_size = 2 + +[package-lock.json] +indent_size = 2 + +[*.md] +indent_size = 2 +trim_trailing_whitespace = false + +[*.php] +ij_php_space_before_short_closure_left_parenthesis = false +ij_php_space_after_type_cast = true + +[*.yaml] +indent_size = 2 + +[*.yml] +indent_size = 2 + +[*.xml.dist] +indent_size = 2 + +[LICENSE*] +indent_style = unset +indent_size = unset diff --git a/tests/Fixtures/merge/ini/consumer-custom-sections.txt b/tests/Fixtures/merge/ini/consumer-custom-sections.txt new file mode 100644 index 0000000..d1d3dcc --- /dev/null +++ b/tests/Fixtures/merge/ini/consumer-custom-sections.txt @@ -0,0 +1,7 @@ +root = true + +[*] +indent_size = 3 + +[src/assets/dist/**] +indent_size = unset diff --git a/tests/Fixtures/merge/ini/consumer-scaffold.expected.txt b/tests/Fixtures/merge/ini/consumer-scaffold.expected.txt new file mode 100644 index 0000000..fca7679 --- /dev/null +++ b/tests/Fixtures/merge/ini/consumer-scaffold.expected.txt @@ -0,0 +1,50 @@ +# editorconfig.org + +root = true + +[*] +charset = utf-8 +end_of_line = lf +insert_final_newline = true +indent_style = space +indent_size = 4 +trim_trailing_whitespace = true + +[*.{cjs,js,mjs}] +indent_size = 2 + +[*.scss] +indent_size = 2 + +[*.css] +indent_size = 2 + +[package.json] +indent_size = 2 + +[package-lock.json] +indent_size = 2 + +[*.md] +indent_size = unset +trim_trailing_whitespace = false + +[*.php] +ij_php_space_before_short_closure_left_parenthesis = false +ij_php_space_after_type_cast = true + +[*.yaml] +indent_size = 2 + +[*.yml] +indent_size = 2 + +[*.xml.dist] +indent_size = 2 + +[LICENSE*] +indent_style = unset +indent_size = unset + +[*.js] +indent_size = 2 diff --git a/tests/Fixtures/merge/ini/consumer-scaffold.txt b/tests/Fixtures/merge/ini/consumer-scaffold.txt new file mode 100644 index 0000000..2f0552d --- /dev/null +++ b/tests/Fixtures/merge/ini/consumer-scaffold.txt @@ -0,0 +1,47 @@ +# editorconfig.org + +root = true + +[*] +charset = utf-8 +end_of_line = lf +insert_final_newline = true +indent_style = space +indent_size = 4 +trim_trailing_whitespace = true + +[*.{cjs,js,mjs}] +indent_size = 2 + +[*.scss] +indent_size = 2 + +[*.css] +indent_size = 2 + +[package.json] +indent_size = 2 + +[package-lock.json] +indent_size = 2 + +[*.md] +indent_size = unset +trim_trailing_whitespace = false + +[*.php] +ij_php_space_before_short_closure_left_parenthesis = false +ij_php_space_after_type_cast = true + +[*.yaml] +indent_size = 2 + +[*.yml] +indent_size = 2 + +[*.xml.dist] +indent_size = 2 + +[LICENSE*] +indent_style = unset +indent_size = unset diff --git a/tests/Fixtures/merge/ini/provider.txt b/tests/Fixtures/merge/ini/provider.txt new file mode 100644 index 0000000..6b45e5d --- /dev/null +++ b/tests/Fixtures/merge/ini/provider.txt @@ -0,0 +1,47 @@ +# editorconfig.org + +root = true + +[*] +charset = utf-8 +end_of_line = lf +insert_final_newline = true +indent_style = space +indent_size = 4 +trim_trailing_whitespace = true + +[*.js] +indent_size = 2 + +[*.scss] +indent_size = 2 + +[*.css] +indent_size = 2 + +[package.json] +indent_size = 2 + +[package-lock.json] +indent_size = 2 + +[*.md] +indent_size = 2 +trim_trailing_whitespace = false + +[*.php] +ij_php_space_before_short_closure_left_parenthesis = false +ij_php_space_after_type_cast = true + +[*.yaml] +indent_size = 2 + +[*.yml] +indent_size = 2 + +[*.xml.dist] +indent_size = 2 + +[LICENSE*] +indent_style = unset +indent_size = unset diff --git a/tests/Fixtures/merge/list/consumer-reordered.txt b/tests/Fixtures/merge/list/consumer-reordered.txt new file mode 100644 index 0000000..e9068fb --- /dev/null +++ b/tests/Fixtures/merge/list/consumer-reordered.txt @@ -0,0 +1,30 @@ +# everything the provider ships, my own order and headers +.settings +.project +.buildpath +Thumbs.db +.vscode +vendor +.vagrant +.phpunit.result.cache +.phpunit.cache + +# tooling +.phpactor.* +.idea +package-lock.json +node_modules +nbproject +.DS_Store +.github/skills/** +.github/prompts/** +.github/instructions/** +.github/copilot/** +.github/copilot-instructions.md +.github/agents/** +composer.lock +c3.php +code_coverage +.config/gh +.codex +.claude diff --git a/tests/Fixtures/merge/list/consumer-scaffold.txt b/tests/Fixtures/merge/list/consumer-scaffold.txt new file mode 100644 index 0000000..2400549 --- /dev/null +++ b/tests/Fixtures/merge/list/consumer-scaffold.txt @@ -0,0 +1,58 @@ +# AI agents (if present) +.codex +.claude + +# codecoverage (if present) +code_coverage + +# codeception (if present) +c3.php + +# composer +composer.lock + +# gitHub copilot config (if present) +.github/agents/** +.github/copilot-instructions.md +.github/copilot/** +.github/instructions/** +.github/prompts/** +.github/skills/** + +# mac ds_store (if present) +.DS_Store + +# netbeans project (if present) +nbproject + +# node_modules (if present) +node_modules +package-lock.json +!src/assets/package-lock.json + +# phpactor (if present) +.phpactor.* + +# phpstorm project (if present) +.idea + +# phpunit (if present) +.phpunit.cache +.phpunit.result.cache + +# vagrant (if present) +.vagrant + +# vendor +vendor + +# vscode project (if present) +.vscode + +# windows thumbnail cache (if present) +Thumbs.db + +# zend studio for eclipse project (if present) +.buildpath +.project +.settings diff --git a/tests/Fixtures/merge/list/consumer-scaffold.v1.expected.txt b/tests/Fixtures/merge/list/consumer-scaffold.v1.expected.txt new file mode 100644 index 0000000..0257501 --- /dev/null +++ b/tests/Fixtures/merge/list/consumer-scaffold.v1.expected.txt @@ -0,0 +1,61 @@ +# AI agents (if present) +.codex +.claude + +# codecoverage (if present) +code_coverage + +# codeception (if present) +c3.php + +# composer +composer.lock + +# gitHub copilot config (if present) +.github/agents/** +.github/copilot-instructions.md +.github/copilot/** +.github/instructions/** +.github/prompts/** +.github/skills/** + +# mac ds_store (if present) +.DS_Store + +# netbeans project (if present) +nbproject + +# node_modules (if present) +node_modules +package-lock.json +!src/assets/package-lock.json + +# phpactor (if present) +.phpactor.* + +# phpstorm project (if present) +.idea + +# phpunit (if present) +.phpunit.cache +.phpunit.result.cache + +# vagrant (if present) +.vagrant + +# vendor +vendor + +# vscode project (if present) +.vscode + +# windows thumbnail cache (if present) +Thumbs.db + +# zend studio for eclipse project (if present) +.buildpath +.project +.settings + +# Local AI agent, editor, and GitHub CLI config (if present) +.config/gh diff --git a/tests/Fixtures/merge/list/consumer-scaffold.v2.expected.txt b/tests/Fixtures/merge/list/consumer-scaffold.v2.expected.txt new file mode 100644 index 0000000..2405e78 --- /dev/null +++ b/tests/Fixtures/merge/list/consumer-scaffold.v2.expected.txt @@ -0,0 +1,65 @@ +# AI agents (if present) +.codex +.claude + +# codecoverage (if present) +code_coverage + +# codeception (if present) +c3.php + +# composer +composer.lock + +# gitHub copilot config (if present) +.github/agents/** +.github/copilot-instructions.md +.github/copilot/** +.github/instructions/** +.github/prompts/** +.github/skills/** + +# mac ds_store (if present) +.DS_Store + +# netbeans project (if present) +nbproject + +# node_modules (if present) +node_modules +package-lock.json +!src/assets/package-lock.json + +# phpactor (if present) +.phpactor.* + +# phpstorm project (if present) +.idea + +# phpunit (if present) +.phpunit.cache +.phpunit.result.cache + +# vagrant (if present) +.vagrant + +# vendor +vendor + +# vscode project (if present) +.vscode + +# windows thumbnail cache (if present) +Thumbs.db + +# zend studio for eclipse project (if present) +.buildpath +.project +.settings + +# Local AI agent, editor, and GitHub CLI config (if present) +.config/gh +.config/gh-extra + +# psalm cache (if present) +.psalm-cache diff --git a/tests/Fixtures/merge/list/provider-v1.txt b/tests/Fixtures/merge/list/provider-v1.txt new file mode 100644 index 0000000..2d02692 --- /dev/null +++ b/tests/Fixtures/merge/list/provider-v1.txt @@ -0,0 +1,58 @@ +# Local AI agent, editor, and GitHub CLI config (if present) +.claude +.codex +.config/gh + +# codecoverage (if present) +code_coverage + +# codeception (if present) +c3.php + +# composer +composer.lock + +# GitHub Copilot config (if present) +.github/agents/** +.github/copilot-instructions.md +.github/copilot/** +.github/instructions/** +.github/prompts/** +.github/skills/** + +# mac ds_store (if present) +.DS_Store + +# netbeans project (if present) +nbproject + +# node_modules (if present) +node_modules +package-lock.json + +# phpstorm project (if present) +.idea + +# phpactor (if present) +.phpactor.* + +# phpunit (if present) +.phpunit.cache +.phpunit.result.cache + +# vagrant (if present) +.vagrant + +# vendor +vendor + +# vscode project (if present) +.vscode + +# windows thumbnail cache (if present) +Thumbs.db + +# zend studio for eclipse project (if present) +.buildpath +.project +.settings diff --git a/tests/Fixtures/merge/list/provider-v2.txt b/tests/Fixtures/merge/list/provider-v2.txt new file mode 100644 index 0000000..9605080 --- /dev/null +++ b/tests/Fixtures/merge/list/provider-v2.txt @@ -0,0 +1,62 @@ +# Local AI agent, editor, and GitHub CLI config (if present) +.claude +.codex +.config/gh +.config/gh-extra + +# codecoverage (if present) +code_coverage + +# codeception (if present) +c3.php + +# composer +composer.lock + +# GitHub Copilot config (if present) +.github/agents/** +.github/copilot-instructions.md +.github/copilot/** +.github/instructions/** +.github/prompts/** +.github/skills/** + +# mac ds_store (if present) +.DS_Store + +# netbeans project (if present) +nbproject + +# node_modules (if present) +node_modules +package-lock.json + +# phpstorm project (if present) +.idea + +# phpactor (if present) +.phpactor.* + +# phpunit (if present) +.phpunit.cache +.phpunit.result.cache + +# vagrant (if present) +.vagrant + +# vendor +vendor + +# vscode project (if present) +.vscode + +# windows thumbnail cache (if present) +Thumbs.db + +# zend studio for eclipse project (if present) +.buildpath +.project +.settings + +# psalm cache (if present) +.psalm-cache diff --git a/tests/Fixtures/merge/text/consumer.expected.txt b/tests/Fixtures/merge/text/consumer.expected.txt new file mode 100644 index 0000000..c840f7e --- /dev/null +++ b/tests/Fixtures/merge/text/consumer.expected.txt @@ -0,0 +1,11 @@ +# Local overrides +APP_ENV=dev +DB_DSN=mysql:host=db;dbname=myapp +DB_USER=root +MAILER_DSN=smtp://localhost:1025 + +# Application environment +APP_DEBUG=true +# Database +DB_DSN=mysql:host=localhost;dbname=app +DB_PASSWORD= diff --git a/tests/Fixtures/merge/text/consumer.txt b/tests/Fixtures/merge/text/consumer.txt new file mode 100644 index 0000000..13c3e65 --- /dev/null +++ b/tests/Fixtures/merge/text/consumer.txt @@ -0,0 +1,5 @@ +# Local overrides +APP_ENV=dev +DB_DSN=mysql:host=db;dbname=myapp +DB_USER=root +MAILER_DSN=smtp://localhost:1025 diff --git a/tests/Fixtures/merge/text/provider.txt b/tests/Fixtures/merge/text/provider.txt new file mode 100644 index 0000000..03acd3a --- /dev/null +++ b/tests/Fixtures/merge/text/provider.txt @@ -0,0 +1,8 @@ +# Application environment +APP_ENV=dev +APP_DEBUG=true + +# Database +DB_DSN=mysql:host=localhost;dbname=app +DB_USER=root +DB_PASSWORD= diff --git a/tests/Fixtures/runtime/guarded-cli.php b/tests/Fixtures/runtime/guarded-cli.php new file mode 100644 index 0000000..ff31c69 --- /dev/null +++ b/tests/Fixtures/runtime/guarded-cli.php @@ -0,0 +1,43 @@ + `; prints the comma-separated exit codes. + */ + +use PHPForge\Scaffold\Console\Application; +use Symfony\Component\Console\Input\ArgvInput; +use Symfony\Component\Console\Output\NullOutput; + +$autoload = $argv[1] ?? ''; +$projectRoot = $argv[2] ?? ''; + +require $autoload; + +spl_autoload_register( + static function (string $class): void { + if (preg_match('/^Composer\\\\(?:(?:IO|Package|Script|Plugin|EventDispatcher)\\\\|Composer$)/', $class) === 1) { + fwrite(STDERR, "Composer class loaded: {$class}\n"); + + exit(97); + } + }, + true, + true, +); + +$application = new Application(); + +$application->setAutoExit(false); + +$codes = []; + +foreach ([['sync'], ['status'], ['diff', '--all'], ['prune'], ['sync', '--dry-run']] as $command) { + $codes[] = $application->run(new ArgvInput(['scaffold', ...$command, '-d', $projectRoot]), new NullOutput()); +} + +echo implode(',', $codes); diff --git a/tests/Functional/ApplyLifecycleTest.php b/tests/Functional/ApplyLifecycleTest.php new file mode 100644 index 0000000..de7e181 --- /dev/null +++ b/tests/Functional/ApplyLifecycleTest.php @@ -0,0 +1,121 @@ +project(); + + $manifest = ['copy' => ['.styleci.yml']]; + + $builder->createStubFile('demo/scaffold', '.styleci.yml', "preset: psr12\n"); + + $this->dispatch($builder, $manifest); + + $builder->createProjectFile('.styleci.yml', "preset: laravel\n"); + + (new EjectService()) + ->run($builder->getProjectRoot(), new BufferedOutputWriter(), '.styleci.yml', true); + + Assert::same( + $this->dispatch($builder, $manifest), + '', + 'An ejected file needs no output.', + ); + FileAssert::contentSame( + "{$builder->getProjectRoot()}/.styleci.yml", + "preset: laravel\n", + 'User edit must survive the next install.', + ); + Assert::true( + (new LockFile($builder->getProjectRoot()))->read()['files']['.styleci.yml']['ejected'] ?? false, + "Entry must stay 'ejected'.", + ); + } + + public function providerBumpUpdatesAppendAndReplaceLeavesPreserveAndRecordsStubHash(): void + { + $builder = $this->project(); + + $manifest = [ + 'copy' => ['.gitignore', '.styleci.yml', 'ecs.php'], + 'modes' => ['.gitignore' => 'append', 'ecs.php' => 'preserve'], + ]; + + $root = $builder->getProjectRoot(); + + $stubs = "{$builder->getVendorDir()}/demo/scaffold"; + + $builder->createStubFile('demo/scaffold', '.gitignore', "# composer\ncomposer.lock\n"); + $builder->createStubFile('demo/scaffold', '.styleci.yml', "preset: psr12\n"); + $builder->createStubFile('demo/scaffold', 'ecs.php', "dispatch($builder, $manifest); + + $builder->createProjectFile('.gitignore', "# composer\ncomposer.lock\n/build\n"); + $builder->createStubFile('demo/scaffold', '.gitignore', "# composer\ncomposer.lock\ncomposer.phar\n"); + $builder->createStubFile('demo/scaffold', '.styleci.yml', "preset: per\n"); + $builder->createStubFile('demo/scaffold', 'ecs.php', "dispatch($builder, $manifest, ScriptEvents::POST_UPDATE_CMD, '2.0.0'); + + $lock = (new LockFile($root))->read(); + + Assert::same( + [ + '.gitignore' => file_get_contents("{$root}/.gitignore"), + '.styleci.yml' => file_get_contents("{$root}/.styleci.yml"), + 'ecs.php' => file_get_contents("{$root}/ecs.php"), + ], + [ + '.gitignore' => "# composer\ncomposer.lock\n/build\ncomposer.phar\n", + '.styleci.yml' => "preset: per\n", + 'ecs.php' => " '2.0.0', 'path' => str_replace('\\', '/', $stubs)], + "Provider version must advance to '2.0.0'.", + ); + Assert::same( + array_column($lock['files'], 'stub-hash'), + [ + Hasher::hash("{$stubs}/.gitignore"), + Hasher::hash("{$stubs}/.styleci.yml"), + Hasher::hash("{$stubs}/ecs.php"), + ], + 'Stub hash of every file must match the bumped stub.', + ); + } +} diff --git a/tests/Functional/ComposerInstallTest.php b/tests/Functional/ComposerInstallTest.php deleted file mode 100644 index 2c167a8..0000000 --- a/tests/Functional/ComposerInstallTest.php +++ /dev/null @@ -1,419 +0,0 @@ -tempDir); - - $builder->createStubFile( - 'demo/scaffold', - 'config/params.php', - " 'a@b.c'];\n", - ); - $builder->createStubFile( - 'demo/scaffold', - '.gitignore', - "/runtime/\n", - ); - $builder->createComposerJson( - [ - 'name' => 'demo/smoke-project', - 'config' => ['vendor-dir' => $builder->getVendorDir()], - 'extra' => [ - 'scaffold' => ['allowed-packages' => ['demo/scaffold']], - ], - ], - ); - - $io = new BufferIO(); - - $composer = $this->buildComposerForProject($builder->getProjectRoot(), $io); - $this->addMockProvider( - $composer, - 'demo/scaffold', - [ - 'copy' => ['config/params.php', '.gitignore'], - 'modes' => [ - 'config/params.php' => 'preserve', - '.gitignore' => 'append', - ], - ], - ); - $this->resetInstallScaffoldRanFlag(); - - (new EventSubscriber())->onPostInstall($this->makePostInstallEvent($composer, $io)); - - self::assertFileExists( - $builder->getProjectRoot() . '/config/params.php', - "First 'post-install-cmd' must materialize preserve-mode files from the provider stub.", - ); - self::assertFileExists( - $builder->getProjectRoot() . '/.gitignore', - "First 'post-install-cmd' must materialize append-mode files from the provider stub.", - ); - - $lockData = (new LockFile($builder->getProjectRoot()))->read(); - - self::assertArrayHasKey( - 'demo/scaffold', - $lockData['providers'], - "Lock must record the provider after the first 'post-install-cmd'.", - ); - self::assertArrayHasKey( - 'config/params.php', - $lockData['files'], - "Lock must track every destination written during 'post-install-cmd'.", - ); - self::assertArrayHasKey( - '.gitignore', - $lockData['files'], - "Lock must track every destination written during 'post-install-cmd'.", - ); - } - - public function testNonStringAllowedPackagesEntryIsReportedAndIgnored(): void - { - $builder = new FakeProjectBuilder($this->tempDir); - - $builder->createStubFile( - 'demo/scaffold', - 'config/params.php', - "createComposerJson( - [ - 'name' => 'demo/smoke-project', - 'config' => ['vendor-dir' => $builder->getVendorDir()], - 'extra' => [ - 'scaffold' => [ - // `42` is not a string and must be rejected without aborting the run. - 'allowed-packages' => ['demo/scaffold', 42], - ], - ], - ], - ); - - $io = new BufferIO(); - - $composer = $this->buildComposerForProject($builder->getProjectRoot(), $io); - $this->addMockProvider( - $composer, - 'demo/scaffold', - [ - 'copy' => ['config/params.php'], - 'modes' => ['config/params.php' => 'preserve'], - ], - ); - $this->resetInstallScaffoldRanFlag(); - - (new EventSubscriber())->onPostInstall($this->makePostInstallEvent($composer, $io)); - - self::assertStringContainsString( - 'Non-string entry in allowed-packages ignored', - $io->getOutput(), - 'Non-string entries in allowed-packages must be reported so configuration errors are visible.', - ); - self::assertFileExists( - $builder->getProjectRoot() . '/config/params.php', - 'Valid providers must still be scaffolded even when a sibling allowed-packages entry is malformed.', - ); - } - - public function testNoScaffoldExtraIsAcceptedAndTreatedAsEmpty(): void - { - $builder = new FakeProjectBuilder($this->tempDir); - - // No 'extra.scaffold' key: runScaffold must emit the no-config notice and leave the project untouched. - $builder->createComposerJson( - [ - 'name' => 'demo/smoke-project', - 'config' => ['vendor-dir' => $builder->getVendorDir()], - ], - ); - - $io = new BufferIO(); - - $composer = $this->buildComposerForProject($builder->getProjectRoot(), $io); - $this->resetInstallScaffoldRanFlag(); - - (new EventSubscriber())->onPostInstall($this->makePostInstallEvent($composer, $io)); - - self::assertStringContainsString( - 'No extra.scaffold configuration found', - $io->getOutput(), - 'Projects without `extra.scaffold` must still dispatch the handler and gracefully emit the no-config notice.', - ); - } - - public function testPostUpdateTriggersPartialScaffold(): void - { - $builder = new FakeProjectBuilder($this->tempDir); - - $builder->createStubFile( - 'demo/scaffold', - 'config/params.php', - "createComposerJson( - [ - 'name' => 'demo/smoke-project', - 'config' => ['vendor-dir' => $builder->getVendorDir()], - 'extra' => [ - 'scaffold' => [ - 'allowed-packages' => [ - 'demo/scaffold', - ], - ], - ], - ], - ); - - $io = new BufferIO(); - - $composer = $this->buildComposerForProject($builder->getProjectRoot(), $io); - $this->addMockProvider( - $composer, - 'demo/scaffold', - [ - 'copy' => ['config/params.php'], - 'modes' => ['config/params.php' => 'preserve'], - ], - ); - $this->resetInstallScaffoldRanFlag(); - - (new EventSubscriber())->onPostUpdate($this->makePostUpdateEvent($composer, $io)); - - self::assertFileExists( - $builder->getProjectRoot() . '/config/params.php', - "'post-update-cmd' must dispatch the same partial scaffold flow as 'post-install-cmd'.", - ); - } - - public function testReplaceModeWarnsAndSkipsWhenUserModifiedBetweenRuns(): void - { - $builder = new FakeProjectBuilder($this->tempDir); - - $builder->createStubFile( - 'demo/scaffold', - '.env.dist', - "APP_ENV=dev\n", - ); - $builder->createComposerJson( - [ - 'name' => 'demo/smoke-project', - 'config' => ['vendor-dir' => $builder->getVendorDir()], - 'extra' => [ - 'scaffold' => [ - 'allowed-packages' => [ - 'demo/scaffold', - ], - ], - ], - ], - ); - - $io = new BufferIO(); - - $composer = $this->buildComposerForProject($builder->getProjectRoot(), $io); - $this->addMockProvider( - $composer, - 'demo/scaffold', - [ - 'copy' => ['.env.dist'], - ], - ); - $this->resetInstallScaffoldRanFlag(); - - $subscriber = new EventSubscriber(); - - $subscriber->onPostInstall($this->makePostInstallEvent($composer, $io)); - - // Simulate the user editing the replace-mode file between two install runs. - file_put_contents( - $builder->getProjectRoot() . '/.env.dist', - "APP_ENV=production\nUSER_EDIT=1\n", - ); - - $subscriber->onPostInstall($this->makePostInstallEvent($composer, $io)); - - self::assertStringContainsString( - 'User-modified file skipped: ".env.dist".', - $io->getOutput(), - 'Replace mode must emit a user-modified warning when the current file diverges from the scaffold hash.', - ); - - $envContent = file_get_contents($builder->getProjectRoot() . '/.env.dist'); - - self::assertIsString( - $envContent, - 'Replace-mode destination must remain readable after scaffolding.', - ); - self::assertStringContainsString( - 'USER_EDIT=1', - $envContent, - 'Replace mode must preserve the user edit instead of reverting to the provider stub.', - ); - } - - public function testScaffolderExceptionIsLoggedAndHandlerDoesNotCrash(): void - { - $builder = new FakeProjectBuilder($this->tempDir); - - // Malformed lock JSON makes 'LockFile::read()' throw; the EventSubscriber must catch and log the abort. - file_put_contents("{$builder->getProjectRoot()}/scaffold-lock.json", '{ not valid json'); - - $builder->createStubFile( - 'demo/scaffold', - 'config/params.php', - "createComposerJson( - [ - 'name' => 'demo/smoke-project', - 'config' => ['vendor-dir' => $builder->getVendorDir()], - 'extra' => [ - 'scaffold' => [ - 'allowed-packages' => [ - 'demo/scaffold', - ], - ], - ], - ], - ); - - $io = new BufferIO(); - - $composer = $this->buildComposerForProject($builder->getProjectRoot(), $io); - $this->addMockProvider( - $composer, - 'demo/scaffold', - [ - 'copy' => ['config/params.php'], - 'modes' => ['config/params.php' => 'preserve'], - ], - ); - $this->resetInstallScaffoldRanFlag(); - - (new EventSubscriber())->onPostInstall($this->makePostInstallEvent($composer, $io)); - - self::assertStringContainsString( - 'Scaffolding aborted', - $io->getOutput(), - 'An exception bubbling out of Scaffolder must be caught and reported without crashing Composer.', - ); - } - - public function testScaffoldExtraWithoutAllowedPackagesKeyIsTreatedAsEmpty(): void - { - $builder = new FakeProjectBuilder($this->tempDir); - - $builder->createComposerJson( - [ - 'name' => 'demo/smoke-project', - 'config' => ['vendor-dir' => $builder->getVendorDir()], - // `extra.scaffold` is present but `allowed-packages` is missing entirely. - 'extra' => ['scaffold' => []], - ], - ); - - $io = new BufferIO(); - - $composer = $this->buildComposerForProject($builder->getProjectRoot(), $io); - $this->resetInstallScaffoldRanFlag(); - - (new EventSubscriber())->onPostInstall($this->makePostInstallEvent($composer, $io)); - - self::assertStringContainsString( - 'No allowed-packages configured', - $io->getOutput(), - "A scaffold extra without the 'allowed-packages' key must produce the allowed-packages skip message.", - ); - } - - public function testSecondPostInstallPreservesContentAndLockWhenUnmodified(): void - { - $builder = new FakeProjectBuilder($this->tempDir); - - $builder->createStubFile('demo/scaffold', '.env.dist', "APP_ENV=dev\n"); - $builder->createComposerJson( - [ - 'name' => 'demo/smoke-project', - 'config' => ['vendor-dir' => $builder->getVendorDir()], - 'extra' => [ - 'scaffold' => [ - 'allowed-packages' => [ - 'demo/scaffold', - ], - ], - ], - ], - ); - - $io = new BufferIO(); - - $composer = $this->buildComposerForProject($builder->getProjectRoot(), $io); - $this->addMockProvider( - $composer, - 'demo/scaffold', - [ - 'copy' => ['.env.dist'], - ], - ); - $this->resetInstallScaffoldRanFlag(); - - $subscriber = new EventSubscriber(); - - $subscriber->onPostInstall($this->makePostInstallEvent($composer, $io)); - - $lockAfterFirst = file_get_contents($builder->getProjectRoot() . '/scaffold-lock.json'); - - $subscriber->onPostInstall($this->makePostInstallEvent($composer, $io)); - - self::assertSame( - "APP_ENV=dev\n", - file_get_contents($builder->getProjectRoot() . '/.env.dist'), - "Second 'post-install-cmd' must not corrupt a replace-mode file whose hash still matches the lock.", - ); - self::assertSame( - $lockAfterFirst, - file_get_contents($builder->getProjectRoot() . '/scaffold-lock.json'), - "Second 'post-install-cmd' must not grow or mutate the lock when no scaffold state actually changed.", - ); - self::assertStringNotContainsString( - 'User-modified file skipped', - $io->getOutput(), - 'No user-modified warning must be emitted when the file hash still matches what the lock recorded.', - ); - } - - protected function setUp(): void - { - $this->setUpTempDirectory(); - } - - protected function tearDown(): void - { - $this->tearDownTempDirectory(); - $this->resetInstallScaffoldRanFlag(); - } -} diff --git a/tests/Functional/ComposerRunPolicyTest.php b/tests/Functional/ComposerRunPolicyTest.php new file mode 100644 index 0000000..08764fa --- /dev/null +++ b/tests/Functional/ComposerRunPolicyTest.php @@ -0,0 +1,283 @@ +project(); + + $builder->createStubFile('demo/scaffold', 'a.txt', "v1\n"); + $builder->createStubFile('demo/scaffold', 'keep.txt', "keep v1\n"); + + $manifest = ['copy' => ['a.txt', 'keep.txt'], 'modes' => ['keep.txt' => 'preserve']]; + + $this->dispatch($builder, $manifest); + + file_put_contents( + "{$builder->getProjectRoot()}/a.txt", + "mine\n", + ); + + $skipped = ConsoleMessage::SCAFFOLD_PREFIXED->getMessage( + ConsoleMessage::SCAFFOLD_USER_MODIFIED_SKIPPED->getMessage('a.txt'), + ) . PHP_EOL; + + Assert::same( + $this->dispatch($builder, $manifest), + $skipped + . ExpectedSummary::line(0, 1, ExpectedSummary::part(1, ConsoleMessage::FRAGMENT_WARNING)) + . PHP_EOL, + 'A user edit without a provider change is no conflict.', + ); + + $builder->createStubFile('demo/scaffold', 'a.txt', "v2\n"); + $builder->createStubFile('demo/scaffold', 'keep.txt', "keep v2\n"); + + $conflict = $skipped + . ConsoleMessage::SCAFFOLD_CONFLICTS->getMessage(1, ConsoleMessage::FRAGMENT_CONFLICT_FILE->getMessage()) + . PHP_EOL; + + Assert::same( + $this->dispatch($builder, $manifest), + $conflict + . ExpectedSummary::line( + 0, + 1, + ExpectedSummary::part(1, ConsoleMessage::FRAGMENT_OUTDATED), + ExpectedSummary::part(1, ConsoleMessage::FRAGMENT_CONFLICT), + ExpectedSummary::part(1, ConsoleMessage::FRAGMENT_WARNING), + ) + . PHP_EOL, + 'Bump must report the conflict and the kept preserve file.', + ); + Assert::same( + $this->dispatch($builder, $manifest), + $conflict + . ExpectedSummary::line( + 0, + 1, + ExpectedSummary::part(1, ConsoleMessage::FRAGMENT_CONFLICT), + ExpectedSummary::part(1, ConsoleMessage::FRAGMENT_WARNING), + ) + . PHP_EOL, + 'Conflict must persist until the update is taken.', + ); + FileAssert::contentSame( + "{$builder->getProjectRoot()}/a.txt", + "mine\n", + 'Edit must survive.', + ); + FileAssert::contentSame( + "{$builder->getProjectRoot()}/keep.txt", + "keep v1\n", + 'Preserve file must stay.', + ); + } + + public function nonStringAllowedPackagesEntryIsReportedAndIgnored(): void + { + $builder = $this->project(['allowed-packages' => ['demo/scaffold', 42]]); + + $builder->createStubFile('demo/scaffold', 'a.txt', "a\n"); + + Assert::same( + $this->dispatch($builder, ['copy' => ['a.txt']]), + ConsoleMessage::SCAFFOLD_ALLOWED_ENTRY_IGNORED->getMessage() . PHP_EOL + . ExpectedSummary::line(1, 0) . PHP_EOL, + 'The ignored entry must be reported before the summary.', + ); + FileAssert::contentSame( + "{$builder->getProjectRoot()}/a.txt", + "a\n", + 'Valid provider must be scaffolded.', + ); + } + + public function orphansAreListedAfterTheProviderDropsAFile(): void + { + $builder = $this->project(); + + $builder->createStubFile('demo/scaffold', 'a.txt', "a\n"); + $builder->createStubFile('demo/scaffold', 'old.txt', "old\n"); + + $this->dispatch($builder, ['copy' => ['a.txt', 'old.txt']]); + + Assert::same( + $this->dispatch($builder, ['copy' => ['a.txt']]), + ConsoleMessage::SCAFFOLD_ORPHAN_HEADER->getMessage(1, ConsoleMessage::FRAGMENT_FILE->getMessage()) + . PHP_EOL + . ConsoleMessage::SCAFFOLD_ORPHAN_ENTRY->getMessage('old.txt', 'demo/scaffold') . PHP_EOL + . ExpectedSummary::line(0, 1, ExpectedSummary::part(1, ConsoleMessage::FRAGMENT_ORPHAN)) . PHP_EOL, + 'Orphan must be listed with the prune hint and counted.', + ); + FileAssert::fileExists( + "{$builder->getProjectRoot()}/old.txt", + 'Composer runs never delete orphans.', + ); + Assert::same( + array_keys((new LockFile($builder->getProjectRoot()))->read()['files']), + ['a.txt', 'old.txt'], + "Orphan entry 'old.txt' must stay in the lock.", + ); + } + + public function throwScaffoldExceptionAfterSummaryWhenAFileFailsToApply(): void + { + $builder = $this->project(); + + $builder->createStubFile('demo/scaffold', 'a.txt', "a\n"); + $builder->createStubFile('demo/scaffold', 'evil.json', '{}'); + + $io = new BufferIO(); + + $exception = $this->failingDispatch( + $builder, + ['copy' => ['a.txt', ['from' => 'evil.json', 'to' => 'scaffold-lock.json']]], + $io, + ); + + Assert::same( + $exception?->getMessage(), + Message::SCAFFOLD_FILES_FAILED->getMessage(1, Message::SCAFFOLD_FRAGMENT_FAILED_FILE->getMessage()), + 'Exception must carry the error count.', + ); + Assert::same( + $io->getOutput(), + ConsoleMessage::SCAFFOLD_APPLY_FAILED->getMessage( + 'scaffold-lock.json', + Message::PATH_RESERVED->getMessage('scaffold-lock.json'), + ) . PHP_EOL + . ExpectedSummary::line(1, 0, ExpectedSummary::part(1, ConsoleMessage::FRAGMENT_ERROR)) . PHP_EOL, + 'Failure must be reported and the summary must close the output.', + ); + Assert::same( + array_keys((new LockFile($builder->getProjectRoot()))->read()['files']), + ['a.txt'], + "Successful file 'a.txt' must still be recorded.", + ); + } + + public function throwScaffoldExceptionWhenAnAllowedManifestIsInvalid(): void + { + $builder = $this->project(); + + $io = new BufferIO(); + + $exception = $this->failingDispatch($builder, ['copy' => ['a.txt'], 'mdoes' => []], $io); + + $expected = Message::SCAFFOLD_MANIFEST_LOAD_FAILED->getMessage( + 'demo/scaffold', + Message::MANIFEST_KEY_UNKNOWN->getMessage( + 'mdoes', + 'allowed-packages, auto, copy, exclude, manifest, merge, modes', + ), + ); + + Assert::same( + $exception?->getMessage(), + $expected, + 'Exception must name the provider.', + ); + Assert::same( + $io->getOutput(), + $expected . PHP_EOL + . ExpectedSummary::line(0, 0, ExpectedSummary::part(1, ConsoleMessage::FRAGMENT_ERROR)) . PHP_EOL, + 'Failure must be reported and the summary must close the output.', + ); + FileAssert::fileDoesNotExist( + "{$builder->getProjectRoot()}/scaffold-lock.json", + 'Nothing may be recorded.', + ); + } + + /** + * Ensures a corrupt lock aborts the run with the chained cause after the summary, applying nothing. + */ + public function throwScaffoldExceptionWhenTheLockIsCorrupt(): void + { + $builder = $this->project(); + + $builder->createStubFile('demo/scaffold', 'a.txt', "a\n"); + $builder->createProjectFile('scaffold-lock.json', '{ not valid json'); + + $io = new BufferIO(); + + $exception = $this->failingDispatch($builder, ['copy' => ['a.txt']], $io); + + $expected = Message::SCAFFOLD_ABORTED->getMessage( + Message::LOCK_INVALID_JSON->getMessage( + (new LockFile((string) realpath($builder->getProjectRoot())))->getPath(), + 'Syntax error', + ), + ); + + Assert::same( + [$exception?->getMessage(), $exception?->getCode(), get_debug_type($exception?->getPrevious())], + [$expected, 0, RuntimeException::class], + "Exception must carry the cause, code '0' and the chained 'RuntimeException'.", + ); + Assert::same( + $io->getOutput(), + $expected . PHP_EOL + . ExpectedSummary::line(0, 0, ExpectedSummary::part(1, ConsoleMessage::FRAGMENT_ERROR)) . PHP_EOL, + 'Abort must be written before the summary.', + ); + FileAssert::fileDoesNotExist( + "{$builder->getProjectRoot()}/a.txt", + 'Nothing may be applied.', + ); + } + + /** + * Dispatches `post-install-cmd` with `demo/scaffold` shipping `$manifest` and returns the exception it throws, or + * `null`; the output stays in `$io`. + * + * @param array $manifest Raw `extra.scaffold` of `demo/scaffold`. + */ + private function failingDispatch( + FakeProjectBuilder $builder, + array $manifest, + BufferIO $io, + ): ScaffoldException|null { + try { + $this->dispatch($builder, $manifest, io: $io); + } catch (ScaffoldException $e) { + return $e; + } + + return null; + } +} diff --git a/tests/Functional/ComposerSummaryLineTest.php b/tests/Functional/ComposerSummaryLineTest.php new file mode 100644 index 0000000..c223500 --- /dev/null +++ b/tests/Functional/ComposerSummaryLineTest.php @@ -0,0 +1,99 @@ +project(['allowed-packages' => ['demo/scaffold', 'demo/missing']]); + + $manifest = ['copy' => ['a.txt', 'b.txt']]; + + $lockPath = "{$builder->getProjectRoot()}/scaffold-lock.json"; + + $builder->createStubFile('demo/scaffold', 'a.txt', "a\n"); + $builder->createStubFile('demo/scaffold', 'b.txt', "b\n"); + + Assert::same( + $this->dispatch($builder, $manifest), + Message::SCAFFOLD_PROVIDER_NOT_INSTALLED->getMessage('demo/missing') . PHP_EOL + . ExpectedSummary::line(2, 0, ExpectedSummary::part(1, Message::FRAGMENT_WARNING)) . PHP_EOL, + 'First run must warn about the missing provider and end with the summary.', + ); + Assert::same( + [ + (new LockFile($builder->getProjectRoot()))->read()['providers'], + array_keys((new LockFile($builder->getProjectRoot()))->read()['files']), + ], + [ + [ + 'demo/scaffold' => [ + 'version' => '1.0.0', + 'path' => str_replace('\\', '/', "{$builder->getVendorDir()}/demo/scaffold"), + ], + ], + ['a.txt', 'b.txt'], + ], + 'Lock must record the provider and both files.', + ); + + $this->project(); + + $lock = (string) file_get_contents($lockPath); + + Assert::same( + $this->dispatch($builder, $manifest), + '', + 'A no-op run must be silent.', + ); + FileAssert::contentSame( + $lockPath, + $lock, + 'A no-op run must leave the lock byte-identical.', + ); + + unlink("{$builder->getProjectRoot()}/a.txt"); + + Assert::same( + $this->dispatch($builder, $manifest), + ExpectedSummary::line(1, 1) . PHP_EOL, + 'A restored file must count as written.', + ); + + file_put_contents( + "{$builder->getProjectRoot()}/b.txt", + "mine\n", + ); + + Assert::same( + $this->dispatch($builder, $manifest), + Message::SCAFFOLD_PREFIXED->getMessage(Message::SCAFFOLD_USER_MODIFIED_SKIPPED->getMessage('b.txt')) + . PHP_EOL + . ExpectedSummary::line(0, 1, ExpectedSummary::part(1, Message::FRAGMENT_WARNING)) . PHP_EOL, + 'A warned run must end with the summary.', + ); + } +} diff --git a/tests/Functional/CreateProjectTest.php b/tests/Functional/CreateProjectTest.php deleted file mode 100644 index c20aab4..0000000 --- a/tests/Functional/CreateProjectTest.php +++ /dev/null @@ -1,358 +0,0 @@ -tempDir); - - $builder->createStubFile('demo/scaffold', '.gitignore', "/runtime/\n"); - $builder->createComposerJson( - [ - 'name' => 'demo/smoke-project', - 'config' => ['vendor-dir' => $builder->getVendorDir()], - 'extra' => [ - 'scaffold' => [ - 'allowed-packages' => [ - 'demo/scaffold', - ], - ], - ], - ], - ); - - // Pre-populate the lock so partial scaffold (fullScaffold=false) would skip '.gitignore'. - $builder->createProjectFile('.gitignore', "existing\n"); - - (new LockFile($builder->getProjectRoot()))->write( - [ - 'providers' => [ - 'demo/scaffold' => ['version' => '1.0.0', 'path' => $builder->getVendorDir() . '/demo/scaffold'], - ], - 'files' => [ - '.gitignore' => [ - 'hash' => 'sha256:' . hash('sha256', "existing\n"), - 'provider' => 'demo/scaffold', - 'source' => '.gitignore', - 'mode' => 'append', - ], - ], - ], - ); - - $io = new BufferIO(); - - $composer = $this->buildComposerForProject($builder->getProjectRoot(), $io); - $this->addMockProvider( - $composer, - 'demo/scaffold', - [ - 'copy' => ['.gitignore'], - 'modes' => ['.gitignore' => 'append'], - ], - ); - $this->resetInstallScaffoldRanFlag(); - - (new EventSubscriber())->onPostCreateProject($this->makePostCreateProjectEvent($composer, $io)); - - self::assertSame( - "existing\n/runtime/\n", - file_get_contents($builder->getProjectRoot() . '/.gitignore'), - "'onPostCreateProject' must dispatch with 'fullScaffold=true' so append entries apply even when already locked.", - ); - } - - public function testCreateProjectAppliesFullScaffoldWhenInstallDidNotRun(): void - { - $builder = new FakeProjectBuilder($this->tempDir); - - $builder->createStubFile('demo/scaffold', '.gitignore', "/runtime/\n"); - $builder->createComposerJson( - [ - 'name' => 'demo/smoke-project', - 'config' => ['vendor-dir' => $builder->getVendorDir()], - 'extra' => [ - 'scaffold' => [ - 'allowed-packages' => [ - 'demo/scaffold', - ], - ], - ], - ], - ); - - $io = new BufferIO(); - - $composer = $this->buildComposerForProject($builder->getProjectRoot(), $io); - $this->addMockProvider( - $composer, - 'demo/scaffold', - [ - 'copy' => ['.gitignore'], - 'modes' => ['.gitignore' => 'append'], - ], - ); - $this->resetInstallScaffoldRanFlag(); - - (new EventSubscriber())->onPostCreateProject($this->makePostCreateProjectEvent($composer, $io)); - - self::assertSame( - "/runtime/\n", - file_get_contents($builder->getProjectRoot() . '/.gitignore'), - "'post-create-project-cmd' alone must apply append-mode entries when post-install-cmd did not run before it.", - ); - } - - public function testInstallThenCreateProjectDoesNotDuplicateAppendEntries(): void - { - $builder = new FakeProjectBuilder($this->tempDir); - - $builder->createStubFile('demo/scaffold', '.gitignore', "/runtime/\n"); - $builder->createComposerJson( - [ - 'name' => 'demo/smoke-project', - 'config' => ['vendor-dir' => $builder->getVendorDir()], - 'extra' => [ - 'scaffold' => [ - 'allowed-packages' => [ - 'demo/scaffold', - ], - ], - ], - ], - ); - - $io = new BufferIO(); - - $composer = $this->buildComposerForProject($builder->getProjectRoot(), $io); - $this->addMockProvider( - $composer, - 'demo/scaffold', - [ - 'copy' => ['.gitignore'], - 'modes' => ['.gitignore' => 'append'], - ], - ); - $this->resetInstallScaffoldRanFlag(); - - $subscriber = new EventSubscriber(); - - // Composer 'create-project' fires post-install-cmd first, then post-create-project-cmd within the same process. - $subscriber->onPostInstall($this->makePostInstallEvent($composer, $io)); - $subscriber->onPostCreateProject($this->makePostCreateProjectEvent($composer, $io)); - - self::assertSame( - "/runtime/\n", - file_get_contents($builder->getProjectRoot() . '/.gitignore'), - "'post-create-project-cmd' must short-circuit when 'post-install-cmd' already ran to avoid duplicate appends.", - ); - } - - public function testLockRecordsBothFilesAndProvidersAfterCreateProjectFlow(): void - { - $builder = new FakeProjectBuilder($this->tempDir); - - $builder->createStubFile('demo/scaffold', 'config/params.php', "createComposerJson( - [ - 'name' => 'demo/smoke-project', - 'config' => ['vendor-dir' => $builder->getVendorDir()], - 'extra' => [ - 'scaffold' => [ - 'allowed-packages' => [ - 'demo/scaffold', - ], - ], - ], - ], - ); - - $io = new BufferIO(); - - $composer = $this->buildComposerForProject($builder->getProjectRoot(), $io); - $this->addMockProvider( - $composer, - 'demo/scaffold', - [ - 'copy' => ['config/params.php'], - ], - '2.5.0', - ); - $this->resetInstallScaffoldRanFlag(); - - $subscriber = new EventSubscriber(); - - $subscriber->onPostInstall($this->makePostInstallEvent($composer, $io)); - $subscriber->onPostCreateProject($this->makePostCreateProjectEvent($composer, $io)); - - $lockData = (new LockFile($builder->getProjectRoot()))->read(); - - $providerEntry = $lockData['providers']['demo/scaffold'] ?? null; - - self::assertIsArray( - $providerEntry, - 'Lock must contain an entry for the authorized provider.', - ); - self::assertSame( - '2.5.0', - $providerEntry['version'] ?? null, - 'Provider version reported by Composer must be persisted into the lock file.', - ); - self::assertArrayHasKey( - 'config/params.php', - $lockData['files'], - 'Destinations applied during the create-project flow must be tracked in the lock file.', - ); - } - - public function testOnPostInstallSkipsAppendEntryAlreadyInLockToAvoidDuplication(): void - { - $builder = new FakeProjectBuilder($this->tempDir); - - $builder->createStubFile('demo/scaffold', '.gitignore', "/runtime/\n"); - $builder->createComposerJson( - [ - 'name' => 'demo/smoke-project', - 'config' => ['vendor-dir' => $builder->getVendorDir()], - 'extra' => [ - 'scaffold' => [ - 'allowed-packages' => [ - 'demo/scaffold', - ], - ], - ], - ], - ); - - $builder->createProjectFile('.gitignore', "existing\n"); - - (new LockFile($builder->getProjectRoot()))->write( - [ - 'providers' => [ - 'demo/scaffold' => ['version' => '1.0.0', 'path' => $builder->getVendorDir() . '/demo/scaffold'], - ], - 'files' => [ - '.gitignore' => [ - 'hash' => 'sha256:' . hash('sha256', "existing\n"), - 'provider' => 'demo/scaffold', - 'source' => '.gitignore', - 'mode' => 'append', - ], - ], - ], - ); - - $io = new BufferIO(); - - $composer = $this->buildComposerForProject($builder->getProjectRoot(), $io); - $this->addMockProvider( - $composer, - 'demo/scaffold', - [ - 'copy' => ['.gitignore'], - 'modes' => ['.gitignore' => 'append'], - ], - ); - $this->resetInstallScaffoldRanFlag(); - - (new EventSubscriber())->onPostInstall($this->makePostInstallEvent($composer, $io)); - - self::assertSame( - "existing\n", - file_get_contents($builder->getProjectRoot() . '/.gitignore'), - "'onPostInstall' must dispatch with 'fullScaffold=false' so locked append entries are skipped.", - ); - } - - public function testOnPostUpdateSkipsAppendEntryAlreadyInLockToAvoidDuplication(): void - { - $builder = new FakeProjectBuilder($this->tempDir); - - $builder->createStubFile('demo/scaffold', '.gitignore', "/runtime/\n"); - $builder->createComposerJson( - [ - 'name' => 'demo/smoke-project', - 'config' => ['vendor-dir' => $builder->getVendorDir()], - 'extra' => [ - 'scaffold' => [ - 'allowed-packages' => [ - 'demo/scaffold', - ], - ], - ], - ], - ); - - $builder->createProjectFile('.gitignore', "existing\n"); - - (new LockFile($builder->getProjectRoot()))->write( - [ - 'providers' => [ - 'demo/scaffold' => ['version' => '1.0.0', 'path' => $builder->getVendorDir() . '/demo/scaffold'], - ], - 'files' => [ - '.gitignore' => [ - 'hash' => 'sha256:' . hash('sha256', "existing\n"), - 'provider' => 'demo/scaffold', - 'source' => '.gitignore', - 'mode' => 'append', - ], - ], - ], - ); - - $io = new BufferIO(); - - $composer = $this->buildComposerForProject($builder->getProjectRoot(), $io); - $this->addMockProvider( - $composer, - 'demo/scaffold', - [ - 'copy' => ['.gitignore'], - 'modes' => ['.gitignore' => 'append'], - ], - ); - $this->resetInstallScaffoldRanFlag(); - - (new EventSubscriber())->onPostUpdate($this->makePostUpdateEvent($composer, $io)); - - self::assertSame( - "existing\n", - file_get_contents($builder->getProjectRoot() . '/.gitignore'), - "'onPostUpdate' must dispatch with 'fullScaffold=false' so locked append entries are skipped.", - ); - } - - protected function setUp(): void - { - $this->setUpTempDirectory(); - } - - protected function tearDown(): void - { - $this->tearDownTempDirectory(); - $this->resetInstallScaffoldRanFlag(); - } -} diff --git a/tests/Functional/IntegerLikeDestinationTest.php b/tests/Functional/IntegerLikeDestinationTest.php new file mode 100644 index 0000000..21d8cd4 --- /dev/null +++ b/tests/Functional/IntegerLikeDestinationTest.php @@ -0,0 +1,264 @@ + ['123', '0'], 'modes' => ['0' => 'preserve']]; + + /** + * Ensures `diff` renders an edited integer-like destination under its own label. + */ + public function diffRendersIntegerLikeDestination(): void + { + $builder = $this->scaffold(); + + file_put_contents( + "{$builder->getProjectRoot()}/123", + "edited\n", + ); + + $out = new BufferedOutputWriter(); + + Assert::same( + (new DiffService())->run($this->context($builder), $out, '123'), + 0, + "Exit code must be '0'.", + ); + Assert::same( + [$out->stdoutBuffer, $out->stderrBuffer], + [ + Message::DIFF_PREVIEW_HEADER->getMessage( + '123', + 'replace', + 'php-forge/numeric', + Message::FRAGMENT_USER_MODIFIED_PREVIEW->getMessage(), + ) . PHP_EOL + . "--- a/123\n+++ b/123\n@@ -1 +1 @@\n-edited\n+one two three" . PHP_EOL, + '', + ], + "Diff must label the destination '123' and report no error.", + ); + } + + /** + * Ensures `eject` marks only the integer-like destination as ejected and keeps the file. + */ + public function ejectMarksIntegerLikeDestinationEjected(): void + { + $builder = $this->scaffold(); + + Assert::same( + (new EjectService())->run($builder->getProjectRoot(), new BufferedOutputWriter(), '123', true), + 0, + "Exit code must be '0'.", + ); + + $files = (new LockFile($builder->getProjectRoot()))->read()['files']; + + Assert::same( + [array_keys($files), $files['123']['ejected'] ?? false], + [[0, 123], true], + "Entry '123' must be 'ejected' and entry '0' must stay.", + ); + FileAssert::fileExists( + "{$builder->getProjectRoot()}/123", + 'Ejected file must stay on disk.', + ); + } + + /** + * Ensures `reapply` of the integer-like destination `0` restores only that file. + */ + public function reapplyRestoresIntegerLikeDestination(): void + { + $builder = $this->scaffold(); + + file_put_contents("{$builder->getProjectRoot()}/0", "edited\n"); + + $out = new BufferedOutputWriter(); + + Assert::same( + (new ReapplyService())->run($this->context($builder), $out, '0', '', true), + 0, + "Exit code must be '0'.", + ); + Assert::same( + $out->stdoutBuffer, + Message::REAPPLY_APPLIED->getMessage('0') . PHP_EOL + . Message::REAPPLY_SUMMARY->getMessage( + '', + 1, + Message::FRAGMENT_WRITTEN->getMessage(), + 0, + 0, + '', + 0, + Message::FRAGMENT_ERRORS->getMessage(), + ) + . PHP_EOL, + "Only the filtered file '0' must be reapplied.", + ); + FileAssert::contentSame( + "{$builder->getProjectRoot()}/0", + "zero\n", + 'Stub must be restored.', + ); + } + + /** + * Ensures the scaffolder writes integer-like destinations and applies the mode pattern keyed by one. + */ + public function scaffoldWritesIntegerLikeDestinations(): void + { + $builder = $this->scaffold($io = new BufferIO()); + + FileAssert::contentSame( + "{$builder->getProjectRoot()}/123", + "one two three\n", + "File '123' must be written.", + ); + FileAssert::contentSame( + "{$builder->getProjectRoot()}/0", + "zero\n", + "File '0' must be written.", + ); + Assert::same( + $io->getOutput(), + '', + 'No error may be reported.', + ); + + $files = (new LockFile($builder->getProjectRoot()))->read()['files']; + + Assert::same( + [$files['0']['mode'] ?? null, $files['123']['mode'] ?? null], + ['preserve', 'replace'], + "Entry '0' must take the 'preserve' pattern and entry '123' the default mode.", + ); + } + + /** + * Ensures `status` reports integer-like destinations in the JSON report and the table. + */ + public function statusReportsIntegerLikeDestinations(): void + { + $builder = $this->scaffold(); + $json = new BufferedOutputWriter(); + $table = new BufferedOutputWriter(); + + (new StatusService()) + ->run($this->context($builder), $json, true); + + $report = json_decode($json->stdoutBuffer, true, flags: JSON_THROW_ON_ERROR); + + Assert::same( + is_array($report) ? $report['files'] ?? null : null, + [ + '0' => ['provider' => 'php-forge/numeric', 'mode' => 'preserve', 'status' => 'synced'], + '123' => ['provider' => 'php-forge/numeric', 'mode' => 'replace', 'status' => 'synced'], + ], + "Files '123' and '0' must be 'synced'.", + ); + Assert::same( + (new StatusService())->run($this->context($builder), $table), + 0, + "Exit code must be '0'.", + ); + Assert::same( + $table->stdoutBuffer, + 'File Provider Mode Status' . PHP_EOL + . '-----------------------------------------' . PHP_EOL + . '0 php-forge/numeric preserve synced' . PHP_EOL + . '123 php-forge/numeric replace synced' . PHP_EOL + . Message::STATUS_SUMMARY->getMessage( + 2, + Message::FRAGMENT_FILES->getMessage(), + Message::FRAGMENT_COUNT->getMessage(2, 'synced'), + ) . PHP_EOL, + "Table must list '0' and '123'.", + ); + } + + /** + * Returns the services context of the project of `$builder`, whose vendor directory is a sibling of its root. + */ + private function context(FakeProjectBuilder $builder): ProjectContext + { + $root = $builder->getProjectRoot(); + + return new ProjectContext( + $root, + $builder->getVendorDir(), + ProjectConfig::fromComposerJson("{$root}/composer.json"), + InstalledPackages::detect($builder->getVendorDir(), $root), + ); + } + + /** + * Scaffolds the provider `php-forge/numeric`, which ships the destinations `123` and `0`, into a fake project and + * returns its builder. + * + * @param BufferIO $io IO of the run. + */ + private function scaffold(BufferIO $io = new BufferIO()): FakeProjectBuilder + { + $builder = new FakeProjectBuilder($this->tempDir); + + $extra = ['scaffold' => ['allowed-packages' => ['php-forge/numeric']]]; + + $config = ProjectConfig::fromExtra($extra); + + $provider = new CompletePackage('php-forge/numeric', '1.0.0.0', '1.0.0'); + + $builder->createComposerJson(['extra' => $extra]); + $builder->createStubFile( + 'php-forge/numeric', + 'composer.json', + json_encode(['extra' => ['scaffold' => self::MANIFEST]], JSON_THROW_ON_ERROR), + ); + $builder->createStubFile('php-forge/numeric', '123', "one two three\n"); + $builder->createStubFile('php-forge/numeric', '0', "zero\n"); + $provider->setExtra(['scaffold' => self::MANIFEST]); + + (new Scaffolder( + new ManifestLoader(new ManifestSchema(), new ManifestExpander()), + new FileApplier($config, new PathValidator(), new ComposerIoWriter($io)), + new LockFile($builder->getProjectRoot()), + new ComposerIoWriter($io), + new ScaffoldSummary(), + ))->scaffold($config, [$provider], $builder->getProjectRoot(), $builder->getVendorDir()); + + return $builder; + } +} diff --git a/tests/Functional/MultiLayerCompositionTest.php b/tests/Functional/MultiLayerCompositionTest.php deleted file mode 100644 index 0c0f2f2..0000000 --- a/tests/Functional/MultiLayerCompositionTest.php +++ /dev/null @@ -1,134 +0,0 @@ -seedTwoProvidersSharingDestination(); - - $builder->createComposerJson( - [ - 'name' => 'demo/composition', - 'config' => ['vendor-dir' => $builder->getVendorDir()], - 'extra' => [ - // Provider 'provider-b' is listed last, so its stub must win. - 'scaffold' => [ - 'allowed-packages' => [ - 'demo/provider-a', - 'demo/provider-b', - ], - ], - ], - ], - ); - - $io = new BufferIO(); - - $composer = $this->buildComposerForProject($builder->getProjectRoot(), $io); - $this->addMockProvidersSharingDestination($composer); - $this->resetInstallScaffoldRanFlag(); - - (new EventSubscriber())->onPostCreateProject($this->makePostCreateProjectEvent($composer, $io)); - - self::assertSame( - 'provider-b content', - file_get_contents($builder->getProjectRoot() . '/config/web.php'), - 'When multiple allowed providers map the same destination, the last entry in allowed-packages must win.', - ); - - $lockData = (new LockFile($builder->getProjectRoot()))->read(); - - self::assertSame( - 'demo/provider-b', - $lockData['files']['config/web.php']['provider'] ?? null, - 'Lock file must attribute the destination to the winning provider, not the overridden one.', - ); - } - - public function testSwappedOrderChangesPrecedence(): void - { - $builder = $this->seedTwoProvidersSharingDestination(); - - $builder->createComposerJson( - [ - 'name' => 'demo/composition', - 'config' => ['vendor-dir' => $builder->getVendorDir()], - 'extra' => [ - // Now provider-a is listed last. - 'scaffold' => [ - 'allowed-packages' => [ - 'demo/provider-b', - 'demo/provider-a', - ], - ], - ], - ], - ); - - $io = new BufferIO(); - - $composer = $this->buildComposerForProject($builder->getProjectRoot(), $io); - $this->addMockProvidersSharingDestination($composer); - $this->resetInstallScaffoldRanFlag(); - - (new EventSubscriber())->onPostCreateProject($this->makePostCreateProjectEvent($composer, $io)); - - self::assertSame( - 'provider-a content', - file_get_contents($builder->getProjectRoot() . '/config/web.php'), - 'Swapping the order of allowed-packages must swap which provider wins the shared destination.', - ); - } - - protected function setUp(): void - { - $this->setUpTempDirectory(); - } - - protected function tearDown(): void - { - $this->tearDownTempDirectory(); - $this->resetInstallScaffoldRanFlag(); - } - - private function addMockProvidersSharingDestination(Composer $composer): void - { - $manifest = ['copy' => ['config/web.php']]; - - $this->addMockProvider($composer, 'demo/provider-a', $manifest); - $this->addMockProvider($composer, 'demo/provider-b', $manifest); - } - - private function seedTwoProvidersSharingDestination(): FakeProjectBuilder - { - $builder = new FakeProjectBuilder($this->tempDir); - - $builder->createStubFile('demo/provider-a', 'config/web.php', 'provider-a content'); - $builder->createStubFile('demo/provider-b', 'config/web.php', 'provider-b content'); - - return $builder; - } -} diff --git a/tests/Functional/PostCreateProjectTest.php b/tests/Functional/PostCreateProjectTest.php new file mode 100644 index 0000000..0ae7f0d --- /dev/null +++ b/tests/Functional/PostCreateProjectTest.php @@ -0,0 +1,143 @@ +project(); + + $manifest = [ + 'copy' => ['.gitignore'], + 'modes' => ['.gitignore' => 'append'], + ]; + + $path = "{$builder->getProjectRoot()}/.gitignore"; + + $builder->createStubFile('demo/scaffold', '.gitignore', "/runtime/\n"); + $builder->createProjectFile('.gitignore', "existing\n"); + + (new LockFile($builder->getProjectRoot()))->write( + [ + 'providers' => [ + 'demo/scaffold' => ['version' => '1.0.0', 'path' => "{$builder->getVendorDir()}/demo/scaffold"], + ], + 'files' => [ + '.gitignore' => [ + 'hash' => 'sha256:' . hash('sha256', "existing\n"), + 'provider' => 'demo/scaffold', + 'source' => '.gitignore', + 'mode' => 'append', + ], + ], + ], + ); + + $this->dispatch($builder, $manifest, $event); + + FileAssert::contentSame( + $path, + "existing\n\n/runtime/\n", + 'Locked append file must receive the missing entry.', + ); + + $this->dispatch($builder, $manifest, $event); + + FileAssert::contentSame( + $path, + "existing\n\n/runtime/\n", + 'Second run must not duplicate the entry.', + ); + } + + #[DataProvider(PostCreateProjectProvider::class . '::installEvents')] + public function postCreateProjectDoesNothingAfterAnInstallRun(string $event): void + { + $builder = $this->project(); + + $root = $builder->getProjectRoot(); + + $manifest = [ + 'copy' => ['.gitignore', 'config/params.php', 'src/bootstrap.php'], + 'modes' => ['.gitignore' => 'append', 'src/bootstrap.php' => 'prepend'], + ]; + + $builder->createStubFile('demo/scaffold', '.gitignore', "/runtime/\n"); + $builder->createStubFile('demo/scaffold', 'config/params.php', "createStubFile('demo/scaffold', 'src/bootstrap.php', "// PROVIDER HEADER\n"); + $builder->createProjectFile('src/bootstrap.php', "// user code\n"); + + $this->dispatch($builder, $manifest, $event, '2.5.0'); + + unlink("{$root}/config/params.php"); + + Assert::same( + $this->dispatch($builder, $manifest, ScriptEvents::POST_CREATE_PROJECT_CMD, '2.5.0'), + '', + 'The skipped run must write nothing.', + ); + Assert::same( + [ + '.gitignore' => file_get_contents("{$root}/.gitignore"), + 'src/bootstrap.php' => file_get_contents("{$root}/src/bootstrap.php"), + ], + [ + '.gitignore' => "/runtime/\n", + 'src/bootstrap.php' => "// PROVIDER HEADER\n// user code\n", + ], + 'Append and prepend blocks must appear once.', + ); + FileAssert::fileDoesNotExist( + "{$root}/config/params.php", + 'The skipped run must not restore a deleted file.', + ); + + $lock = (new LockFile($root))->read(); + + Assert::same( + [$lock['providers'], array_keys($lock['files'])], + [ + [ + 'demo/scaffold' => [ + 'version' => '2.5.0', + 'path' => str_replace('\\', '/', "{$builder->getVendorDir()}/demo/scaffold"), + ], + ], + ['.gitignore', 'config/params.php', 'src/bootstrap.php'], + ], + "Lock must record provider version '2.5.0' and every file.", + ); + } +} diff --git a/tests/Functional/ScaffolderTest.php b/tests/Functional/ScaffolderTest.php index 456dbb2..5b975a4 100644 --- a/tests/Functional/ScaffolderTest.php +++ b/tests/Functional/ScaffolderTest.php @@ -4,1085 +4,1306 @@ namespace PHPForge\Scaffold\Tests\Functional; -use Composer\IO\{BufferIO, IOInterface, NullIO}; -use Composer\Package\PackageInterface; +use Closure; +use Composer\IO\BufferIO; +use Composer\Package\{CompletePackage, PackageInterface}; +use PHPForge\Scaffold\Config\ProjectConfig; +use PHPForge\Scaffold\Console\{ComposerIoWriter, Message as ConsoleMessage}; +use PHPForge\Scaffold\Exception\{Message, ScaffoldException}; use PHPForge\Scaffold\Manifest\{ManifestExpander, ManifestLoader, ManifestSchema}; -use PHPForge\Scaffold\Scaffold\{Applier, Scaffolder}; +use PHPForge\Scaffold\Scaffold\FileApplier; use PHPForge\Scaffold\Scaffold\Lock\{Hasher, LockFile}; -use PHPForge\Scaffold\Security\{PackageAllowlist, PathValidator}; -use PHPForge\Scaffold\Tests\Support\{FakeProjectBuilder, TempDirectoryTrait}; -use PHPUnit\Framework\Attributes\Group; -use PHPUnit\Framework\TestCase; +use PHPForge\Scaffold\Scaffold\{ScaffoldRunner, ScaffoldSummary, Scaffolder}; +use PHPForge\Scaffold\Security\PathValidator; +use PHPForge\Scaffold\Tests\Provider\ScaffolderProvider; +use PHPForge\Scaffold\Tests\Support\{FakeProjectBuilder, FileAssert, TempDirectoryTrait}; use ReflectionMethod; +use Testo\Assert; +use Testo\Core\Exception\SkipTest; +use Testo\Data\DataProvider; +use Testo\Test; + +use function array_column; +use function array_filter; +use function array_intersect_key; +use function array_keys; +use function array_map; +use function file_get_contents; +use function file_put_contents; +use function hash; +use function mkdir; +use function str_replace; +use function symlink; +use function unlink; /** * Functional tests for {@see Scaffolder} end-to-end scaffold execution. + * + * {@see ScaffolderProvider} for test case data providers. */ -#[Group('scaffold')] -#[Group('functional')] -final class ScaffolderTest extends TestCase +#[Test] +final class ScaffolderTest { use TempDirectoryTrait; - public function testAllowedPackageNotInstalledEmitsSkipMessage(): void + /** + * Ensures an adopted preserve file stays the user's when the provider switches it to replace mode. + */ + public function adoptedPreserveFileIsSkippedWhenProviderFlipsItToReplace(): void { $builder = new FakeProjectBuilder($this->tempDir); - // Root authorizes a provider that was never added to the installed-packages list. - $root = $this->makeRootPackage(['php-forge/missing']); - $io = new BufferIO(); - $scaffolder = new Scaffolder( - new ManifestLoader(new ManifestSchema(), new ManifestExpander()), - new Applier( - new PackageAllowlist(['php-forge/missing']), - new PathValidator(), - new Hasher(), - $io, - ), - new LockFile($builder->getProjectRoot()), - $io, - ); - $scaffolder->scaffold($root, [], $builder->getProjectRoot(), $builder->getVendorDir(), true); + $builder->createStubFile('php-forge/test', 'ecs.php', "stub\n"); + $builder->createProjectFile('ecs.php', "mine\n"); - self::assertStringContainsString( - 'Provider "php-forge/missing" is not installed', - $io->getOutput(), - "Allowed providers not installed by Composer must emit a skip message so 'allowed-packages' typos are noticed.", + self::scaffold( + $builder, + ['php-forge/test'], + [self::provider('php-forge/test', ['copy' => ['ecs.php'], 'modes' => ['ecs.php' => 'preserve']])], ); - } - - public function testAppendModeIsIdempotentOnFullScaffold(): void - { - $builder = new FakeProjectBuilder($this->tempDir); - - $builder->createStubFile('php-forge/test', '.gitignore', '*.log'); - $builder->createProjectFile('.gitignore', 'vendor/'); - $provider = $this->makeProviderPackage( - 'php-forge/test', - [ - 'scaffold' => [ - 'copy' => ['.gitignore'], - 'modes' => ['.gitignore' => 'append'], - ], - ], + Assert::true( + self::lockEntry($builder, 'ecs.php')['adopted'] ?? false, + "Existing file must be 'adopted'.", ); - $root = $this->makeRootPackage(['php-forge/test']); - $scaffolder = $this->makeScaffolder(['php-forge/test'], $builder); - - // First run: full scaffold writes the missing line. - $scaffolder->scaffold($root, [$provider], $builder->getProjectRoot(), $builder->getVendorDir(), true); - - $afterFirst = file_get_contents($builder->getProjectRoot() . '/.gitignore'); - - // Second full scaffold: every provider line is already present, so nothing should change. - $scaffolder->scaffold($root, [$provider], $builder->getProjectRoot(), $builder->getVendorDir(), true); - $afterSecond = file_get_contents($builder->getProjectRoot() . '/.gitignore'); + self::scaffold( + $builder, + ['php-forge/test'], + [self::provider('php-forge/test', ['copy' => ['ecs.php']])], + $io, + ); - self::assertSame( - $afterFirst, - $afterSecond, - 'Append mode must be idempotent on full scaffold and never duplicate provider lines already present.', + FileAssert::contentSame( + "{$builder->getProjectRoot()}/ecs.php", + "mine\n", + 'User file must be kept.', + ); + Assert::same( + $io->getOutput(), + ConsoleMessage::SCAFFOLD_ADOPTED_SKIPPED->getMessage('ecs.php') . PHP_EOL, + 'Skip must be reported.', + ); + Assert::true( + self::lockEntry($builder, 'ecs.php')['adopted'] ?? false, + "Entry must stay 'adopted'.", ); } - public function testAppendModeRefreshesLockOwnershipWhenNewProviderClaimsExistingFile(): void + /** + * Ensures a skipped append file is attributed to the provider that now claims it. + */ + public function appendModeRefreshesLockOwnershipWhenNewProviderClaimsExistingFile(): void { $builder = new FakeProjectBuilder($this->tempDir); - // Two providers ship the same '.gitignore' content; the destination already matches both stubs identically. + $manifest = [ + 'copy' => ['.gitignore'], + 'modes' => ['.gitignore' => 'append'], + ]; + $builder->createStubFile('php-forge/old-provider', '.gitignore', "*.log\n"); $builder->createStubFile('php-forge/new-provider', '.gitignore', "*.log\n"); $builder->createProjectFile('.gitignore', "*.log\n"); - $oldProvider = $this->makeProviderPackage( - 'php-forge/old-provider', - ['scaffold' => ['copy' => ['.gitignore'], 'modes' => ['.gitignore' => 'append']]], - ); - $newProvider = $this->makeProviderPackage( - 'php-forge/new-provider', - ['scaffold' => ['copy' => ['.gitignore'], 'modes' => ['.gitignore' => 'append']]], + self::scaffold( + $builder, + ['php-forge/old-provider'], + [ + self::provider( + 'php-forge/old-provider', + $manifest + ), + ], ); - // First run: only the old provider is allowed; lock records its ownership. - $oldRoot = $this->makeRootPackage(['php-forge/old-provider']); - $oldScaffolder = $this->makeScaffolder(['php-forge/old-provider'], $builder); - $oldScaffolder->scaffold($oldRoot, [$oldProvider], $builder->getProjectRoot(), $builder->getVendorDir(), true); - - $oldLock = (new LockFile($builder->getProjectRoot()))->read(); - - self::assertSame( + Assert::same( + self::lockEntry($builder, '.gitignore')['provider'] ?? null, 'php-forge/old-provider', - $oldLock['files']['.gitignore']['provider'] ?? null, - 'Initial scaffold must record the old provider as the owner.', + "Initial owner must be 'php-forge/old-provider'.", ); - // Second run: only the new provider is allowed. AppendMode finds no missing lines (Skipped) but the - // ownership metadata must be refreshed to point to the new provider. - $newRoot = $this->makeRootPackage(['php-forge/new-provider']); - $newScaffolder = $this->makeScaffolder(['php-forge/new-provider'], $builder); - $newScaffolder->scaffold($newRoot, [$newProvider], $builder->getProjectRoot(), $builder->getVendorDir(), true); - - $newLock = (new LockFile($builder->getProjectRoot()))->read(); + self::scaffold( + $builder, + ['php-forge/new-provider'], + [ + self::provider( + 'php-forge/new-provider', + $manifest + ), + ], + ); - self::assertSame( + Assert::same( + self::lockEntry($builder, '.gitignore')['provider'] ?? null, 'php-forge/new-provider', - $newLock['files']['.gitignore']['provider'] ?? null, - 'Skipped append must refresh the lock ownership metadata when a different provider claims the file.', + "A skipped append must move ownership to 'php-forge/new-provider'.", ); } - public function testAppendModeSkippedOnInstallWhenAlreadyInLock(): void + /** + * Ensures a new provider line lands under its comment header on a partial run and both hashes follow. + */ + public function appendNewProviderLinePropagatesOnPartialRun(): void { $builder = new FakeProjectBuilder($this->tempDir); - $builder->createStubFile('php-forge/test', '.gitignore', '*.log'); - $builder->createProjectFile('.gitignore', 'vendor/'); - - $provider = $this->makeProviderPackage( + $provider = self::provider( 'php-forge/test', - [ - 'scaffold' => [ - 'copy' => ['.gitignore'], - 'modes' => ['.gitignore' => 'append'], - ], - ], + ['copy' => ['.gitignore'], 'modes' => ['.gitignore' => 'append']], ); - $root = $this->makeRootPackage(['php-forge/test']); - $scaffolder = $this->makeScaffolder(['php-forge/test'], $builder); - // First run: full scaffold writes the append and records lock. - $scaffolder->scaffold($root, [$provider], $builder->getProjectRoot(), $builder->getVendorDir(), true); + $path = "{$builder->getProjectRoot()}/.gitignore"; - $afterFirst = file_get_contents($builder->getProjectRoot() . '/.gitignore'); + $builder->createStubFile('php-forge/test', '.gitignore', "# logs\n*.log\n"); + $builder->createProjectFile('.gitignore', "vendor/\n"); - // Second run: partial (install) append is already in lock, must be skipped. - $scaffolder->scaffold($root, [$provider], $builder->getProjectRoot(), $builder->getVendorDir(), false); + self::scaffold( + $builder, + ['php-forge/test'], + [$provider], + ); + + $builder->createStubFile('php-forge/test', '.gitignore', "# logs\n*.log\n*.cache\n"); - self::assertSame( - $afterFirst, - file_get_contents($builder->getProjectRoot() . '/.gitignore'), - 'Append mode file should not be re-appended on install if already in lock.', + self::scaffold( + $builder, + ['php-forge/test'], + [$provider], + ); + + FileAssert::contentSame( + $path, + "vendor/\n\n# logs\n*.log\n*.cache\n", + 'New entry must land under its header.', + ); + Assert::same( + array_intersect_key(self::lockEntry($builder, '.gitignore'), ['hash' => true, 'stub-hash' => true]), + ['hash' => Hasher::hash($path), 'stub-hash' => self::stubHash($builder, '.gitignore')], + 'Lock hash must follow the rewritten file and stub hash the bumped stub.', ); } - public function testApplierExceptionIsLoggedAndScaffoldingContinues(): void + /** + * Ensures a destination that the applier rejects is reported per file without aborting the run. + */ + public function applierExceptionIsReportedWithoutAbortingTheRun(): void { $builder = new FakeProjectBuilder($this->tempDir); + $io = new BufferIO(); - // Allowlist names a different provider so 'apply()' throws "Package not allowed"; the loop must catch and log it. $builder->createStubFile('php-forge/test', 'app.php', 'content'); - $provider = $this->makeProviderPackage( - 'php-forge/test', - [ - 'scaffold' => [ - 'copy' => ['app.php'], - ], - ], - ); - $root = $this->makeRootPackage(['php-forge/test']); - - $io = new BufferIO(); - - // Allowlist only admits a DIFFERENT provider, so assertAllowed throws RuntimeException during apply(). - $scaffolder = new Scaffolder( - new ManifestLoader(new ManifestSchema(), new ManifestExpander()), - new Applier(new PackageAllowlist(['safe/other']), new PathValidator(), new Hasher(), $io), - new LockFile($builder->getProjectRoot()), - $io, + self::scaffolder($builder, self::config(['safe/other']), $io)->scaffold( + self::config(['php-forge/test']), + [self::provider('php-forge/test', ['copy' => ['app.php']])], + $builder->getProjectRoot(), + $builder->getVendorDir(), ); - $scaffolder->scaffold($root, [$provider], $builder->getProjectRoot(), $builder->getVendorDir(), true); - - self::assertStringContainsString( - 'Error applying "app.php"', + Assert::same( $io->getOutput(), - 'Applier exceptions must be caught per-destination and reported via writeError without aborting the loop.', + ConsoleMessage::SCAFFOLD_APPLY_FAILED->getMessage( + 'app.php', + Message::PACKAGE_NOT_ALLOWED->getMessage('php-forge/test'), + ) . PHP_EOL, + 'The rejection must be reported.', + ); + FileAssert::fileDoesNotExist( + "{$builder->getProjectRoot()}/app.php", + 'Nothing may be written.', ); } - public function testEmptyAllowedPackagesIsNoop(): void + /** + * Ensures a destination that is a symlink escaping the root is rejected without creating the target. + */ + public function danglingSymlinkDestinationIsNotWrittenOutsideRoot(): void { - $this->expectNotToPerformAssertions(); + if (DIRECTORY_SEPARATOR === '\\') { + throw new SkipTest('Dangling symlink resolution is only verified on POSIX.'); + } $builder = new FakeProjectBuilder($this->tempDir); + $io = new BufferIO(); - $root = $this->makeRootPackage([]); - $this - ->makeScaffolder([], $builder) - ->scaffold($root, [], $builder->getProjectRoot(), $builder->getVendorDir(), true); - } + $outside = "{$this->tempDir}/outside"; - public function testEmptyAllowedPackagesListEmitsSkipMessage(): void - { - $builder = new FakeProjectBuilder($this->tempDir); + mkdir($outside); - // Root with `extra.scaffold` present but the allowed-packages list explicitly empty. - $root = self::createStub(PackageInterface::class); - $root->method('getExtra')->willReturn(['scaffold' => ['allowed-packages' => []]]); + $builder->createStubFile('php-forge/test', 'rep.txt', 'provider bytes'); - $io = new BufferIO(); - $scaffolder = new Scaffolder( - new ManifestLoader(new ManifestSchema(), new ManifestExpander()), - new Applier(new PackageAllowlist([]), new PathValidator(), new Hasher(), $io), - new LockFile($builder->getProjectRoot()), + symlink("{$outside}/OUTSIDE_TARGET.txt", "{$builder->getProjectRoot()}/rep.txt"); + + self::scaffold( + $builder, + ['php-forge/test'], + [self::provider('php-forge/test', ['copy' => ['rep.txt']])], $io, ); - $scaffolder->scaffold($root, [], $builder->getProjectRoot(), $builder->getVendorDir(), true); - - self::assertStringContainsString( - 'No allowed-packages configured', - $io->getOutput(), - 'Empty allowed-packages list must emit the configured-but-empty skip message.', + FileAssert::fileDoesNotExist( + "{$outside}/OUTSIDE_TARGET.txt", + 'No file may be created outside the root.', ); - } - - public function testEmptyManifestReturnsEarlyAndDoesNotWriteLockFile(): void - { - $builder = new FakeProjectBuilder($this->tempDir); - - // Provider has no scaffold extra at all; loader returns an empty mapping list and the lock stays untouched. - $provider = $this->makeProviderPackage('php-forge/empty', []); - $root = $this->makeRootPackage(['php-forge/empty']); - - $this - ->makeScaffolder(['php-forge/empty'], $builder) - ->scaffold($root, [$provider], $builder->getProjectRoot(), $builder->getVendorDir(), true); - - self::assertFalse( - (new LockFile($builder->getProjectRoot()))->exists(), - 'An empty manifest must short-circuit before the lock is written.', + Assert::same( + $io->getOutput(), + ConsoleMessage::SCAFFOLD_APPLY_FAILED->getMessage( + 'rep.txt', + Message::PATH_SYMLINK_ESCAPE->getMessage('Destination', 'rep.txt'), + ) . PHP_EOL, + 'The rejection must be reported.', ); } - public function testFailedManifestLoadIsLoggedAndSkippedInsteadOfFatal(): void + /** + * Ensures a deleted append file is written again on the next run. + */ + public function deletedAppendFileIsRecreatedOnPartialRun(): void { $builder = new FakeProjectBuilder($this->tempDir); - $provider = $this->makeProviderPackage( - 'php-forge/bad', + $provider = self::provider( + 'php-forge/test', [ - // `manifest: "../escape.json"` triggers a traversal RuntimeException inside the loader. - 'scaffold' => ['manifest' => '../escape.json'], + 'copy' => ['.gitignore'], + 'modes' => ['.gitignore' => 'append'], ], ); - $root = $this->makeRootPackage(['php-forge/bad']); - $io = new BufferIO(); - $scaffolder = new Scaffolder( - new ManifestLoader(new ManifestSchema(), new ManifestExpander()), - new Applier(new PackageAllowlist(['php-forge/bad']), new PathValidator(), new Hasher(), $io), - new LockFile($builder->getProjectRoot()), - $io, + $builder->createStubFile('php-forge/test', '.gitignore', "*.log\n"); + + self::scaffold( + $builder, + ['php-forge/test'], + [$provider], ); - $scaffolder->scaffold($root, [$provider], $builder->getProjectRoot(), $builder->getVendorDir(), true); + unlink("{$builder->getProjectRoot()}/.gitignore"); - self::assertStringContainsString( - 'Failed to load manifest for "php-forge/bad"', - $io->getOutput(), - 'A manifest-loader exception must be caught and reported per-provider rather than aborting the entire run.', + self::scaffold( + $builder, + ['php-forge/test'], + [$provider], + ); + + FileAssert::contentSame( + "{$builder->getProjectRoot()}/.gitignore", + "*.log\n", + 'File must be back.', ); } - public function testFirstScaffoldPersistsProviderPathInLock(): void + /** + * Ensures ejected entries of every mode keep the user content and are never rehashed. + */ + public function ejectedEntriesAreNeverTouched(): void { $builder = new FakeProjectBuilder($this->tempDir); - $builder->createStubFile('php-forge/test', 'app.php', 'a'); + $root = $builder->getProjectRoot(); + + $lock = new LockFile($root); - $provider = $this->makeProviderPackage( + $provider = self::provider( 'php-forge/test', [ - 'scaffold' => [ - 'copy' => ['app.php'], - ], + 'copy' => ['replace.txt', '.gitignore', 'prepend.txt'], + 'modes' => ['.gitignore' => 'append', 'prepend.txt' => 'prepend'], ], ); - $root = $this->makeRootPackage(['php-forge/test']); - $this - ->makeScaffolder(['php-forge/test'], $builder) - ->scaffold($root, [$provider], $builder->getProjectRoot(), $builder->getVendorDir(), true); - $lockData = (new LockFile($builder->getProjectRoot()))->read(); + $edits = [ + 'replace.txt' => "mine\n", + '.gitignore' => "vendor/\n", + 'prepend.txt' => "code\n", + ]; - self::assertArrayHasKey( - 'php-forge/test', - $lockData['providers'], - 'Lock file must persist the provider entry after the first scaffold run.', + $builder->createStubFile('php-forge/test', 'replace.txt', "stub\n"); + $builder->createStubFile('php-forge/test', '.gitignore', "*.log\n"); + $builder->createStubFile('php-forge/test', 'prepend.txt', "// header\n"); + + self::scaffold( + $builder, + ['php-forge/test'], + [$provider], ); - $providerEntry = $lockData['providers']['php-forge/test'] ?? null; + $data = $lock->read(); - $expectedPath = str_replace('\\', '/', $builder->getVendorDir() . '/php-forge/test'); + foreach ($edits as $destination => $content) { + $builder->createProjectFile($destination, $content); - self::assertSame( - ['version' => '2.0.0', 'path' => $expectedPath], - $providerEntry, - 'Provider entry must record both version and path (absolute when vendor is outside the project root).', - ); - } + $data['files'][$destination]['ejected'] = true; + } - public function testFirstScaffoldRecordsRelativePathWhenProviderLivesInsideProject(): void - { - $builder = new FakeProjectBuilder($this->tempDir); + $lock->write($data); - $providerRootInsideProject = $builder->getProjectRoot() . '/vendor/php-forge/test'; + $lockBytes = file_get_contents($lock->getPath()); - mkdir($providerRootInsideProject, 0o777, recursive: true); - file_put_contents($providerRootInsideProject . '/app.php', 'a'); + self::scaffold( + $builder, + ['php-forge/test'], + [$provider], + ); - $provider = $this->makeProviderPackage( - 'php-forge/test', + Assert::same( [ - 'scaffold' => [ - 'copy' => ['app.php'], - ], + 'replace.txt' => file_get_contents("{$root}/replace.txt"), + '.gitignore' => file_get_contents("{$root}/.gitignore"), + 'prepend.txt' => file_get_contents("{$root}/prepend.txt"), ], + $edits, + 'Ejected files must keep the user content.', ); - $root = $this->makeRootPackage(['php-forge/test']); - $this - ->makeScaffolder(['php-forge/test'], $builder) - ->scaffold( - $root, - [$provider], - $builder->getProjectRoot(), - $builder->getVendorDir(), - true, - ['php-forge/test' => $providerRootInsideProject], - ); - - $lockData = (new LockFile($builder->getProjectRoot()))->read(); - - self::assertSame( - ['version' => '2.0.0', 'path' => 'vendor/php-forge/test'], - $lockData['providers']['php-forge/test'] ?? null, - 'When the provider install path is inside the project root, the lock must store a project-relative path.', + FileAssert::contentSame( + $lock->getPath(), + (string) $lockBytes, + 'Ejected entries must never be rehashed.', ); } - public function testLastProviderWinsForSameDestination(): void + /** + * Ensures the first run records the provider version and its absolute path outside the project root. + */ + public function firstScaffoldPersistsProviderPathInLock(): void { $builder = new FakeProjectBuilder($this->tempDir); - $builder->createStubFile('php-forge/base', 'app.php', 'base content'); - $builder->createStubFile('php-forge/override', 'app.php', 'override content'); + $builder->createStubFile('php-forge/test', 'app.php', 'a'); - $base = $this->makeProviderPackage( - 'php-forge/base', + self::scaffold( + $builder, + ['php-forge/test'], [ - 'scaffold' => [ - 'copy' => ['app.php'], - ], + self::provider( + 'php-forge/test', + ['copy' => ['app.php']] + ), ], ); - $override = $this->makeProviderPackage( - 'php-forge/override', + + Assert::same( + (new LockFile($builder->getProjectRoot()))->read()['providers'], [ - 'scaffold' => [ - 'copy' => ['app.php'], + 'php-forge/test' => [ + 'version' => '2.0.0', + 'path' => str_replace('\\', '/', "{$builder->getVendorDir()}/php-forge/test"), ], ], + 'Provider entry must record the version and the absolute path.', ); - $root = $this->makeRootPackage(['php-forge/base', 'php-forge/override']); - $this - ->makeScaffolder(['php-forge/base', 'php-forge/override'], $builder) - ->scaffold( - $root, - [$base, $override], - $builder->getProjectRoot(), - $builder->getVendorDir(), - true, - ); + } + + /** + * Ensures an install path inside the project root is recorded relative to it. + */ + public function firstScaffoldRecordsRelativePathWhenProviderLivesInsideProject(): void + { + $builder = new FakeProjectBuilder($this->tempDir); - self::assertSame( - 'override content', - file_get_contents($builder->getProjectRoot() . '/app.php'), - 'When multiple providers write to the same destination, the last provider in the list should win.', + $installPath = "{$builder->getProjectRoot()}/vendor/php-forge/test"; + + mkdir($installPath, 0o777, recursive: true); + file_put_contents( + "{$installPath}/app.php", + 'a', ); - $lockData = (new LockFile($builder->getProjectRoot()))->read(); + self::scaffold( + $builder, + ['php-forge/test'], + [self::provider('php-forge/test', ['copy' => ['app.php']])], + installPaths: ['php-forge/test' => $installPath], + ); - $appEntry = $lockData['files']['app.php'] ?? null; + Assert::same( + (new LockFile($builder->getProjectRoot()))->read()['providers']['php-forge/test'] ?? null, + ['version' => '2.0.0', 'path' => 'vendor/php-forge/test'], + "Path must be stored relative to the project root as 'vendor/php-forge/test'.", + ); + } + + /** + * Ensures the provider listed last in `allowed-packages` wins a shared destination, whatever the install order. + * + * @param list $allowed Root `allowed-packages`. + * @param string $winner Provider expected to write the destination. + * @param string $loser Provider expected to be overridden. + */ + #[DataProvider(ScaffolderProvider::class . '::allowedOrders')] + public function laterAllowedProviderWinsTheSharedDestination(array $allowed, string $winner, string $loser): void + { + $builder = new FakeProjectBuilder($this->tempDir); + $io = new BufferIO(); + + $builder->createStubFile('php-forge/base', 'app.php', 'php-forge/base'); + $builder->createStubFile('php-forge/override', 'app.php', 'php-forge/override'); - self::assertNotNull( - $appEntry, - "Lock must contain exactly one entry for 'app.php'.", + self::scaffold( + $builder, + $allowed, + [ + self::provider('php-forge/base', ['copy' => ['app.php']]), + self::provider('php-forge/override', ['copy' => ['app.php']]), + ], + $io, ); - self::assertCount( - 1, - array_filter(array_keys($lockData['files']), static fn(string $k): bool => $k === 'app.php'), - "Lock must contain exactly one entry for 'app.php'.", + + FileAssert::contentSame( + "{$builder->getProjectRoot()}/app.php", + $winner, + "Provider '{$winner}' must win.", ); - self::assertSame( - 'php-forge/override', - $appEntry['provider'], - "Lock entry for 'app.php' must be attributed to the last (winning) provider.", + Assert::same( + array_column((new LockFile($builder->getProjectRoot()))->read()['files'], 'provider'), + [$winner], + "Lock must hold one entry, attributed to '{$winner}'.", + ); + Assert::same( + $io->getOutput(), + ConsoleMessage::SCAFFOLD_OVERRIDE->getMessage('app.php', $winner, $loser) . PHP_EOL, + 'The collision must be reported once, naming both providers.', ); } - public function testLockFileRecordsCorrectHash(): void + /** + * Ensures the lock file is a reserved destination that a provider cannot overwrite. + */ + public function lockFileDestinationIsRejected(): void { $builder = new FakeProjectBuilder($this->tempDir); + $io = new BufferIO(); - $builder->createStubFile('php-forge/app-base-scaffold', 'nginx.conf', 'server {}'); + $builder->createStubFile('php-forge/test', 'evil.json', '{"providers": [], "files": []}'); + + self::scaffold( + $builder, + ['php-forge/test'], + [self::provider('php-forge/test', ['copy' => [['from' => 'evil.json', 'to' => 'scaffold-lock.json']]])], + $io, + ); - $provider = $this->makeProviderPackage( - 'php-forge/app-base-scaffold', + Assert::same( + $io->getOutput(), + ConsoleMessage::SCAFFOLD_APPLY_FAILED->getMessage( + 'scaffold-lock.json', + Message::PATH_RESERVED->getMessage('scaffold-lock.json'), + ) . PHP_EOL, + 'The reserved destination must be rejected.', + ); + Assert::same( + (new LockFile($builder->getProjectRoot()))->read(), [ - 'scaffold' => [ - 'copy' => ['nginx.conf'], + 'providers' => [ + 'php-forge/test' => [ + 'version' => '2.0.0', + 'path' => str_replace('\\', '/', "{$builder->getVendorDir()}/php-forge/test"), + ], ], + 'files' => [], ], + 'The lock file must be written by the plugin, not copied from the provider.', ); - $root = $this->makeRootPackage(['php-forge/app-base-scaffold']); - $this - ->makeScaffolder(['php-forge/app-base-scaffold'], $builder) - ->scaffold($root, [$provider], $builder->getProjectRoot(), $builder->getVendorDir(), true); + } - $lockFile = new LockFile($builder->getProjectRoot()); + /** + * Ensures a `merge` override of the manifest applies and is recorded in the lock entry. + */ + public function manifestMergeOverrideIsRecordedInLock(): void + { + $builder = new FakeProjectBuilder($this->tempDir); - $hash = $lockFile->getHashAtScaffold('nginx.conf'); + $builder->createStubFile('php-forge/test', '.gitignore', "# b\nx\n"); + $builder->createProjectFile('.gitignore', "# a\nx\n"); - self::assertNotNull( - $hash, - 'Lock file should contain a hash entry for the scaffolded file.', + self::scaffold( + $builder, + ['php-forge/test'], + [ + self::provider( + 'php-forge/test', + [ + 'copy' => ['.gitignore'], + 'modes' => ['.gitignore' => 'append'], + 'merge' => ['.gitignore' => 'text'], + ], + ), + ], ); - self::assertStringStartsWith( - 'sha256:', - $hash, - 'Hash should be prefixed with sha256:', + + FileAssert::contentSame( + "{$builder->getProjectRoot()}/.gitignore", + "# a\nx\n\n# b\n", + "Manifest 'text' strategy must apply.", ); - self::assertSame( - $hash, - (new Hasher())->hash($builder->getProjectRoot() . '/nginx.conf'), - 'Hash should match the computed hash of the scaffolded file.', + Assert::same( + self::lockEntry($builder, '.gitignore')['merge'] ?? null, + 'text', + 'Override must be recorded.', ); } - public function testLogsSkipMessageWhenRootPackageHasNoScaffoldExtra(): void + /** + * Ensures a metapackage provider, which has no install path, is skipped with a notice. + */ + public function metapackageProviderIsSkippedWithANotice(): void { $builder = new FakeProjectBuilder($this->tempDir); + $io = new BufferIO(); - $root = self::createStub(PackageInterface::class); - - $root->method('getExtra')->willReturn([]); - - $io = $this->createMock(IOInterface::class); + $provider = self::provider( + 'php-forge/meta', + ['copy' => ['app.php']], + ); - $io->expects(self::once()) - ->method('write') - ->with(self::stringContains('No extra.scaffold configuration')); + $builder->createStubFile('php-forge/meta', 'app.php', 'meta'); + $provider->setType('metapackage'); - (new Scaffolder( - new ManifestLoader(new ManifestSchema(), new ManifestExpander()), - new Applier(new PackageAllowlist([]), new PathValidator(), new Hasher(), new NullIO()), - new LockFile($builder->getProjectRoot()), + self::scaffold( + $builder, + ['php-forge/meta'], + [$provider], $io, - ))->scaffold($root, [], $builder->getProjectRoot(), $builder->getVendorDir(), true); + ); + + Assert::same( + $io->getOutput(), + ConsoleMessage::SCAFFOLD_PROVIDER_INSTALL_PATH_MISSING->getMessage('php-forge/meta') . PHP_EOL, + 'The skipped metapackage must be reported.', + ); + FileAssert::fileDoesNotExist( + "{$builder->getProjectRoot()}/app.php", + 'Nothing may be written.', + ); } - public function testManifestLoadFailureOnEarlierProviderDoesNotHaltLaterProviders(): void + /** + * Ensures an allowed but uninstalled provider is reported and the later providers still run. + */ + public function missingProviderPackageDoesNotHaltLaterProviders(): void { $builder = new FakeProjectBuilder($this->tempDir); + $io = new BufferIO(); $builder->createStubFile('php-forge/good', 'app.php', 'good-content'); - $bad = $this->makeProviderPackage( - 'php-forge/bad', - // `manifest: "../escape.json"` triggers a traversal RuntimeException inside the loader. - ['scaffold' => ['manifest' => '../escape.json']], - ); - $good = $this->makeProviderPackage( - 'php-forge/good', - [ - 'scaffold' => [ - 'copy' => ['app.php'], - ], - ], + self::scaffold( + $builder, + ['php-forge/missing', 'php-forge/good'], + [self::provider('php-forge/good', ['copy' => ['app.php']])], + $io, ); - // 'bad' is listed first so its manifest-load failure triggers the continue-branch before 'good' is processed. - $root = $this->makeRootPackage(['php-forge/bad', 'php-forge/good']); - $bufferIo = new BufferIO(); - $scaffolder = new Scaffolder( - new ManifestLoader(new ManifestSchema(), new ManifestExpander()), - new Applier( - new PackageAllowlist(['php-forge/bad', 'php-forge/good']), - new PathValidator(), - new Hasher(), - $bufferIo, - ), - new LockFile($builder->getProjectRoot()), - $bufferIo, + Assert::same( + $io->getOutput(), + ConsoleMessage::SCAFFOLD_PROVIDER_NOT_INSTALLED->getMessage('php-forge/missing') . PHP_EOL, + 'The uninstalled provider must be reported.', + ); + FileAssert::contentSame( + "{$builder->getProjectRoot()}/app.php", + 'good-content', + 'Later provider must run.', ); + } - $scaffolder->scaffold( - $root, - [$bad, $good], + /** + * Ensures a non-string `allowed-packages` entry is skipped and the later string entries still run. + */ + public function nonStringAllowedEntryIsSkippedWithoutHaltingLaterProviders(): void + { + $builder = new FakeProjectBuilder($this->tempDir); + $config = ProjectConfig::fromExtra(['scaffold' => ['allowed-packages' => [42, 'php-forge/good']]]); + + $builder->createStubFile('php-forge/good', 'app.php', 'good-content'); + + self::scaffolder($builder, $config, new BufferIO())->scaffold( + $config, + [self::provider('php-forge/good', ['copy' => ['app.php']])], $builder->getProjectRoot(), $builder->getVendorDir(), - true, ); - self::assertFileExists( - $builder->getProjectRoot() . '/app.php', - "When an earlier provider's manifest fails to load, the foreach must 'continue' so 'app.php' is still written.", - ); - self::assertSame( + FileAssert::contentSame( + "{$builder->getProjectRoot()}/app.php", 'good-content', - file_get_contents($builder->getProjectRoot() . '/app.php'), - "The later provider's stub must be applied after the earlier provider's manifest-load failure is logged.", + "'php-forge/good' must run.", + ); + } + + /** + * Pins the path prefix comparison, including the case-insensitive branch that only Windows paths reach. + */ + #[DataProvider(ScaffolderProvider::class . '::prefixMatches')] + public function prefixMatchesHonorsCaseInsensitiveFlag( + string $haystack, + string $needle, + bool $caseInsensitive, + bool $expected, + ): void { + Assert::same( + (new ReflectionMethod(ScaffoldRunner::class, 'prefixMatches')) + ->invoke(null, $haystack, $needle, $caseInsensitive), + $expected, + 'Prefix comparison must honor the case flag.', ); } - public function testMissingProviderPackageDoesNotHaltLaterProviders(): void + /** + * Ensures a preserve run keeps the recorded hash of an already tracked file that the user changed. + */ + public function preserveDoesNotOverwriteAlreadyTrackedLockEntry(): void { $builder = new FakeProjectBuilder($this->tempDir); - $builder->createStubFile('php-forge/good', 'app.php', 'good-content'); - - $good = $this->makeProviderPackage( - 'php-forge/good', - [ - 'scaffold' => [ - 'copy' => ['app.php'], - ], - ], + $provider = self::provider( + 'php-forge/test', + ['copy' => ['config.php'], 'modes' => ['config.php' => 'preserve']], ); - // 'missing' is allowed but not installed so its branch triggers the skip-message continue path. - $root = $this->makeRootPackage(['php-forge/missing', 'php-forge/good']); - $bufferIo = new BufferIO(); - $scaffolder = new Scaffolder( - new ManifestLoader(new ManifestSchema(), new ManifestExpander()), - new Applier( - new PackageAllowlist(['php-forge/missing', 'php-forge/good']), - new PathValidator(), - new Hasher(), - $bufferIo, - ), - new LockFile($builder->getProjectRoot()), - $bufferIo, + $builder->createStubFile('php-forge/test', 'config.php', 'stub'); + $builder->createProjectFile('config.php', 'user-content'); + + self::scaffold( + $builder, + ['php-forge/test'], + [$provider], ); - // Note: only 'good' is passed as installed; 'missing' is absent. - $scaffolder->scaffold($root, [$good], $builder->getProjectRoot(), $builder->getVendorDir(), true); + file_put_contents( + "{$builder->getProjectRoot()}/config.php", + 'user-modified', + ); - self::assertStringContainsString( - 'Provider "php-forge/missing" is not installed', - $bufferIo->getOutput(), - 'The uninstalled allowed-package must emit the skip message before the loop continues.', + self::scaffold( + $builder, + ['php-forge/test'], + [$provider], ); - self::assertFileExists( - $builder->getProjectRoot() . '/app.php', - "After the uninstalled-provider skip, the loop must 'continue' so 'app.php' is still written.", + + Assert::same( + self::lockEntry($builder, 'config.php')['hash'] ?? null, + 'sha256:' . hash('sha256', 'user-content'), + 'Recorded hash must stay the one of the first run.', ); } - public function testMultipleFilesFromSameProvider(): void + /** + * Ensures preserve mode keeps an untracked existing file and records its hash in a new lock. + */ + public function preserveRecordsExistingUntrackedFileInLock(): void { $builder = new FakeProjectBuilder($this->tempDir); - $builder->createStubFile('php-forge/test', 'a.php', 'a'); - $builder->createStubFile('php-forge/test', 'b.php', 'b'); + $path = "{$builder->getProjectRoot()}/config/params.php"; - $provider = $this->makeProviderPackage( - 'php-forge/test', + $builder->createStubFile('php-forge/test', 'config/params.php', 'stub content'); + $builder->createProjectFile('config/params.php', 'user content'); + + self::scaffold( + $builder, + ['php-forge/test'], [ - 'scaffold' => [ - 'copy' => [ - 'a.php', - 'b.php', - ], - ], + self::provider( + 'php-forge/test', + ['copy' => ['config/params.php'], 'modes' => ['config/params.php' => 'preserve']], + ), ], ); - $root = $this->makeRootPackage(['php-forge/test']); - $this - ->makeScaffolder(['php-forge/test'], $builder) - ->scaffold($root, [$provider], $builder->getProjectRoot(), $builder->getVendorDir(), true); - self::assertFileExists( - $builder->getProjectRoot() . '/a.php', - 'First scaffolded file should exist.', + FileAssert::contentSame( + $path, + 'user content', + 'Preserve file must not be overwritten.', ); - self::assertFileExists( - $builder->getProjectRoot() . '/b.php', - 'Second scaffolded file should exist.', + Assert::same( + self::lockEntry($builder, 'config/params.php')['hash'] ?? null, + Hasher::hash($path), + 'Recorded hash must match the untouched user content.', ); + } - $lockFile = new LockFile($builder->getProjectRoot()); + /** + * Ensures a provider that yields no file mappings is reported and no lock is written. + * + * @param array $extra Provider `extra` block. + * @param array $stubs Provider files keyed by path. + */ + #[DataProvider(ScaffolderProvider::class . '::providersWithoutMappings')] + public function providerWithoutMappingsWritesNoticeAndNoLock(array $extra, array $stubs): void + { + $builder = new FakeProjectBuilder($this->tempDir); + $io = new BufferIO(); + $provider = new CompletePackage('php-forge/empty', '2.0.0.0', '2.0.0'); + + foreach ($stubs as $path => $content) { + $builder->createStubFile('php-forge/empty', $path, $content); + } - self::assertNotNull( - $lockFile->getHashAtScaffold('a.php'), - 'Lock file should contain a hash entry for the first scaffolded file.', + $provider->setExtra($extra); + + self::scaffold( + $builder, + ['php-forge/empty'], + [$provider], + $io, ); - self::assertNotNull( - $lockFile->getHashAtScaffold('b.php'), - 'Lock file should contain a hash entry for the second scaffolded file.', + + Assert::same( + $io->getOutput(), + ConsoleMessage::SCAFFOLD_PROVIDER_MAPPINGS_EMPTY->getMessage('php-forge/empty') . PHP_EOL, + 'A provider yielding zero mappings must be reported.', + ); + FileAssert::fileDoesNotExist( + "{$builder->getProjectRoot()}/scaffold-lock.json", + 'No lock may be written.', ); } - public function testNonStringAllowedEntryIsSkippedWithoutHaltingLaterProviders(): void + /** + * Ensures replace mode writes a missing file and records its hash, provider, source, mode and stub hash. + */ + public function replaceFileIsWrittenAndRecordedWithItsHash(): void { $builder = new FakeProjectBuilder($this->tempDir); - $builder->createStubFile('php-forge/good', 'app.php', 'good-content'); + $hash = 'sha256:' . hash('sha256', 'server {}'); - $good = $this->makeProviderPackage( - 'php-forge/good', - [ - 'scaffold' => [ - 'copy' => ['app.php'], - ], - ], + $builder->createStubFile('php-forge/app-base-scaffold', 'config/nginx.conf', 'server {}'); + + self::scaffold( + $builder, + ['php-forge/app-base-scaffold'], + [self::provider('php-forge/app-base-scaffold', ['copy' => ['config/nginx.conf']])], ); - // First entry is a non-string int so '!is_string' triggers 'continue'; the string entry after must still run. - $root = self::createStub(PackageInterface::class); - $root->method('getExtra')->willReturn( + FileAssert::contentSame( + "{$builder->getProjectRoot()}/config/nginx.conf", + 'server {}', + 'File must be written.', + ); + Assert::same( + self::lockEntry($builder, 'config/nginx.conf'), [ - 'scaffold' => [ - 'allowed-packages' => [42, 'php-forge/good'], - ], + 'hash' => $hash, + 'provider' => 'php-forge/app-base-scaffold', + 'source' => 'config/nginx.conf', + 'mode' => 'replace', + 'stub-hash' => $hash, ], + 'Lock entry must record the written file.', ); + } - $bufferIo = new BufferIO(); - $scaffolder = new Scaffolder( - new ManifestLoader(new ManifestSchema(), new ManifestExpander()), - new Applier(new PackageAllowlist(['php-forge/good']), new PathValidator(), new Hasher(), $bufferIo), - new LockFile($builder->getProjectRoot()), - $bufferIo, - ); + /** + * Ensures replace mode overwrites a differing untracked file and reports it. + */ + public function replaceOverDifferingUntrackedFileWarns(): void + { + $builder = new FakeProjectBuilder($this->tempDir); + $io = new BufferIO(); + + $builder->createStubFile('php-forge/test', '.styleci.yml', "preset: psr12\n"); + $builder->createProjectFile('.styleci.yml', "preset: laravel\n"); - $scaffolder->scaffold($root, [$good], $builder->getProjectRoot(), $builder->getVendorDir(), true); + self::scaffold( + $builder, + ['php-forge/test'], + [self::provider('php-forge/test', ['copy' => ['.styleci.yml']])], + $io, + ); - self::assertFileExists( - $builder->getProjectRoot() . '/app.php', - "When the first allowed-packages entry is not a string, the loop must 'continue' so 'php-forge/good' runs.", + FileAssert::contentSame( + "{$builder->getProjectRoot()}/.styleci.yml", + "preset: psr12\n", + 'Provider must win on adoption.', + ); + Assert::same( + $io->getOutput(), + ConsoleMessage::SCAFFOLD_PREFIXED->getMessage( + ConsoleMessage::SCAFFOLD_UNTRACKED_OVERWRITTEN->getMessage('.styleci.yml'), + ) . PHP_EOL, + 'Overwrite must be reported.', ); } - public function testNoScaffoldExtraOnRootPackageIsNoop(): void + /** + * Ensures replace mode rewrites a tracked destination and its lock hash when the stub changes. + */ + public function replaceOverwritesLockEntryForPreviouslyTrackedDestination(): void { - $this->expectNotToPerformAssertions(); - $builder = new FakeProjectBuilder($this->tempDir); - $this - ->makeScaffolder([], $builder) - ->scaffold($this->makeRootPackage([]), [], $builder->getProjectRoot(), $builder->getVendorDir(), true); - } + $provider = self::provider( + 'php-forge/test', + ['copy' => ['app.php']], + ); - public function testPrefixMatchesHonorsCaseInsensitiveFlag(): void - { - $method = new ReflectionMethod(Scaffolder::class, 'prefixMatches'); + $builder->createStubFile('php-forge/test', 'app.php', 'v1'); - // Case-sensitive branch matches identical casing but rejects differing casing. - self::assertTrue( - (bool) $method->invoke(null, '/Project/vendor/foo', '/Project/', false), - 'Byte-exact comparison must accept an exact casing prefix.', + self::scaffold( + $builder, + ['php-forge/test'], + [$provider], ); - self::assertFalse( - (bool) $method->invoke(null, '/project/vendor/foo', '/Project/', false), - 'Byte-exact comparison must reject a prefix that only differs in casing.', + + $builder->createStubFile('php-forge/test', 'app.php', 'v2'); + + self::scaffold( + $builder, + ['php-forge/test'], + [$provider], ); - // Case-insensitive branch covers the NTFS/Windows path otherwise unreachable on Linux. - self::assertTrue( - (bool) $method->invoke(null, '/project/vendor/foo', '/Project/', true), - 'Case-insensitive comparison must accept a prefix that only differs in casing.', + FileAssert::contentSame( + "{$builder->getProjectRoot()}/app.php", + 'v2', + 'File must hold the new stub.', ); - self::assertFalse( - (bool) $method->invoke(null, '/elsewhere/vendor/foo', '/Project/', true), - 'Case-insensitive comparison must still reject a prefix that is genuinely different.', + Assert::same( + self::lockEntry($builder, 'app.php')['hash'] ?? null, + 'sha256:' . hash('sha256', 'v2'), + 'Lock hash must follow the rewritten file.', ); } - public function testPrependModeSkippedOnPartialRunWhenAlreadyInLock(): void + /** + * Ensures a root package without allowed providers writes only its notice and touches nothing. + * + * @param array $extra Root package `extra` block. + * @param string $notice Expected notice. + */ + #[DataProvider(ScaffolderProvider::class . '::rootsWithoutProviders')] + public function rootWithoutAllowedProvidersWritesOnlyTheNotice(array $extra, string $notice): void { $builder = new FakeProjectBuilder($this->tempDir); + $io = new BufferIO(); + $config = ProjectConfig::fromExtra($extra); - $builder->createStubFile('php-forge/test', 'prepend.txt', 'header'); - $builder->createProjectFile('prepend.txt', 'existing'); - - $provider = $this->makeProviderPackage( - 'php-forge/test', - [ - 'scaffold' => [ - 'copy' => ['prepend.txt'], - 'modes' => ['prepend.txt' => 'prepend'], - ], - ], - ); - - $root = $this->makeRootPackage(['php-forge/test']); - $scaffolder = $this->makeScaffolder(['php-forge/test'], $builder); - - // First run records a lock entry for the prepend mapping. - $scaffolder->scaffold($root, [$provider], $builder->getProjectRoot(), $builder->getVendorDir(), true); + // A lock tracking a file no provider ships would yield an orphan report if the run went on. + $lock = '{"providers": {}, "files": {"old.txt": {"hash": "sha256:x", "provider": "php-forge/gone", ' + . '"source": "old.txt", "mode": "replace"}}}'; - $afterFirst = file_get_contents($builder->getProjectRoot() . '/prepend.txt'); + $builder->createStubFile('php-forge/test', 'app.php', 'a'); + $builder->createProjectFile('scaffold-lock.json', $lock); - // ´artial run must leave the prepended file untouched because it already lives in the lock. - $scaffolder->scaffold($root, [$provider], $builder->getProjectRoot(), $builder->getVendorDir(), false); + self::scaffolder($builder, $config, $io)->scaffold( + $config, + [self::provider('php-forge/test', ['copy' => ['app.php']])], + $builder->getProjectRoot(), + $builder->getVendorDir(), + ); - self::assertSame( - $afterFirst, - file_get_contents($builder->getProjectRoot() . '/prepend.txt'), - 'Prepend mode must be skipped on partial runs when the destination is already recorded in the lock.', + Assert::same( + $io->getOutput(), + $notice . PHP_EOL, + 'Only the notice may be written.', + ); + FileAssert::fileDoesNotExist( + "{$builder->getProjectRoot()}/app.php", + 'No file may be written.', + ); + FileAssert::contentSame( + "{$builder->getProjectRoot()}/scaffold-lock.json", + $lock, + 'The lock must stay unchanged.', ); } - public function testPreserveDoesNotOverwriteAlreadyTrackedLockEntry(): void + /** + * Ensures a provider path change alone rewrites the lock with the fresh version and path. + */ + public function scaffoldPersistsUpdatedProviderPathWhenOnlyProviderChanged(): void { $builder = new FakeProjectBuilder($this->tempDir); $builder->createStubFile('php-forge/test', 'config.php', 'stub'); $builder->createProjectFile('config.php', 'user-content'); - $provider = $this->makeProviderPackage( - 'php-forge/test', + (new LockFile($builder->getProjectRoot()))->write( [ - 'scaffold' => [ - 'copy' => ['config.php'], - 'modes' => ['config.php' => 'preserve'], + 'providers' => ['php-forge/test' => ['path' => '/obsolete/path']], + 'files' => [ + 'config.php' => [ + 'hash' => 'sha256:' . hash('sha256', 'user-content'), + 'provider' => 'php-forge/test', + 'source' => 'config.php', + 'mode' => 'preserve', + ], ], ], ); - $root = $this->makeRootPackage(['php-forge/test']); - $scaffolder = $this->makeScaffolder(['php-forge/test'], $builder); - - // First run records the current hash in the lock. - $scaffolder->scaffold($root, [$provider], $builder->getProjectRoot(), $builder->getVendorDir(), true); - - $initialHash = (new LockFile($builder->getProjectRoot()))->getHashAtScaffold('config.php'); - // User modifies the file in place; a second preserve run must NOT overwrite the lock entry. - file_put_contents($builder->getProjectRoot() . '/config.php', 'user-modified'); - - $scaffolder->scaffold($root, [$provider], $builder->getProjectRoot(), $builder->getVendorDir(), true); + self::scaffold( + $builder, + ['php-forge/test'], + [self::provider('php-forge/test', ['copy' => ['config.php'], 'modes' => ['config.php' => 'preserve']])], + ); - self::assertSame( - $initialHash, - (new LockFile($builder->getProjectRoot()))->getHashAtScaffold('config.php'), - 'Preserve mode must not overwrite an already-tracked lock entry even when the on-disk file changes.', + Assert::same( + (new LockFile($builder->getProjectRoot()))->read()['providers'], + [ + 'php-forge/test' => [ + 'version' => '2.0.0', + 'path' => str_replace('\\', '/', "{$builder->getVendorDir()}/php-forge/test"), + ], + ], + 'The fresh version and path must be persisted.', ); } - public function testPreserveFileIsNotOverwritten(): void - { + /** + * Ensures a second run leaves a file that already holds the provider block unchanged. + * + * @param string $mode Merge mode of the file. + * @param string $stub Provider content. + * @param string $existing Project content before the first run. + * @param string $expected Content after the first run. + */ + #[DataProvider(ScaffolderProvider::class . '::mergedFiles')] + public function secondRunLeavesAMergedFileUnchanged( + string $mode, + string $stub, + string $existing, + string $expected, + ): void { $builder = new FakeProjectBuilder($this->tempDir); - $builder->createStubFile('php-forge/test', 'config/params.php', 'stub content'); - $builder->createProjectFile('config/params.php', 'user content'); - - $provider = $this->makeProviderPackage( + $provider = self::provider( 'php-forge/test', [ - 'scaffold' => [ - 'copy' => ['config/params.php'], - 'modes' => ['config/params.php' => 'preserve'], - ], + 'copy' => ['file.txt'], + 'modes' => ['file.txt' => $mode], ], ); - $root = $this->makeRootPackage(['php-forge/test']); - $this - ->makeScaffolder(['php-forge/test'], $builder) - ->scaffold($root, [$provider], $builder->getProjectRoot(), $builder->getVendorDir(), true); + $path = "{$builder->getProjectRoot()}/file.txt"; - self::assertSame( - 'user content', - file_get_contents($builder->getProjectRoot() . '/config/params.php'), - 'Preserve mode file should not be overwritten if it already exists.', - ); + $builder->createStubFile('php-forge/test', 'file.txt', $stub); + $builder->createProjectFile('file.txt', $existing); - $lockData = (new LockFile($builder->getProjectRoot()))->read(); + self::scaffold( + $builder, + ['php-forge/test'], + [$provider], + ); - $lockEntry = $lockData['files']['config/params.php'] ?? null; + $first = file_get_contents($path); - $userContentHash = (new Hasher())->hash($builder->getProjectRoot() . '/config/params.php'); + self::scaffold( + $builder, + ['php-forge/test'], + [$provider], + ); - if ($lockEntry !== null) { - self::assertSame( - $userContentHash, - $lockEntry['hash'], - 'If a lock entry exists for a preserved file, its hash must match the untouched user content.', - ); - } + Assert::same( + [$first, file_get_contents($path)], + [$expected, $expected], + "The '{$mode}' block must be added once.", + ); } - public function testPreserveRecordsExistingUntrackedFileInLock(): void + /** + * Ensures the stub hash is recorded for every mode, adoption is flagged, and a user-modified skip keeps it. + */ + public function stubHashIsRecordedPerMode(): void { $builder = new FakeProjectBuilder($this->tempDir); - $builder->createStubFile('php-forge/test', 'config.php', 'stub'); - $builder->createProjectFile('config.php', 'user-content'); + $modes = [ + '.gitignore' => 'append', + 'existing.txt' => 'preserve', + 'prepend.txt' => 'prepend', + 'preserve.txt' => 'preserve', + 'replace.txt' => 'replace', + ]; - $provider = $this->makeProviderPackage( + $provider = self::provider( 'php-forge/test', [ - 'scaffold' => [ - 'copy' => ['config.php'], - 'modes' => ['config.php' => 'preserve'], - ], + 'copy' => array_keys($modes), + 'modes' => $modes, ], ); - $root = $this->makeRootPackage(['php-forge/test']); - $this - ->makeScaffolder(['php-forge/test'], $builder) - ->scaffold($root, [$provider], $builder->getProjectRoot(), $builder->getVendorDir(), true); - self::assertFileExists( - $builder->getProjectRoot() . '/scaffold-lock.json', - 'Lock file must be written when preserve mode records an existing untracked file.', - ); - - $lockData = (new LockFile($builder->getProjectRoot()))->read(); - - self::assertArrayHasKey( - 'config.php', - $lockData['files'], - 'Preserve mode must record untracked existing files in the lock.', - ); + foreach (array_keys($modes) as $file) { + $builder->createStubFile('php-forge/test', $file, "{$file} v1\n"); + } - $entry = $lockData['files']['config.php'] ?? null; + $builder->createProjectFile('existing.txt', "mine\n"); - self::assertNotNull( - $entry, - 'Lock entry must exist for the preserved file.', - ); - self::assertSame( - (new Hasher())->hash($builder->getProjectRoot() . '/config.php'), - $entry['hash'], - 'Recorded hash must match the untouched user content.', + self::scaffold( + $builder, + ['php-forge/test'], + [$provider], ); - } - - public function testReplaceFileIsWrittenAndLockCreated(): void - { - $builder = new FakeProjectBuilder($this->tempDir); - $builder->createStubFile('php-forge/app-base-scaffold', 'config/params.php', 'getProjectRoot()))->read()['files']; - $provider = $this->makeProviderPackage( - 'php-forge/app-base-scaffold', + Assert::same( [ - 'scaffold' => [ - 'copy' => ['config/params.php'], + array_map(static fn(array $entry): mixed => $entry['stub-hash'] ?? null, $files), + array_keys(array_filter($files, static fn(array $entry): bool => isset($entry['adopted']))), + ], + [ + [ + '.gitignore' => self::stubHash($builder, '.gitignore'), + 'existing.txt' => self::stubHash($builder, 'existing.txt'), + 'prepend.txt' => self::stubHash($builder, 'prepend.txt'), + 'preserve.txt' => self::stubHash($builder, 'preserve.txt'), + 'replace.txt' => self::stubHash($builder, 'replace.txt'), ], + ['existing.txt'], ], + "Every file must record its stub hash and only 'existing.txt' must be adopted.", ); - $root = $this->makeRootPackage(['php-forge/app-base-scaffold']); - $this - ->makeScaffolder(['php-forge/app-base-scaffold'], $builder) - ->scaffold($root, [$provider], $builder->getProjectRoot(), $builder->getVendorDir(), true); - self::assertFileExists( - $builder->getProjectRoot() . '/config/params.php', - 'Replace mode file should be created if it does not exist.', + $v1Hash = self::stubHash( + $builder, + 'replace.txt', ); - self::assertFileExists( - $builder->getProjectRoot() . '/scaffold-lock.json', - 'Lock file should be created when replace mode file is written.', + + $builder->createProjectFile('replace.txt', "mine\n"); + $builder->createStubFile('php-forge/test', 'replace.txt', "replace.txt v2\n"); + + self::scaffold( + $builder, + ['php-forge/test'], + [$provider], + ); + + Assert::same( + self::lockEntry($builder, 'replace.txt')['stub-hash'] ?? null, + $v1Hash, + 'User-modified replace skip must keep the stub hash of the last apply.', ); } - public function testReplaceOverwritesLockEntryForPreviouslyTrackedDestination(): void + /** + * Ensures a file after a skipped append entry is still applied on a partial run. + */ + public function subsequentFileIsAppliedAfterASkippedEntry(): void { $builder = new FakeProjectBuilder($this->tempDir); - $builder->createStubFile('php-forge/test', 'app.php', 'v1'); - - $provider = $this->makeProviderPackage( + $provider = self::provider( 'php-forge/test', [ - 'scaffold' => [ - 'copy' => ['app.php'], - ], + 'copy' => ['append.txt', 'fresh.txt'], + 'modes' => ['append.txt' => 'append'], ], ); - $root = $this->makeRootPackage(['php-forge/test']); - $scaffolder = $this->makeScaffolder(['php-forge/test'], $builder); - $scaffolder->scaffold($root, [$provider], $builder->getProjectRoot(), $builder->getVendorDir(), true); - - $firstHash = (new LockFile($builder->getProjectRoot()))->getHashAtScaffold('app.php'); + $builder->createStubFile('php-forge/test', 'append.txt', 'appended'); + $builder->createStubFile('php-forge/test', 'fresh.txt', 'fresh content'); + $builder->createProjectFile('append.txt', 'existing'); - // Change the stub so the second run writes different content. - $builder->createStubFile('php-forge/test', 'app.php', 'v2'); - $scaffolder->scaffold($root, [$provider], $builder->getProjectRoot(), $builder->getVendorDir(), true); + self::scaffold( + $builder, + ['php-forge/test'], + [$provider], + ); - $secondHash = (new LockFile($builder->getProjectRoot()))->getHashAtScaffold('app.php'); + unlink("{$builder->getProjectRoot()}/fresh.txt"); - self::assertNotSame( - $firstHash, - $secondHash, - 'Lock entry must be overwritten when replace mode re-writes a previously tracked destination.', + self::scaffold( + $builder, + ['php-forge/test'], + [$provider], ); - self::assertSame( - (new Hasher())->hash($builder->getProjectRoot() . '/app.php'), - $secondHash, - 'Lock entry must match the hash of the newly written content.', + + FileAssert::contentSame( + "{$builder->getProjectRoot()}/fresh.txt", + 'fresh content', + 'The loop must continue after the skipped entry.', ); } - public function testScaffoldPersistsUpdatedProviderPathWhenOnlyProviderChanged(): void + /** + * Ensures a manifest failure is written and counted as an error before the exception. + */ + public function throwScaffoldExceptionAfterReportingManifestFailure(): void { $builder = new FakeProjectBuilder($this->tempDir); + $io = new BufferIO(); + $summary = new ScaffoldSummary(); - $builder->createStubFile('php-forge/test', 'config.php', 'stub'); - $builder->createProjectFile('config.php', 'user-content'); - - $userHash = (new Hasher())->hash($builder->getProjectRoot() . '/config.php'); - - // Pre-populate the lock with an outdated provider path; only the provider-path branch must mark '$dirty = true'. - (new LockFile($builder->getProjectRoot()))->write( - [ - 'providers' => [ - 'php-forge/test' => ['path' => '/obsolete/path'], - ], - 'files' => [ - 'config.php' => [ - 'hash' => $userHash, - 'provider' => 'php-forge/test', - 'source' => 'config.php', - 'mode' => 'preserve', - ], - ], - ], + $scaffolder = self::scaffolder( + $builder, + self::config(['php-forge/bad']), + $io, + $summary, ); - $provider = $this->makeProviderPackage( - 'php-forge/test', - [ - 'scaffold' => [ - 'copy' => ['config.php'], - 'modes' => ['config.php' => 'preserve'], - ], - ], + $expected = Message::SCAFFOLD_MANIFEST_LOAD_FAILED->getMessage( + 'php-forge/bad', + Message::MANIFEST_REFERENCE_NOT_RELATIVE->getMessage('php-forge/bad'), ); - $root = $this->makeRootPackage(['php-forge/test']); - $this - ->makeScaffolder(['php-forge/test'], $builder) - ->scaffold($root, [$provider], $builder->getProjectRoot(), $builder->getVendorDir(), true); - - $lockData = (new LockFile($builder->getProjectRoot()))->read(); - - $providerEntry = $lockData['providers']['php-forge/test'] ?? null; - $expectedPath = str_replace('\\', '/', $builder->getVendorDir() . '/php-forge/test'); + $exception = self::catchScaffoldException( + static fn() => $scaffolder->scaffold( + self::config(['php-forge/bad']), + [self::provider('php-forge/bad', ['manifest' => '../escape.json'])], + $builder->getProjectRoot(), + $builder->getVendorDir(), + ), + ); - self::assertSame( - ['version' => '2.0.0', 'path' => $expectedPath], - $providerEntry, - 'Provider-entry updates alone must mark the lock dirty so the fresh {version, path} is persisted to disk.', + Assert::same( + [$exception?->getMessage(), $io->getOutput(), $summary->errors], + [$expected, $expected . PHP_EOL, 1], + "Failure must be thrown, written once and counted as '1' error.", ); } - public function testSubsequentFileAppliedAfterFirstEntryIsSkipped(): void + /** + * Ensures a manifest failure of any allowed provider aborts the run before any file or lock change. + */ + public function throwScaffoldExceptionWhenManifestFailsBeforeAnyFileIsApplied(): void { $builder = new FakeProjectBuilder($this->tempDir); - $builder->createStubFile('php-forge/test', 'append.txt', 'appended'); - $builder->createStubFile('php-forge/test', 'fresh.txt', 'fresh content'); - $builder->createProjectFile('append.txt', 'existing'); + $builder->createStubFile('php-forge/good', 'app.php', 'good'); + $builder->createProjectFile( + 'scaffold-lock.json', + '{"providers": {"php-forge/bad": {"version": "1.0.0", "path": "../vendor/php-forge/bad"}}, "files": {}}', + ); - $provider = $this->makeProviderPackage( - 'php-forge/test', - [ - 'scaffold' => [ - 'copy' => [ - 'append.txt', - 'fresh.txt', - ], - 'modes' => ['append.txt' => 'append'], + $exception = self::catchScaffoldException( + static fn() => self::scaffold( + $builder, + ['php-forge/good', 'php-forge/bad'], + [ + self::provider('php-forge/bad', ['manifest' => 'missing.json']), + self::provider('php-forge/good', ['copy' => ['app.php']]), ], - ], + ), ); - $root = $this->makeRootPackage(['php-forge/test']); - $scaffolder = $this->makeScaffolder(['php-forge/test'], $builder); - - // First full run records both entries in the lock. - $scaffolder->scaffold($root, [$provider], $builder->getProjectRoot(), $builder->getVendorDir(), true); - // Delete `fresh.txt` so the second run must re-create it even though `append.txt` is locked and skipped first. - unlink($builder->getProjectRoot() . '/fresh.txt'); - - // Partial run: 'append.txt' is skipped (continue), but the loop must continue to process fresh.txt. - $scaffolder->scaffold($root, [$provider], $builder->getProjectRoot(), $builder->getVendorDir(), false); - - self::assertFileExists( - $builder->getProjectRoot() . '/fresh.txt', - 'A file following a skipped append entry must still be applied (loop continues, not breaks).', + Assert::same( + $exception?->getMessage(), + Message::SCAFFOLD_MANIFEST_LOAD_FAILED->getMessage( + 'php-forge/bad', + Message::MANIFEST_PROVIDER_FILE_NOT_FOUND->getMessage( + 'php-forge/bad', + 'manifest file', + "{$builder->getVendorDir()}/php-forge/bad/missing.json", + ), + ), + 'Exception must name the provider.', + ); + FileAssert::fileDoesNotExist( + "{$builder->getProjectRoot()}/app.php", + 'No provider may be applied.', + ); + Assert::same( + (new LockFile($builder->getProjectRoot()))->read()['providers'], + ['php-forge/bad' => ['version' => '1.0.0', 'path' => '../vendor/php-forge/bad']], + 'Lock must stay untouched.', ); } - protected function setUp(): void + /** + * Runs `$run` and returns the {@see ScaffoldException} it throws, or `null`. + * + * @param Closure(): void $run Code expected to throw. + */ + private static function catchScaffoldException(Closure $run): ScaffoldException|null { - $this->setUpTempDirectory(); + try { + $run(); + } catch (ScaffoldException $e) { + return $e; + } + + return null; } - protected function tearDown(): void + /** + * Returns the configuration of a root package whose `allowed-packages` is `$allowed`. + * + * @param list $allowed Allowed provider names. + */ + private static function config(array $allowed): ProjectConfig { - $this->tearDownTempDirectory(); + return ProjectConfig::fromExtra(['scaffold' => ['allowed-packages' => $allowed]]); } /** - * @param array $extra + * Returns the lock entry of `$destination` in the project of `$builder`, or an empty array. + * + * @return array */ - private function makeProviderPackage(string $name, array $extra, string $version = '2.0.0'): PackageInterface + private static function lockEntry(FakeProjectBuilder $builder, string $destination): array { - $pkg = self::createStub(PackageInterface::class); - - $pkg->method('getName')->willReturn($name); - $pkg->method('getExtra')->willReturn($extra); - $pkg->method('getPrettyVersion')->willReturn($version); - - return $pkg; + return (new LockFile($builder->getProjectRoot()))->read()['files'][$destination] ?? []; } /** - * @param list $allowedPackages + * Returns the provider package `$name` at version `2.0.0` with `$manifest` as its `extra.scaffold`. + * + * @param array $manifest Raw `extra.scaffold` of the provider. */ - private function makeRootPackage(array $allowedPackages): PackageInterface + private static function provider(string $name, array $manifest): CompletePackage { - $pkg = self::createStub(PackageInterface::class); + $package = new CompletePackage($name, '2.0.0.0', '2.0.0'); - $pkg - ->method('getExtra') - ->willReturn( - $allowedPackages !== [] - ? ['scaffold' => ['allowed-packages' => $allowedPackages]] - : [], - ); + $package->setExtra(['scaffold' => $manifest]); - return $pkg; + return $package; } /** - * @param list $allowedPackages + * Scaffolds `$packages` into the project of `$builder` for a root package that allows `$allowed`. + * + * @param list $allowed Allowed provider names. + * @param list $packages Installed packages. + * @param BufferIO $io IO of the run. + * @param array $installPaths Install paths keyed by package name. */ - private function makeScaffolder(array $allowedPackages, FakeProjectBuilder $builder): Scaffolder - { + private static function scaffold( + FakeProjectBuilder $builder, + array $allowed, + array $packages, + BufferIO $io = new BufferIO(), + array $installPaths = [], + ): void { + $config = self::config($allowed); + + self::scaffolder($builder, $config, $io)->scaffold( + $config, + $packages, + $builder->getProjectRoot(), + $builder->getVendorDir(), + $installPaths, + ); + } + + /** + * Returns a scaffolder for the project of `$builder` whose applier authorizes the providers of `$config`. + */ + private static function scaffolder( + FakeProjectBuilder $builder, + ProjectConfig $config, + BufferIO $io, + ScaffoldSummary $summary = new ScaffoldSummary(), + ): Scaffolder { return new Scaffolder( new ManifestLoader(new ManifestSchema(), new ManifestExpander()), - new Applier( - new PackageAllowlist($allowedPackages), - new PathValidator(), - new Hasher(), - new NullIO(), - ), + new FileApplier($config, new PathValidator(), new ComposerIoWriter($io)), new LockFile($builder->getProjectRoot()), - new NullIO(), + new ComposerIoWriter($io), + $summary, ); } + + /** + * Returns the `sha256:` hash of a stub file of `php-forge/test`. + */ + private static function stubHash(FakeProjectBuilder $builder, string $relative): string + { + return Hasher::hash("{$builder->getVendorDir()}/php-forge/test/{$relative}"); + } } diff --git a/tests/Manifest/DefaultExcludesTest.php b/tests/Manifest/DefaultExcludesTest.php index ac791b9..3937402 100644 --- a/tests/Manifest/DefaultExcludesTest.php +++ b/tests/Manifest/DefaultExcludesTest.php @@ -4,62 +4,68 @@ namespace PHPForge\Scaffold\Tests\Manifest; -use PHPForge\Scaffold\Manifest\DefaultExcludes; +use PHPForge\Scaffold\Manifest\{DefaultExcludes, Glob}; use PHPForge\Scaffold\Tests\Provider\DefaultExcludesProvider; -use PHPUnit\Framework\Attributes\DataProviderExternal; -use PHPUnit\Framework\Attributes\Group; -use PHPUnit\Framework\TestCase; +use Testo\Assert; +use Testo\Codecov\Covers; +use Testo\Data\DataProvider; +use Testo\Test; /** * Unit tests for {@see DefaultExcludes} built-in exclusion patterns. * * {@see DefaultExcludesProvider} for test case data providers. */ -#[Group('scaffold')] -#[Group('manifest')] -final class DefaultExcludesTest extends TestCase +#[Test] +#[Covers(DefaultExcludes::class)] +#[Covers(Glob::class)] +final class DefaultExcludesTest { - #[DataProviderExternal(DefaultExcludesProvider::class, 'excludedPaths')] - public function testExcludedPathMatchesDefaultExcludes(string $path): void + /** + * Ensures tooling, metadata and artefact paths match at least one default-exclude pattern. + */ + #[DataProvider(DefaultExcludesProvider::class . '::excludedPaths')] + public function excludedPathMatchesTheDefaultExcludes(string $path): void { - self::assertTrue( - DefaultExcludes::matches($path), - "'{$path}' must match at least one default-exclude pattern.", + Assert::true( + Glob::matchesAny(DefaultExcludes::PATTERNS, $path), + "'{$path}' must match a default-exclude pattern.", ); } - #[DataProviderExternal(DefaultExcludesProvider::class, 'includedPaths')] - public function testIncludedPathDoesNotMatchDefaultExcludes(string $path): void + /** + * Ensures project content matches no default-exclude pattern. + */ + #[DataProvider(DefaultExcludesProvider::class . '::includedPaths')] + public function includedPathDoesNotMatchTheDefaultExcludes(string $path): void { - self::assertFalse( - DefaultExcludes::matches($path), - "'{$path}' is project content and must not match any default-exclude pattern.", + Assert::false( + Glob::matchesAny(DefaultExcludes::PATTERNS, $path), + "'{$path}' must not match a default-exclude pattern.", ); } - #[DataProviderExternal(DefaultExcludesProvider::class, 'nonPrunableDirectories')] - public function testNonPrunableDirectoryIsNotMatchedByMatchesDirectory(string $relativeDir): void + /** + * Ensures a directory without a default `/**` pattern is not pruned. + */ + #[DataProvider(DefaultExcludesProvider::class . '::nonPrunableDirectories')] + public function nonPrunableDirectoryIsNotPruned(string $directory): void { - self::assertFalse( - DefaultExcludes::matchesDirectory($relativeDir), - "'{$relativeDir}' must not be prunable: no default pattern '{$relativeDir}/**' excludes every descendant.", + Assert::false( + Glob::prunes(DefaultExcludes::PATTERNS, $directory), + "'{$directory}' must not be prunable.", ); } - public function testPatternsArrayIsNotEmpty(): void + /** + * Ensures a directory with a default `/**` pattern is pruned. + */ + #[DataProvider(DefaultExcludesProvider::class . '::prunableDirectories')] + public function prunableDirectoryIsPruned(string $directory): void { - self::assertNotEmpty( - DefaultExcludes::PATTERNS, - 'DefaultExcludes::PATTERNS must declare at least one default-exclude pattern.', - ); - } - - #[DataProviderExternal(DefaultExcludesProvider::class, 'prunableDirectories')] - public function testPrunableDirectoryIsMatchedByMatchesDirectory(string $relativeDir): void - { - self::assertTrue( - DefaultExcludes::matchesDirectory($relativeDir), - "'{$relativeDir}' must be prunable: pattern '{$relativeDir}/**' excludes every descendant.", + Assert::true( + Glob::prunes(DefaultExcludes::PATTERNS, $directory), + "'{$directory}' must be prunable.", ); } } diff --git a/tests/Manifest/FileMappingTest.php b/tests/Manifest/FileMappingTest.php index 936ff66..5224837 100644 --- a/tests/Manifest/FileMappingTest.php +++ b/tests/Manifest/FileMappingTest.php @@ -6,114 +6,59 @@ use Error; use PHPForge\Scaffold\Manifest\{FileMapping, FileMode}; -use PHPUnit\Framework\Attributes\Group; -use PHPUnit\Framework\TestCase; use ReflectionProperty; +use Testo\Assert; +use Testo\Codecov\Covers; +use Testo\Expect; +use Testo\Test; + +use function get_object_vars; /** - * Unit tests for {@see FileMapping} value object construction and property access. + * Unit tests for {@see FileMapping} value object construction and immutability. */ -#[Group('scaffold')] -#[Group('manifest')] -final class FileMappingTest extends TestCase +#[Test] +#[Covers(FileMapping::class)] +final class FileMappingTest { - public function testConstructorAssignsDestination(): void - { - $mapping = new FileMapping( - 'config/params.php', - 'stubs/params.php', - FileMode::Preserve, - 'vendor/pkg', - '/path', - ); - - self::assertSame( - 'config/params.php', - $mapping->destination, - 'Constructor should assign the destination property correctly.', - ); - } - - public function testConstructorAssignsMode(): void - { - $mapping = new FileMapping( - 'config/params.php', - 'stubs/params.php', - FileMode::Replace, - 'vendor/pkg', - '/path', - ); - - self::assertSame( - FileMode::Replace, - $mapping->mode, - 'Constructor should assign the mode property correctly.', - ); - } - - public function testConstructorAssignsProviderName(): void - { - $mapping = new FileMapping( - 'config/params.php', - 'stubs/params.php', - FileMode::Preserve, - 'php-forge/nginx-scaffold', - '/path', - ); - - self::assertSame( - 'php-forge/nginx-scaffold', - $mapping->providerName, - 'Constructor should assign the providerName property correctly.', - ); - } - - public function testConstructorAssignsProviderPath(): void - { - $mapping = new FileMapping( - 'config/params.php', - 'stubs/params.php', - FileMode::Preserve, - 'vendor/pkg', - '/vendor/php-forge/nginx-scaffold', - ); - - self::assertSame( - '/vendor/php-forge/nginx-scaffold', - $mapping->providerPath, - 'Constructor should assign the providerPath property correctly.', - ); - } - - public function testConstructorAssignsSource(): void + /** + * Ensures the constructor assigns every property and defaults the merge strategy to `null`. + */ + public function constructorAssignsEveryProperty(): void { - $mapping = new FileMapping( - 'config/params.php', - 'stubs/params.php', - FileMode::Preserve, - 'vendor/pkg', - '/path', - ); - - self::assertSame( - 'stubs/params.php', - $mapping->source, - 'Constructor should assign the source property correctly.', + Assert::same( + get_object_vars( + new FileMapping( + 'config/params.php', + 'stubs/params.php', + FileMode::Preserve, + 'php-forge/nginx-scaffold', + '/vendor/php-forge/nginx-scaffold', + ), + ), + [ + 'destination' => 'config/params.php', + 'source' => 'stubs/params.php', + 'mode' => FileMode::Preserve, + 'providerName' => 'php-forge/nginx-scaffold', + 'providerPath' => '/vendor/php-forge/nginx-scaffold', + 'mergeStrategy' => null, + ], + "Properties must hold the constructor arguments and a 'null' merge strategy.", ); } - public function testPropertiesAreReadonly(): void + /** + * Ensures a property cannot be modified after construction. + */ + public function throwErrorWhenAPropertyIsModified(): void { - $mapping = new FileMapping( - 'config/params.php', - 'stubs/params.php', - FileMode::Preserve, - 'vendor/pkg', - '/path', - ); + $mapping = new FileMapping('config/params.php', 'stubs/params.php', FileMode::Preserve, 'vendor/pkg', '/path'); - $this->expectException(Error::class); + Expect::exception(Error::class) + ->withMessage('Cannot modify readonly property ' . FileMapping::class . '::$destination'); - (new ReflectionProperty(FileMapping::class, 'destination'))->setValue($mapping, 'other.php'); + (new ReflectionProperty(FileMapping::class, 'destination')) + ->setValue($mapping, 'other.php'); } } diff --git a/tests/Manifest/GlobTest.php b/tests/Manifest/GlobTest.php index a2e8a77..bd87b9b 100644 --- a/tests/Manifest/GlobTest.php +++ b/tests/Manifest/GlobTest.php @@ -5,108 +5,63 @@ namespace PHPForge\Scaffold\Tests\Manifest; use PHPForge\Scaffold\Manifest\Glob; -use PHPUnit\Framework\Attributes\Group; -use PHPUnit\Framework\TestCase; +use PHPForge\Scaffold\Merge\MergeStrategyKind; +use PHPForge\Scaffold\Tests\Provider\GlobProvider; +use Testo\Assert; +use Testo\Codecov\Covers; +use Testo\Data\DataProvider; +use Testo\Test; /** - * Unit tests for {@see Glob} pattern-to-regex conversion and matching semantics. + * Unit tests for {@see Glob} pattern-to-regex conversion, matching semantics and map lookup. + * + * {@see GlobProvider} for test case data providers. */ -#[Group('scaffold')] -#[Group('manifest')] -final class GlobTest extends TestCase +#[Test] +#[Covers(Glob::class)] +final class GlobTest { - public function testDoubleStarCrossesDirectorySeparators(): void - { - self::assertTrue( - Glob::matches('public/**', 'public/assets/css/app.css'), - "'**' must match deep nested paths across '/' separators.", - ); - } - - public function testDoubleStarPrefixMatchesRootFile(): void - { - self::assertTrue( - Glob::matches('**/.gitignore', '.gitignore'), - "'**/.gitignore' must match a root-level '.gitignore' because '**' can expand to empty.", - ); - } - - public function testDoubleStarSlashMatchesDeeplyNestedPath(): void - { - self::assertTrue( - Glob::matches('**/foo', 'a/b/c/foo'), - "'**/foo' must match arbitrarily deep nested paths.", - ); - } - - public function testExactPathMatchesItself(): void - { - self::assertTrue( - Glob::matches('config/params.php', 'config/params.php'), - 'Literal patterns must match themselves byte-exact.', - ); - } - - public function testExactPathRejectsDifferentFile(): void - { - self::assertFalse( - Glob::matches('config/params.php', 'config/web.php'), - 'Literal patterns must not match a different file name.', - ); - } - - public function testQuestionMarkMatchesSingleNonSeparatorChar(): void - { - self::assertTrue( - Glob::matches('yii?', 'yii0'), - "'?' must match a single non-separator character.", - ); - self::assertFalse( - Glob::matches('yii?', 'yii/0'), - "'?' must not match the path separator.", - ); - } - - public function testSingleStarDoesNotCrossDirectorySeparator(): void - { - self::assertFalse( - Glob::matches('config/*.php', 'config/nested/params.php'), - "A single '*' must not match across '/' separators.", - ); - } - - public function testSingleStarMatchesSameLevel(): void - { - self::assertTrue( - Glob::matches('config/*.php', 'config/params.php'), - "'*.php' must match any file with '.php' extension at the same directory level.", - ); - } - - public function testToRegexAnchorsTheFullPath(): void - { - self::assertSame( - '#^config/[^/]*\.php$#', - Glob::toRegex('config/*.php'), - "'toRegex' must produce an anchored regex matching the full string.", + /** + * Ensures a lookup prefers an exact key, then the first matching glob, and yields `null` without a match. + * + * @param array $map Values keyed by glob pattern. + */ + #[DataProvider(GlobProvider::class . '::lookups')] + public function lookupReturnsTheValueOfTheWinningPattern( + array $map, + string $path, + MergeStrategyKind|null $expected, + ): void { + Assert::same( + Glob::lookup($map, $path), + $expected, + "Lookup of '{$path}' must yield the value of the winning pattern.", ); } - public function testToRegexEscapesPunctuation(): void + /** + * Ensures a pattern matches a path exactly when the glob semantics say so. + */ + #[DataProvider(GlobProvider::class . '::matches')] + public function matchesFollowsTheGlobSemantics(string $pattern, string $path, bool $expected): void { - self::assertSame( - '#^file\.with\.dots$#', - Glob::toRegex('file.with.dots'), - "Literal '.' characters must be escaped in the produced regex.", + Assert::same( + Glob::matches($pattern, $path), + $expected, + "Match of '{$pattern}' against '{$path}' must be '" . ($expected ? 'true' : 'false') . "'.", ); } - public function testToRegexTreatsDoubleStarSlashAsOptionalDirectoryChain(): void + /** + * Ensures a pattern compiles to the expected anchored regex. + */ + #[DataProvider(GlobProvider::class . '::regexes')] + public function toRegexCompilesTheAnchoredRegex(string $pattern, string $expected): void { - self::assertSame( - '#^(?:.*/)?foo$#', - Glob::toRegex('**/foo'), - "'**/' must compile to '(?:.*/)?' so the match succeeds with zero or more directory levels.", + Assert::same( + Glob::toRegex($pattern), + $expected, + "Regex of '{$pattern}' must match.", ); } } diff --git a/tests/Manifest/ManifestExpanderTest.php b/tests/Manifest/ManifestExpanderTest.php index 1f88f1d..9b9e220 100644 --- a/tests/Manifest/ManifestExpanderTest.php +++ b/tests/Manifest/ManifestExpanderTest.php @@ -4,586 +4,209 @@ namespace PHPForge\Scaffold\Tests\Manifest; +use PHPForge\Scaffold\Exception\Message; use PHPForge\Scaffold\Manifest\{FileMapping, FileMode, ManifestExpander}; +use PHPForge\Scaffold\Merge\MergeStrategyKind; +use PHPForge\Scaffold\Tests\Provider\ManifestExpanderProvider; use PHPForge\Scaffold\Tests\Support\TempDirectoryTrait; -use PHPUnit\Framework\Attributes\Group; -use PHPUnit\Framework\TestCase; use RuntimeException; - +use Testo\Assert; +use Testo\Codecov\Covers; +use Testo\Core\Exception\SkipTest; +use Testo\Data\{DataProvider, DataSet}; +use Testo\Expect; +use Testo\Test; + +use function array_column; +use function array_map; use function chmod; +use function dirname; use function file_put_contents; use function function_exists; +use function is_string; use function posix_geteuid; /** - * Unit tests for {@see ManifestExpander} covering directory walking, exclusions, and mode resolution. + * Unit tests for {@see ManifestExpander} covering directory walking, exclusions, deduplication, and mode and merge + * strategy resolution. + * + * {@see ManifestExpanderProvider} for test case data providers. */ -#[Group('scaffold')] -#[Group('manifest')] -final class ManifestExpanderTest extends TestCase +#[Test] +#[Covers(ManifestExpander::class)] +final class ManifestExpanderTest { use TempDirectoryTrait; - public function testExpandAppliesDefaultExcludesDuringDirectoryWalk(): void - { - $this->seedFile('src/controllers/SiteController.php'); - $this->seedFile('src/tests/SomeTest.php'); - $this->seedFile('composer.json'); - $this->seedFile('runtime/cache/x.log'); - - $mappings = $this->expand( - [ - 'copy' => ['.'], - 'exclude' => [], - 'modes' => [], - ], - ); - - self::assertContains( - 'src/controllers/SiteController.php', - $this->destinations($mappings), - "Walking '.' must emit the controller file as a destination.", - ); - self::assertNotContains( - 'composer.json', - $this->destinations($mappings), - "Default excludes must hide 'composer.json' when '.' is walked.", - ); - self::assertNotContains( - 'runtime/cache/x.log', - $this->destinations($mappings), - "Default excludes must hide 'runtime/**' contents when the directory is walked.", - ); - } - - public function testExpandAppliesFromToRemapForDirectoryEntry(): void - { - $this->seedFile('metadata/.github/linters/actionlint.yml'); - $this->seedFile('metadata/.github/linters/.markdown-lint.yml'); - - $mappings = $this->expand( - [ - 'copy' => [['from' => 'metadata/.github', 'to' => '.github']], - 'exclude' => [], - 'modes' => [], - ], - ); - - $pairs = array_map( - static fn(FileMapping $mapping): array => [ - 'source' => $mapping->source, - 'destination' => $mapping->destination, - ], - $mappings, - ); - - self::assertSame( - [ - ['source' => 'metadata/.github/linters/.markdown-lint.yml', 'destination' => '.github/linters/.markdown-lint.yml'], - ['source' => 'metadata/.github/linters/actionlint.yml', 'destination' => '.github/linters/actionlint.yml'], - ], - $pairs, - "Directory '{from, to}' entries must rewrite the source prefix to the destination prefix on each walked file.", - ); - } - - public function testExpandAppliesFromToRemapForFileEntry(): void + /** + * Ensures each mapping carries the provider name and path, the default mode and no merge strategy. + */ + public function expandsIntoMappingsOfTheProvider(): void { - $this->seedFile('metadata/.editorconfig'); + $this->seed(['src/Bar.php', 'src/Foo.php']); - $mappings = $this->expand( + Assert::equals( + $this->expand(['src'], [], providerName: 'pkg/example'), [ - 'copy' => [['from' => 'metadata/.editorconfig', 'to' => '.editorconfig']], - 'exclude' => [], - 'modes' => [], + new FileMapping('src/Bar.php', 'src/Bar.php', FileMode::Replace, 'pkg/example', $this->tempDir), + new FileMapping('src/Foo.php', 'src/Foo.php', FileMode::Replace, 'pkg/example', $this->tempDir), ], - ); - - $pairs = array_map( - static fn(FileMapping $mapping): array => [ - 'source' => $mapping->source, - 'destination' => $mapping->destination, - ], - $mappings, - ); - - self::assertSame( - [['source' => 'metadata/.editorconfig', 'destination' => '.editorconfig']], - $pairs, - "File '{from, to}' entries must remap the destination while preserving the provider-relative source.", + "Mappings must belong to 'pkg/example'.", ); } - public function testExpandAppliesUserExcludesOnTopOfDefaults(): void + /** + * Ensures each file is mapped once, in entry order, after the default and manifest excludes. + * + * @param list $seeds Files seeded under the provider root. + * @param list $copy Manifest `copy` entries. + * @param list $exclude Manifest `exclude` patterns. + * @param array $expected Sources keyed by destination, in mapping order. + */ + #[DataProvider(ManifestExpanderProvider::class . '::copyLists')] + public function expandsTheCopyEntries(array $seeds, array $copy, array $exclude, array $expected): void { - $this->seedFile('src/controllers/SiteController.php'); - $this->seedFile('src/controllers/Disabled.php'); - - $mappings = $this->expand( - [ - 'copy' => ['src'], - 'exclude' => ['src/controllers/Disabled.php'], - 'modes' => [], - ], - ); + $this->seed($seeds); - self::assertSame( - ['src/controllers/SiteController.php'], - $this->destinations($mappings), - "User-declared 'exclude[]' patterns must filter walked paths.", + Assert::same( + array_column($this->expand($copy, $exclude), 'source', 'destination'), + $expected, + 'Sources keyed by destination must match.', ); } - public function testExpandAttributesEveryMappingToTheProviderName(): void + /** + * Ensures a `/**` exclude prunes the directory before the walk descends into it. + * + * @param list $exclude Manifest `exclude` patterns. + */ + #[DataSet(['vendor', []], 'default exclude')] + #[DataSet(['secrets', ['secrets/**']], 'user exclude')] + public function prunesExcludedDirectoriesBeforeDescent(string $directory, array $exclude): void { - $this->seedFile('src/Foo.php'); - - $mappings = $this->expand( - [ - 'copy' => ['src'], - 'exclude' => [], - 'modes' => [], - ], - providerName: 'pkg/example', - ); - - self::assertNotEmpty( - $mappings, - 'Seed fixture must produce at least one mapping.', - ); - - foreach ($mappings as $mapping) { - self::assertSame( - 'pkg/example', - $mapping->providerName, - 'Every FileMapping must carry the provider name for lock-file provenance.', + if (PHP_OS_FAMILY === 'Windows') { + throw new SkipTest( + 'chmod mode bits are not enforced on Windows.', ); } - } - public function testExpandContinuesToNextCopyEntryAfterDeduplicatingRepeatedFile(): void - { - $this->seedFile('yii'); - $this->seedFile('other.txt'); - - $mappings = $this->expand( - [ - 'copy' => ['yii', 'yii', 'other.txt'], - 'exclude' => [], - 'modes' => [], - ], - ); - - self::assertContains( - 'other.txt', - $this->destinations($mappings), - "After a duplicate file entry hits the dedup branch, the outer loop must 'continue' to process subsequent entries.", - ); - } - - public function testExpandContinuesToNextCopyEntryAfterWalkingDirectory(): void - { - $this->seedFile('dir1/a.txt'); - $this->seedFile('dir2/b.txt'); - - $mappings = $this->expand( - [ - 'copy' => ['dir1', 'dir2'], - 'exclude' => [], - 'modes' => [], - ], - ); - - self::assertContains( - 'dir2/b.txt', - $this->destinations($mappings), - "After walking the first directory, the outer loop must 'continue' so the next entry is walked too.", - ); - } - - public function testExpandDedupContinueDoesNotBreakDirectoryWalk(): void - { - // Pre-adding 'a.php' as an explicit entry seeds the dedup map so the walk must 'continue' onto 'b.php' / 'c.php'. - $this->seedFile('a.php'); - $this->seedFile('b.php'); - $this->seedFile('c.php'); - - $mappings = $this->expand( - [ - 'copy' => ['a.php', '.'], - 'exclude' => [], - 'modes' => [], - ], - ); - $destinations = $this->destinations($mappings); - - self::assertContains( - 'b.php', - $destinations, - "After 'a.php' hits the dedup branch, the walk must 'continue' so 'b.php' still lands in the output.", - ); - self::assertContains( - 'c.php', - $destinations, - "After 'a.php' hits the dedup branch, the walk must 'continue' so 'c.php' still lands in the output.", - ); - } - - public function testExpandDeduplicatesWhenFileIsReachableByBothFileAndDirectoryEntries(): void - { - $this->seedFile('yii'); - - $mappings = $this->expand( - [ - 'copy' => ['yii', '.'], - 'exclude' => [], - 'modes' => [], - ], - ); - - $destinations = $this->destinations($mappings); - - self::assertSame( - 1, - array_count_values($destinations)['yii'] ?? 0, - 'A destination reachable from both an explicit file entry and a directory walk must appear only once.', - ); - } - - public function testExpandEmitsEntriesForEachFileInsideCopyDirectory(): void - { - $this->seedFile('src/controllers/SiteController.php'); - $this->seedFile('src/models/User.php'); - - $mappings = $this->expand( - [ - 'copy' => ['src'], - 'exclude' => [], - 'modes' => [], - ], - ); - - self::assertSame( - ['src/controllers/SiteController.php', 'src/models/User.php'], - $this->destinations($mappings), - "Walking 'src' must emit every file beneath it as a destination.", - ); - } - - public function testExpandNormalisesTrailingSeparatorInCopyDirectoryEntry(): void - { - $this->seedFile('src/controllers/SiteController.php'); - - $mappings = $this->expand( - [ - 'copy' => ['src/'], - 'exclude' => [], - 'modes' => [], - ], - ); - - self::assertSame( - ['src/controllers/SiteController.php'], - $this->destinations($mappings), - "A trailing '/' on a 'copy' directory entry must produce the same destinations as the un-slashed form.", - ); - } - - public function testExpandPrunesDefaultExcludedDirectoriesWithoutDescendingIntoThem(): void - { - // Descent-pruning proof requires POSIX mode bits to be honoured: 'chmod 0' on 'vendor' must deny 'opendir()' - // so the walk only completes when the recursive filter rejects descent BEFORE reading the subtree. - $this->skipUnlessChmodDeniesDirectoryReads(); - $this->seedFile('src/main.php'); - $this->seedFile('vendor/pkg/bogus.php'); - - chmod("{$this->tempDir}/vendor", 0); - - try { - $mappings = $this->expand( - [ - 'copy' => ['.'], - 'exclude' => [], - 'modes' => [], - ], + if (function_exists('posix_geteuid') && posix_geteuid() === 0) { + throw new SkipTest( + 'Running as root bypasses chmod mode bits.', ); - } finally { - chmod("{$this->tempDir}/vendor", 0o755); } - self::assertSame( - ['src/main.php'], - $this->destinations($mappings), - "Default-excluded directories must be pruned BEFORE descent; otherwise an unreadable 'vendor/' would derail it.", - ); - } - - public function testExpandPrunesUserExcludedDirectoriesWithoutDescendingIntoThem(): void - { - // Requires POSIX mode bits: Windows and root ignore 'chmod 0', which would reduce the test to file-level exclusion. - $this->skipUnlessChmodDeniesDirectoryReads(); - $this->seedFile('src/main.php'); - $this->seedFile('secrets/keys.txt'); + // 'chmod 0' denies 'opendir()', so the walk completes only when the directory is pruned before it is read. + $this->seed(['src/main.php', "{$directory}/pkg/bogus.php"]); - chmod("{$this->tempDir}/secrets", 0); + chmod("{$this->tempDir}/{$directory}", 0); try { - $mappings = $this->expand( - [ - 'copy' => ['.'], - 'exclude' => ['secrets/**'], - 'modes' => [], - ], - ); + $mappings = $this->expand(['.'], $exclude); } finally { - chmod("{$this->tempDir}/secrets", 0o755); + chmod("{$this->tempDir}/{$directory}", 0o755); } - self::assertSame( + Assert::same( + array_column($mappings, 'destination'), ['src/main.php'], - $this->destinations($mappings), - "User-exclude patterns 'X/**' must prune directories BEFORE descent; otherwise unreadable subtrees derail the walk.", - ); - } - - public function testExpandResolvesExactMatchInModesAndShortCircuitsGlobLoop(): void - { - // Declaration order is deliberate: the glob is declared BEFORE the exact path to exercise the 'isset' short-circuit. - $this->seedFile('config/params.php'); - - $mappings = $this->expand( - [ - 'copy' => ['config/params.php'], - 'exclude' => [], - 'modes' => [ - 'config/*.php' => FileMode::Preserve, - 'config/params.php' => FileMode::Replace, - ], - ], - ); - - self::assertSame( - FileMode::Replace, - $mappings[0]->mode ?? null, - "Exact path match must win over a preceding-but-also-matching glob via the 'isset' early return.", - ); - } - - public function testExpandResolvesModesByExactPathThenByGlobThenDefaultsToReplace(): void - { - $this->seedFile('config/web.php'); - $this->seedFile('config/params.php'); - $this->seedFile('src/controllers/SiteController.php'); - - $mappings = $this->expand( - [ - 'copy' => [ - 'config', - 'src', - ], - 'exclude' => [], - 'modes' => [ - 'config/params.php' => FileMode::Preserve, - 'config/*.php' => FileMode::Append, - ], - ], - ); - - $modesByDestination = []; - - foreach ($mappings as $mapping) { - $modesByDestination[$mapping->destination] = $mapping->mode; - } - - self::assertSame( - FileMode::Preserve, - $modesByDestination['config/params.php'] ?? null, - 'Exact path match must win over a glob pattern that would also match.', - ); - self::assertSame( - FileMode::Append, - $modesByDestination['config/web.php'] ?? null, - "Glob 'config/*.php' must resolve 'config/web.php' after the exact-path lookup misses.", - ); - self::assertSame( - FileMode::Replace, - $modesByDestination['src/controllers/SiteController.php'] ?? null, - "A destination with no match in 'modes{}' must default to 'FileMode::Replace'.", + "Directory '{$directory}' must be pruned before descent.", ); } - public function testExpandReturnsWalkResultsInAlphabeticallySortedOrder(): void - { - // Seed in reverse-alphabetic order so the dirent order cannot accidentally match the expected sorted output. - $this->seedFile('zzz.php'); - $this->seedFile('mmm.php'); - $this->seedFile('aaa.php'); - - $mappings = $this->expand( - [ - 'copy' => ['.'], - 'exclude' => [], - 'modes' => [], - ], - ); - - $rawOrder = array_map(static fn(FileMapping $mapping): string => $mapping->destination, $mappings); - - self::assertSame( - ['aaa.php', 'mmm.php', 'zzz.php'], - $rawOrder, - "Walk results must be sorted alphabetically so 'scaffold-lock.json' stays deterministic across filesystems.", - ); - } - - public function testExpandSkipsExcludedFilesAndContinuesToRemainingEntries(): void - { - $this->seedFile('src/drop.txt'); - $this->seedFile('src/keep.txt'); - - $mappings = $this->expand( - [ - 'copy' => ['src'], - 'exclude' => ['src/drop.txt'], - 'modes' => [], - ], - ); - - self::assertSame( - ['src/keep.txt'], - $this->destinations($mappings), - "After an excluded file hits the skip branch, the walk must 'continue' so remaining files still process.", - ); - } - - public function testExpandThrowsWhenCopyEntryDoesNotExistOnDisk(): void - { - $this->expectException(RuntimeException::class); - $this->expectExceptionMessage('does not exist'); - - $this->expand( - [ - 'copy' => ['missing-dir'], - 'exclude' => [], - 'modes' => [], - ], - ); - } + /** + * Ensures the mode and the merge strategy prefer an exact path, then the first matching glob, then the default. + * + * @param list $seeds Files seeded under the provider root. + * @param list $copy Manifest `copy` entries. + * @param array $modes Manifest `modes` map. + * @param array $merge Manifest `merge` map. + * @param array{mode: array, merge: array} $expected Mode and + * merge strategy keyed by destination. + */ + #[DataProvider(ManifestExpanderProvider::class . '::attributes')] + public function resolvesTheModeAndMergeStrategyOfEachDestination( + array $seeds, + array $copy, + array $modes, + array $merge, + array $expected, + ): void { + $this->seed($seeds); - public function testExpandTreatsExplicitFileInCopyAsPassthroughBypassingDefaultExcludes(): void - { - $this->seedFile('runtime/.gitignore'); + $mappings = $this->expand($copy, [], $modes, $merge); - $mappings = $this->expand( + Assert::same( [ - 'copy' => ['runtime/.gitignore'], - 'exclude' => [], - 'modes' => [], + 'mode' => array_column($mappings, 'mode', 'destination'), + 'merge' => array_column($mappings, 'mergeStrategy', 'destination'), ], - ); - - self::assertSame( - ['runtime/.gitignore'], - $this->destinations($mappings), - 'An explicit file entry under a default-excluded directory must still ship; explicit entries bypass excludes.', + $expected, + 'Mode and merge strategy keyed by destination must match.', ); } - public function testExpandUserExcludeGlobMatchesMultipleFiles(): void - { - $this->seedFile('src/a.txt'); - $this->seedFile('src/b.txt'); - $this->seedFile('src/c.php'); - - $mappings = $this->expand( - [ - 'copy' => ['src'], - 'exclude' => ['src/*.txt'], - 'modes' => [], - ], - ); - - self::assertSame( - ['src/c.php'], - $this->destinations($mappings), - 'User exclude globs must filter by pattern, not just literal path.', - ); - } - - protected function setUp(): void - { - $this->setUpTempDirectory(); - } - - protected function tearDown(): void - { - $this->tearDownTempDirectory(); - } - /** - * Extracts the destination paths from a list of file mappings. - * - * @param list $mappings - * - * @return list + * Ensures a `copy` entry missing on disk is rejected. */ - private function destinations(array $mappings): array + public function throwRuntimeExceptionWhenCopyEntryDoesNotExist(): void { - $destinations = array_map(static fn(FileMapping $mapping): string => $mapping->destination, $mappings); - - sort($destinations); + Expect::exception(RuntimeException::class) + ->withMessage(Message::MANIFEST_COPY_ENTRY_NOT_FOUND->getMessage('missing-dir', $this->tempDir)); - return $destinations; + $this->expand(['missing-dir'], []); } /** - * Invokes {@see ManifestExpander::expand()} against the test's temp directory. + * Expands a manifest against the temp directory, normalising string `copy` entries to the `{from, to}` form. * - * Accepts the legacy string form (`'copy' => ['src']`) and normalises it to the typed `{from, to}` form expected - * by the expander, so existing tests do not need to be rewritten when only a single path is being declared. + * @param list $copy Manifest `copy` entries. + * @param list $exclude Manifest `exclude` patterns. + * @param array $modes Manifest `modes` map. + * @param array $merge Manifest `merge` map. * - * @param array{copy: list, exclude: list, modes: array} $manifest - * - * @return list + * @return list Expanded mappings. */ - private function expand(array $manifest, string $providerName = 'pkg/test'): array - { - $manifest['copy'] = array_map( - static fn(mixed $entry): array => is_string($entry) ? ['from' => $entry, 'to' => $entry] : $entry, - $manifest['copy'], + private function expand( + array $copy, + array $exclude, + array $modes = [], + array $merge = [], + string $providerName = 'pkg/test', + ): array { + return (new ManifestExpander())->expand( + [ + 'copy' => array_map( + static fn(string|array $entry): array => is_string($entry) + ? ['from' => $entry, 'to' => $entry] + : $entry, + $copy, + ), + 'exclude' => $exclude, + 'modes' => $modes, + 'merge' => $merge, + ], + $this->tempDir, + $providerName, ); - - /** @var array{copy: list, exclude: list, modes: array} $manifest */ - return (new ManifestExpander())->expand($manifest, $this->tempDir, $providerName); } /** - * Writes an empty file at `$relative` under the temp directory, creating intermediate directories as needed. - */ - private function seedFile(string $relative): void - { - $absolute = "{$this->tempDir}/{$relative}"; - - $this->ensureTestDirectory(dirname($absolute)); - - file_put_contents($absolute, ''); - } - - /** - * Skips the current test when the platform or user cannot make `chmod(dir, 0)` deny directory reads. + * Writes empty files at the given paths under the temp directory, creating intermediate directories as needed. * - * Windows ignores POSIX mode bits entirely, and the root user bypasses them, so a `chmod 0` guard degrades to a - * no-op in either environment; the tests that rely on it for descent-prevention proof cannot produce a signal - * there and must be skipped rather than silently pass. + * @param list $relatives Paths relative to the temp directory. */ - private function skipUnlessChmodDeniesDirectoryReads(): void + private function seed(array $relatives): void { - if (PHP_OS_FAMILY === 'Windows') { - self::markTestSkipped('chmod mode bits are not enforced on Windows.'); - } + foreach ($relatives as $relative) { + $absolute = "{$this->tempDir}/{$relative}"; - if (function_exists('posix_geteuid') && posix_geteuid() === 0) { - self::markTestSkipped('Running as root bypasses chmod mode bits.'); + $this->ensureTestDirectory(dirname($absolute)); + + file_put_contents( + $absolute, + '', + ); } } } diff --git a/tests/Manifest/ManifestLoaderTest.php b/tests/Manifest/ManifestLoaderTest.php index 42cac86..d45da4b 100644 --- a/tests/Manifest/ManifestLoaderTest.php +++ b/tests/Manifest/ManifestLoaderTest.php @@ -4,383 +4,261 @@ namespace PHPForge\Scaffold\Tests\Manifest; -use Composer\Package\PackageInterface; -use JsonException; -use PHPForge\Scaffold\Manifest\{FileMode, ManifestExpander, ManifestLoader, ManifestSchema}; +use Exception; +use PHPForge\Scaffold\Exception\Message; +use PHPForge\Scaffold\Manifest\{FileMapping, FileMode, ManifestExpander, ManifestLoader, ManifestSchema}; +use PHPForge\Scaffold\Tests\Provider\ManifestLoaderProvider; use PHPForge\Scaffold\Tests\Support\TempDirectoryTrait; -use PHPUnit\Framework\Attributes\Group; -use PHPUnit\Framework\TestCase; use RuntimeException; -use Xepozz\InternalMocker\MockerState; +use Testo\Assert; +use Testo\Codecov\Covers; +use Testo\Data\{DataProvider, DataSet}; +use Testo\Expect; +use Testo\Test; +use function dirname; use function file_put_contents; -use function json_encode; /** - * Unit tests for {@see ManifestLoader} inline and external manifest loading with the `copy`/`exclude`/`modes` schema. + * Unit tests for {@see ManifestLoader} reading the inline or external provider manifest, from the `extra` section or + * from the provider `composer.json`, and expanding it into file mappings. + * + * {@see ManifestLoaderProvider} for test case data providers. */ -#[Group('scaffold')] -#[Group('manifest')] -final class ManifestLoaderTest extends TestCase +#[Test] +#[Covers(ManifestLoader::class)] +final class ManifestLoaderTest { use TempDirectoryTrait; - public function testLoadAcceptsExternalManifestPathContainingColonInNonLeadingPosition(): void + /** + * Ensures an external manifest named in `composer.json` next to consumer keys is read from the provider root. + */ + public function expandsTheExternalManifestOfComposerJson(): void { - // Pins the '^' anchor in '/^[A-Za-z]:/': non-leading colons (stream wrappers, namespaces) must not be rejected. - $manifest = ['copy' => ['src']]; - - $this->seedFile('src/Foo.php'); - $this->ensureTestDirectory("{$this->tempDir}/subdir"); - - file_put_contents("{$this->tempDir}/subdir/a:b.json", (string) json_encode($manifest)); - - $package = self::createStub(PackageInterface::class); - - $package->method('getExtra')->willReturn(['scaffold' => ['manifest' => 'subdir/a:b.json']]); - $package->method('getName')->willReturn('pkg/example'); + // Shape of 'php-forge/coding-standard': a provider that is also a consumer of 'php-forge/baseline'. + $this->seed('src/Foo.php'); + $this->seed('stubs/ecs.php'); + $this->seed('config/params.php'); + $this->seed('config/web.php'); + $this->seed( + 'composer.json', + '{"extra": {"scaffold": {"manifest": "scaffold.json", "allowed-packages": ["php-forge/baseline"]}}}', + ); + $this->seed( + 'scaffold.json', + '{"copy": ["src", {"from": "stubs/ecs.php", "to": "ecs.php"}, "config"], "exclude": ["config/web.php"], ' + . '"modes": {"config/*.php": "preserve", "ecs.php": "append"}}', + ); - $result = $this->loader()->load($package, $this->tempDir); + $provider = 'php-forge/coding-standard'; - self::assertCount( - 1, - $result, - "A manifest path whose non-leading segment contains '[A-Za-z]:' must load; the drive-letter check fires only on leading.", + Assert::equals( + $this->loader()->loadFromPath($provider, $this->tempDir), + [ + $this->mapping('src/Foo.php', 'src/Foo.php', FileMode::Replace, $provider), + $this->mapping('ecs.php', 'stubs/ecs.php', FileMode::Append, $provider), + $this->mapping('config/params.php', 'config/params.php', FileMode::Preserve, $provider), + ], + "Every key of the external manifest must apply to the mappings of 'php-forge/coding-standard'.", ); } - public function testLoadExpandsInlineManifest(): void + /** + * Ensures an inline manifest is expanded even when the block also carries the consumer keys. + */ + public function expandsTheInlineManifestNextToConsumerKeys(): void { - $this->seedFile('src/Foo.php'); - $this->seedFile('config/params.php'); - - $package = self::createStub(PackageInterface::class); + $this->seed('src/Foo.php'); + $this->seed('config/params.php'); - $package - ->method('getExtra') - ->willReturn( + Assert::equals( + $this->loader()->loadFromExtra( [ 'scaffold' => [ 'copy' => ['src', 'config'], 'modes' => ['config/*.php' => 'preserve'], + 'allowed-packages' => ['php-forge/baseline'], + 'auto' => false, ], ], - ); - $package->method('getName')->willReturn('pkg/example'); - - $result = $this->loader()->load($package, $this->tempDir); - - self::assertCount( - 2, - $result, - 'Inline manifest must produce one FileMapping per expanded file.', - ); - - $modes = []; - - foreach ($result as $mapping) { - $modes[$mapping->destination] = $mapping->mode; - - self::assertSame( 'pkg/example', - $mapping->providerName, - 'Every FileMapping must be attributed to the provider name.', - ); - } - - self::assertSame( - FileMode::Preserve, - $modes['config/params.php'] ?? null, - "'config/*.php' glob must resolve to FileMode::Preserve.", - ); - self::assertSame( - FileMode::Replace, - $modes['src/Foo.php'] ?? null, - 'Files with no matching mode must default to FileMode::Replace.', - ); - } - - public function testLoadExternalManifestPreservesEveryDeclaredKey(): void - { - $this->seedFile('src/Foo.php'); - $this->seedFile('config/params.php'); - $this->seedFile('config/web.php'); - - $manifest = [ - 'copy' => ['src', 'config'], - 'exclude' => ['config/secrets.php'], - 'modes' => ['config/*.php' => 'preserve'], - ]; - - file_put_contents("{$this->tempDir}/scaffold.json", (string) json_encode($manifest)); - - $package = self::createStub(PackageInterface::class); - - $package - ->method('getExtra') - ->willReturn(['scaffold' => ['manifest' => 'scaffold.json']]); - $package->method('getName')->willReturn('pkg/example'); - - $result = $this->loader()->load($package, $this->tempDir); - - $destinations = []; - - foreach ($result as $mapping) { - $destinations[$mapping->destination] = $mapping->mode; - } - - self::assertArrayHasKey( - 'src/Foo.php', - $destinations, - "The 'src' copy root must survive decoding; losing the second copy entry would hide this destination.", - ); - self::assertArrayHasKey( - 'config/params.php', - $destinations, - "The 'config' copy root must survive decoding; it is declared as the second entry of 'copy[]'.", - ); - self::assertSame( - FileMode::Preserve, - $destinations['config/params.php'] ?? null, - "The 'modes{}' key must survive decoding so the glob applies the expected mode.", + $this->tempDir, + ), + [ + $this->mapping('src/Foo.php', 'src/Foo.php', FileMode::Replace, 'pkg/example'), + $this->mapping('config/params.php', 'config/params.php', FileMode::Preserve, 'pkg/example'), + ], + 'Inline manifest must expand into one mapping per file of the provider.', ); } - public function testLoadReadsExternalManifestRelativeToProviderRoot(): void - { - $this->seedFile('src/Foo.php'); - - $manifest = ['copy' => ['src']]; - - file_put_contents("{$this->tempDir}/scaffold.json", (string) json_encode($manifest)); - - $package = self::createStub(PackageInterface::class); - - $package - ->method('getExtra') - ->willReturn(['scaffold' => ['manifest' => 'scaffold.json']]); - $package->method('getName')->willReturn('pkg/example'); - - $result = $this->loader()->load($package, $this->tempDir); - - self::assertCount( - 1, - $result, - 'External manifest must produce mappings identical to an equivalent inline declaration.', - ); - } - - public function testLoadReturnsEmptyWhenExtraDoesNotDeclareScaffold(): void + /** + * Ensures a manifest reference with a colon past the drive-letter position is a relative path. + */ + public function externalManifestPathMayHoldAColonPastTheDriveLetter(): void { - $package = self::createStub(PackageInterface::class); + $this->seed('src/Foo.php'); + $this->seed('subdir/a:b.json', '{"copy": ["src"]}'); - $package->method('getExtra')->willReturn([]); - - self::assertSame( - [], - $this->loader()->load($package, $this->tempDir), - 'Absence of the "scaffold" key must produce no mappings.', + Assert::equals( + $this->loader()->loadFromExtra( + ['scaffold' => ['manifest' => 'subdir/a:b.json']], + 'pkg/example', + $this->tempDir, + ), + [$this->mapping('src/Foo.php', 'src/Foo.php', FileMode::Replace, 'pkg/example')], + "Manifest 'subdir/a:b.json' must be read.", ); } - public function testLoadReturnsEmptyWhenScaffoldIsNotArray(): void + /** + * Ensures a provider `composer.json` without a `scaffold` object yields no mappings. + */ + #[DataSet(['{}'], 'no extra')] + #[DataSet(['{"extra": "text"}'], 'extra not an object')] + #[DataSet(['{"extra": {"scaffold": "invalid"}}'], 'scaffold not an object')] + public function loadFromPathYieldsNothingWithoutAScaffoldObject(string $composerJson): void { - $package = self::createStub(PackageInterface::class); + $this->seed('composer.json', $composerJson); - $package->method('getExtra')->willReturn(['scaffold' => 'invalid']); - - self::assertSame( + Assert::same( + $this->loader()->loadFromPath('p/a', $this->tempDir), [], - $this->loader()->load($package, $this->tempDir), - 'Non-array "scaffold" value must produce no mappings.', + "Package without a 'scaffold' object must yield no mappings.", ); } - public function testLoadThrowsWhenExternalManifestCannotBeRead(): void - { - // Forces 'file_get_contents' to 'false' to cover the race where 'is_file()' succeeds but reading then fails. - $manifestPath = "{$this->tempDir}/scaffold.json"; - - file_put_contents($manifestPath, '{}'); - - MockerState::addCondition( - 'PHPForge\\Scaffold\\Manifest', - 'file_get_contents', - [$manifestPath, false, null, 0, null], - false, - ); - - $package = self::createStub(PackageInterface::class); - - $package->method('getExtra')->willReturn(['scaffold' => ['manifest' => 'scaffold.json']]); - $package->method('getName')->willReturn('pkg/unreadable'); - - $this->expectException(RuntimeException::class); - $this->expectExceptionMessage('could not read manifest file'); - - $this->loader()->load($package, $this->tempDir); - } - - public function testLoadThrowsWhenExternalManifestDecodesToNonObject(): void - { - file_put_contents("{$this->tempDir}/scaffold.json", '"just-a-string"'); - - $package = self::createStub(PackageInterface::class); - - $package->method('getExtra')->willReturn(['scaffold' => ['manifest' => 'scaffold.json']]); - $package->method('getName')->willReturn('pkg/bad'); - - $this->expectException(RuntimeException::class); - $this->expectExceptionMessage('decode to an object'); - - $this->loader()->load($package, $this->tempDir); - } - - public function testLoadThrowsWhenExternalManifestFileIsMissing(): void - { - $package = self::createStub(PackageInterface::class); - - $package->method('getExtra')->willReturn(['scaffold' => ['manifest' => 'missing.json']]); - $package->method('getName')->willReturn('pkg/bad'); - - $this->expectException(RuntimeException::class); - $this->expectExceptionMessage('manifest file not found'); - - $this->loader()->load($package, $this->tempDir); - } - - public function testLoadThrowsWhenExternalManifestJsonIsInvalid(): void - { - file_put_contents("{$this->tempDir}/scaffold.json", '{ not valid json '); - - $package = self::createStub(PackageInterface::class); - - $package->method('getExtra')->willReturn(['scaffold' => ['manifest' => 'scaffold.json']]); - $package->method('getName')->willReturn('pkg/bad'); - - $this->expectException(JsonException::class); - - $this->loader()->load($package, $this->tempDir); - } - - public function testLoadThrowsWhenExternalManifestPathContainsTraversal(): void + /** + * Ensures an empty, non-string, absolute or traversing manifest reference is rejected. + */ + #[DataProvider(ManifestLoaderProvider::class . '::invalidReferences')] + public function throwRuntimeExceptionForInvalidReference(mixed $reference, Message $message): void { - $package = self::createStub(PackageInterface::class); - - $package->method('getExtra')->willReturn(['scaffold' => ['manifest' => '../escape.json']]); - $package->method('getName')->willReturn('pkg/bad'); - - $this->expectException(RuntimeException::class); - $this->expectExceptionMessage('relative path'); + Expect::exception(RuntimeException::class) + ->withMessage( + $message->getMessage('pkg/bad'), + ); - $this->loader()->load($package, $this->tempDir); + $this + ->loader() + ->loadFromExtra(['scaffold' => ['manifest' => $reference]], 'pkg/bad', $this->tempDir); } - public function testLoadThrowsWhenExternalManifestPathIsAbsolute(): void + /** + * Ensures an external manifest body may not carry the consumer keys of the inline block. + */ + public function throwRuntimeExceptionWhenExternalManifestDeclaresConsumerKey(): void { - $package = self::createStub(PackageInterface::class); + $this->seed('scaffold.json', '{"copy": ["src"], "allowed-packages": ["a/b"]}'); - $package->method('getExtra')->willReturn(['scaffold' => ['manifest' => '/etc/malicious.json']]); - $package->method('getName')->willReturn('pkg/bad'); + Expect::exception(RuntimeException::class) + ->withMessage(Message::MANIFEST_KEY_UNKNOWN->getMessage('allowed-packages', 'copy, exclude, merge, modes')); - $this->expectException(RuntimeException::class); - $this->expectExceptionMessage('relative path'); - - $this->loader()->load($package, $this->tempDir); + $this + ->loader() + ->loadFromExtra(['scaffold' => ['manifest' => 'scaffold.json']], 'pkg/example', $this->tempDir); } - public function testLoadThrowsWhenExternalManifestPathIsAbsoluteWindowsBackslash(): void + /** + * Ensures an unreadable provider file is reported with the PHP warning. + */ + #[DataSet(['composer.json'], 'composer.json')] + #[DataSet(['manifest file'], 'manifest file')] + public function throwRuntimeExceptionWhenProviderFileCannotBeRead(string $label): void { - $package = self::createStub(PackageInterface::class); + $path = $this->seedProviderFile($label, '{}'); - $package->method('getExtra')->willReturn(['scaffold' => ['manifest' => '\\Windows\\scaffold.json']]); - $package->method('getName')->willReturn('pkg/bad'); + $this->restrictFileAccess($path, 0o000); - $this->expectException(RuntimeException::class); - $this->expectExceptionMessage('relative path'); + Expect::exception(RuntimeException::class) + ->withMessage( + Message::FILESYSTEM_FAILED->getMessage( + Message::MANIFEST_PROVIDER_FILE_UNREADABLE->getMessage('p/a', $label, $path), + "file_get_contents({$path}): Failed to open stream: Permission denied", + ), + ); - $this->loader()->load($package, $this->tempDir); + $this + ->loader() + ->loadFromPath('p/a', $this->tempDir); } - public function testLoadThrowsWhenExternalManifestPathIsAbsoluteWindowsDrive(): void - { - $package = self::createStub(PackageInterface::class); - - $package->method('getExtra')->willReturn(['scaffold' => ['manifest' => 'C:\\malicious.json']]); - $package->method('getName')->willReturn('pkg/bad'); - - $this->expectException(RuntimeException::class); - $this->expectExceptionMessage('relative path'); - - $this->loader()->load($package, $this->tempDir); + /** + * Ensures a missing, non-object or invalid JSON provider file is rejected. + * + * @param string|null $content Content of the file, or `null` when it is missing. + * @param class-string $exception Expected exception class. + * @param Message|string $message Message case rendered with the package, label and path, or the literal message. + */ + #[DataProvider(ManifestLoaderProvider::class . '::decodeFailures')] + public function throwWhenProviderFileCannotBeDecoded( + string $label, + string|null $content, + string $exception, + Message|string $message, + ): void { + $path = $this->seedProviderFile($label, $content); + + Expect::exception($exception) + ->withMessage($message instanceof Message ? $message->getMessage('p/a', $label, $path) : $message); + + $this + ->loader() + ->loadFromPath('p/a', $this->tempDir); } - public function testLoadThrowsWhenExternalManifestPathIsEmptyString(): void + /** + * Returns a manifest loader with the default schema and expander. + */ + private function loader(): ManifestLoader { - $package = self::createStub(PackageInterface::class); - - $package->method('getExtra')->willReturn(['scaffold' => ['manifest' => '']]); - $package->method('getName')->willReturn('pkg/bad'); - - $this->expectException(RuntimeException::class); - $this->expectExceptionMessage('non-empty string'); - - $this->loader()->load($package, $this->tempDir); + return new ManifestLoader(new ManifestSchema(), new ManifestExpander()); } - public function testLoadThrowsWhenExternalManifestPathIsNotString(): void + /** + * Returns the mapping of a file of the provider rooted at the temp directory. + */ + private function mapping(string $destination, string $source, FileMode $mode, string $provider): FileMapping { - $package = self::createStub(PackageInterface::class); - - $package->method('getExtra')->willReturn(['scaffold' => ['manifest' => 42]]); - $package->method('getName')->willReturn('pkg/bad'); - - $this->expectException(RuntimeException::class); - $this->expectExceptionMessage('non-empty string'); - - $this->loader()->load($package, $this->tempDir); + return new FileMapping($destination, $source, $mode, $provider, $this->tempDir); } - public function testLoadThrowsWhenInlineManifestOmitsCopy(): void + /** + * Writes `$content` at `$relative` under the temp directory, creating intermediate directories as needed. + */ + private function seed(string $relative, string $content = ''): void { - $package = self::createStub(PackageInterface::class); - - $package->method('getExtra')->willReturn(['scaffold' => ['modes' => ['*.php' => 'replace']]]); - $package->method('getName')->willReturn('pkg/bad'); - - $this->expectException(RuntimeException::class); - $this->expectExceptionMessage('"copy"'); - - $this->loader()->load($package, $this->tempDir); - } + $absolute = "{$this->tempDir}/{$relative}"; - protected function setUp(): void - { - $this->setUpTempDirectory(); - } + $this->ensureTestDirectory(dirname($absolute)); - protected function tearDown(): void - { - $this->tearDownTempDirectory(); + file_put_contents( + $absolute, + $content, + ); } /** - * Builds a {@see ManifestLoader} with real dependencies. + * Writes the provider `composer.json`, or the external manifest it names, and returns the path of that file. + * + * @param string $label `composer.json`, or `manifest file` for the external manifest. + * @param string|null $content Content of the file, or `null` to leave it missing. + * + * @return string Absolute path of the file. */ - private function loader(): ManifestLoader + private function seedProviderFile(string $label, string|null $content): string { - return new ManifestLoader(new ManifestSchema(), new ManifestExpander()); - } + $relative = $label === 'composer.json' ? 'composer.json' : 'scaffold.json'; - /** - * Writes an empty file at `$relative` under the temp directory, creating intermediate directories as needed. - */ - private function seedFile(string $relative): void - { - $absolute = "{$this->tempDir}/{$relative}"; + if ($relative === 'scaffold.json') { + $this->seed('composer.json', '{"extra": {"scaffold": {"manifest": "scaffold.json"}}}'); + } - $this->ensureTestDirectory(dirname($absolute)); + if ($content !== null) { + $this->seed($relative, $content); + } - file_put_contents($absolute, ''); + return "{$this->tempDir}/{$relative}"; } } diff --git a/tests/Manifest/ManifestSchemaTest.php b/tests/Manifest/ManifestSchemaTest.php index eafb2aa..de86335 100644 --- a/tests/Manifest/ManifestSchemaTest.php +++ b/tests/Manifest/ManifestSchemaTest.php @@ -4,343 +4,51 @@ namespace PHPForge\Scaffold\Tests\Manifest; -use PHPForge\Scaffold\Manifest\{FileMode, ManifestSchema}; -use PHPUnit\Framework\Attributes\Group; -use PHPUnit\Framework\TestCase; +use PHPForge\Scaffold\Manifest\ManifestSchema; +use PHPForge\Scaffold\Tests\Provider\ManifestSchemaProvider; use RuntimeException; +use Testo\Assert; +use Testo\Codecov\Covers; +use Testo\Data\DataProvider; +use Testo\Expect; +use Testo\Test; /** - * Unit tests for {@see ManifestSchema} validation of the `copy` / `exclude` / `modes` shape. + * Unit tests for {@see ManifestSchema} validation of the `copy` / `exclude` / `modes` / `merge` shape and its keys. + * + * {@see ManifestSchemaProvider} for test case data providers. */ -#[Group('scaffold')] -#[Group('manifest')] -final class ManifestSchemaTest extends TestCase +#[Test] +#[Covers(ManifestSchema::class)] +final class ManifestSchemaTest { - public function testValidateAcceptsCopyEntryAsFromToObjectWithRemap(): void - { - $result = (new ManifestSchema())->validate( - [ - 'copy' => [ - ['from' => 'metadata/.editorconfig', 'to' => '.editorconfig'], - ['from' => 'metadata/.gitignore', 'to' => '.gitignore'], - ], - ], - ); - - self::assertSame( - [ - ['from' => 'metadata/.editorconfig', 'to' => '.editorconfig'], - ['from' => 'metadata/.gitignore', 'to' => '.gitignore'], - ], - $result['copy'], - "Object 'copy' entries must round-trip with separate 'from' and 'to' to support source-destination remapping.", - ); - } - - public function testValidateAcceptsCopyEntryContainingColonInNonLeadingPosition(): void - { - // Pins the '^' anchor in '/^[A-Za-z]:/': non-leading colons (namespaces, stream wrappers) must not be rejected. - $result = (new ManifestSchema())->validate(['copy' => ['some/module:file.php']]); - - self::assertSame( - [['from' => 'some/module:file.php', 'to' => 'some/module:file.php']], - $result['copy'], - 'A colon past the second character must be treated as a literal byte; the drive-letter check fires only on leading.', - ); - } - - public function testValidateAcceptsFullManifest(): void - { - $result = (new ManifestSchema())->validate( - [ - 'copy' => ['src', 'config'], - 'exclude' => ['config/test-local.php'], - 'modes' => ['config/*.php' => 'preserve'], - ], - ); - - self::assertSame( - [ - ['from' => 'src', 'to' => 'src'], - ['from' => 'config', 'to' => 'config'], - ], - $result['copy'], - ); - self::assertSame(['config/test-local.php'], $result['exclude']); - self::assertSame([FileMode::Preserve], array_values($result['modes'])); - self::assertSame(['config/*.php'], array_keys($result['modes'])); - } - - public function testValidatePreservesAllExcludeEntries(): void - { - $result = (new ManifestSchema())->validate( - [ - 'copy' => ['src'], - 'exclude' => ['first.php', 'second.php', 'third.php'], - ], - ); - - self::assertSame( - ['first.php', 'second.php', 'third.php'], - $result['exclude'], - "Every 'exclude[]' entry must round-trip through the validator; dropping entries hides expander patterns.", - ); - } - - public function testValidateResolvesAllFourModesCorrectly(): void - { - $result = (new ManifestSchema())->validate( - [ - 'copy' => ['src'], - 'modes' => [ - 'replace.php' => 'replace', - 'preserve.php' => 'preserve', - 'append.txt' => 'append', - 'prepend.txt' => 'prepend', - ], - ], - ); - - self::assertSame( - [ - 'replace.php' => FileMode::Replace, - 'preserve.php' => FileMode::Preserve, - 'append.txt' => FileMode::Append, - 'prepend.txt' => FileMode::Prepend, - ], - $result['modes'], - 'All four FileMode cases must resolve correctly from their string values.', - ); - } - - public function testValidateReturnsTypedStructureForMinimalManifest(): void - { - $result = (new ManifestSchema())->validate(['copy' => ['src']]); - - self::assertSame( - [ - 'copy' => [['from' => 'src', 'to' => 'src']], - 'exclude' => [], - 'modes' => [], - ], - $result, - "Minimal manifest with only 'copy' must default 'exclude' to empty list and 'modes' to empty map.", - ); - } - - public function testValidateThrowsWhenCopyEntryContainsTraversal(): void - { - $this->expectException(RuntimeException::class); - $this->expectExceptionMessage( - 'Manifest "copy" entry "../escape" must not contain path traversal segments.', - ); - - (new ManifestSchema())->validate(['copy' => ['../escape']]); - } - - public function testValidateThrowsWhenCopyEntryIsAbsoluteUnixPath(): void - { - $this->expectException(RuntimeException::class); - $this->expectExceptionMessage( - 'Manifest "copy" entry "/etc" must be a relative path.', - ); - - (new ManifestSchema())->validate(['copy' => ['/etc']]); - } - - public function testValidateThrowsWhenCopyEntryIsAbsoluteWindowsBackslashPath(): void - { - $this->expectException(RuntimeException::class); - $this->expectExceptionMessage( - 'Manifest "copy" entry "\Windows\System32" must be a relative path.', - ); - - (new ManifestSchema())->validate(['copy' => ['\\Windows\\System32']]); - } - - public function testValidateThrowsWhenCopyEntryIsAbsoluteWindowsPath(): void - { - $this->expectException(RuntimeException::class); - $this->expectExceptionMessage( - 'Manifest "copy" entry "C:\\Windows" must be a relative path.', - ); - - (new ManifestSchema())->validate(['copy' => ['C:\\Windows']]); - } - - public function testValidateThrowsWhenCopyEntryIsEmptyString(): void - { - $this->expectException(RuntimeException::class); - $this->expectExceptionMessage( - 'Manifest "copy" entries must be non-empty strings.', - ); - - (new ManifestSchema())->validate(['copy' => ['']]); - } - - public function testValidateThrowsWhenCopyEntryIsNeitherStringNorFromToObject(): void - { - $this->expectException(RuntimeException::class); - $this->expectExceptionMessage( - 'Manifest "copy" entries must be either a string or an object with "from" and "to" keys.', - ); - - (new ManifestSchema())->validate(['copy' => [42]]); - } - - public function testValidateThrowsWhenCopyFromContainsTraversal(): void - { - $this->expectException(RuntimeException::class); - $this->expectExceptionMessage( - 'Manifest "copy.from" entry "../escape" must not contain path traversal segments.', - ); - - (new ManifestSchema())->validate( - ['copy' => [['from' => '../escape', 'to' => 'escape']]], - ); - } - - public function testValidateThrowsWhenCopyIsAssociativeObject(): void - { - $this->expectException(RuntimeException::class); - $this->expectExceptionMessage('Manifest "copy" must be a sequential list of entries, not an associative object.'); - - // The plain object form must be rejected so its keys are not silently iterated as two unrelated string entries. - (new ManifestSchema())->validate( - ['copy' => ['from' => 'metadata/.gitignore', 'to' => '.gitignore']], - ); - } - - public function testValidateThrowsWhenCopyIsEmptyArray(): void - { - $this->expectException(RuntimeException::class); - $this->expectExceptionMessage( - 'Manifest "copy" must declare at least one path.', - ); - - (new ManifestSchema())->validate(['copy' => []]); - } - - public function testValidateThrowsWhenCopyIsNotArray(): void - { - $this->expectException(RuntimeException::class); - $this->expectExceptionMessage( - 'Manifest is missing required key "copy" or it is not an array.', + /** + * Ensures an invalid manifest is rejected with the message naming the offending key or entry. + * + * @param array $raw Raw manifest. + */ + #[DataProvider(ManifestSchemaProvider::class . '::invalidManifests')] + public function throwRuntimeExceptionForInvalidManifest(array $raw, bool $inline, string $message): void + { + Expect::exception(RuntimeException::class) + ->withMessage($message); + + (new ManifestSchema())->validate($raw, $inline); + } + + /** + * Ensures a valid manifest is normalised into the typed structure with defaults for the optional keys. + * + * @param array $raw Raw manifest. + * @param array $expected Validated manifest. + */ + #[DataProvider(ManifestSchemaProvider::class . '::validManifests')] + public function validateReturnsTheTypedStructure(array $raw, bool $inline, array $expected): void + { + Assert::same( + (new ManifestSchema())->validate($raw, $inline), + $expected, + 'Validated manifest must match.', ); - - (new ManifestSchema())->validate(['copy' => 'src']); - } - - public function testValidateThrowsWhenCopyKeyIsMissing(): void - { - $this->expectException(RuntimeException::class); - $this->expectExceptionMessage( - 'Manifest is missing required key "copy" or it is not an array.', - ); - - (new ManifestSchema())->validate([]); - } - - public function testValidateThrowsWhenCopyToIsAbsolutePath(): void - { - $this->expectException(RuntimeException::class); - $this->expectExceptionMessage( - 'Manifest "copy.to" entry "/etc/foo" must be a relative path.', - ); - - (new ManifestSchema())->validate( - ['copy' => [['from' => 'metadata/foo', 'to' => '/etc/foo']]], - ); - } - - public function testValidateThrowsWhenExcludeEntryContainsTraversal(): void - { - $this->expectException(RuntimeException::class); - $this->expectExceptionMessage( - 'Manifest "exclude" entry "../bad" must not contain path traversal segments.', - ); - - (new ManifestSchema())->validate(['copy' => ['src'], 'exclude' => ['../bad']]); - } - - public function testValidateThrowsWhenExcludeIsNotArray(): void - { - $this->expectException(RuntimeException::class); - $this->expectExceptionMessage( - 'Manifest "exclude" must be an array when present.', - ); - - (new ManifestSchema())->validate(['copy' => ['src'], 'exclude' => 'not-an-array']); - } - - public function testValidateThrowsWhenModesIsNotObject(): void - { - $this->expectException(RuntimeException::class); - $this->expectExceptionMessage( - 'Manifest "modes" must be an object when present.', - ); - - (new ManifestSchema())->validate(['copy' => ['src'], 'modes' => 'invalid']); - } - - public function testValidateThrowsWhenModesKeyContainsTraversal(): void - { - $this->expectException(RuntimeException::class); - $this->expectExceptionMessage( - 'Manifest "modes" entry "../escape" must not contain path traversal segments.', - ); - - (new ManifestSchema())->validate(['copy' => ['src'], 'modes' => ['../escape' => 'preserve']]); - } - - public function testValidateThrowsWhenModesKeyIsAbsoluteUnixPath(): void - { - $this->expectException(RuntimeException::class); - $this->expectExceptionMessage( - 'Manifest "modes" entry "/etc/passwd" must be a relative path.', - ); - - (new ManifestSchema())->validate(['copy' => ['src'], 'modes' => ['/etc/passwd' => 'preserve']]); - } - - public function testValidateThrowsWhenModesKeyIsAbsoluteWindowsPath(): void - { - $this->expectException(RuntimeException::class); - $this->expectExceptionMessage( - 'Manifest "modes" entry "C:\Windows" must be a relative path.', - ); - - (new ManifestSchema())->validate(['copy' => ['src'], 'modes' => ['C:\\Windows' => 'preserve']]); - } - - public function testValidateThrowsWhenModesKeyIsEmptyString(): void - { - $this->expectException(RuntimeException::class); - $this->expectExceptionMessage( - 'Manifest "modes" entries must be non-empty strings.', - ); - - (new ManifestSchema())->validate(['copy' => ['src'], 'modes' => ['' => 'preserve']]); - } - - public function testValidateThrowsWhenModesValueIsNotString(): void - { - $this->expectException(RuntimeException::class); - $this->expectExceptionMessage( - 'Manifest "modes" value for pattern "config/*.php" must be a string.', - ); - - (new ManifestSchema())->validate(['copy' => ['src'], 'modes' => ['config/*.php' => 123]]); - } - - public function testValidateThrowsWhenModesValueIsUnknownMode(): void - { - $this->expectException(RuntimeException::class); - $this->expectExceptionMessage( - 'Manifest "modes" value for pattern "config/*.php" has invalid mode "unknown-mode". Allowed: append, ' - . 'prepend, preserve, replace.', - ); - - (new ManifestSchema())->validate(['copy' => ['src'], 'modes' => ['config/*.php' => 'unknown-mode']]); } } diff --git a/tests/Merge/IniMergeStrategyTest.php b/tests/Merge/IniMergeStrategyTest.php new file mode 100644 index 0000000..4bf4b45 --- /dev/null +++ b/tests/Merge/IniMergeStrategyTest.php @@ -0,0 +1,41 @@ + $expected Expected `[text, terminator]` segments. + */ + #[DataProvider(LinesProvider::class . '::segments')] + public function splitRawKeepsEachTerminator(string $content, array $expected): void + { + Assert::same( + Lines::splitRaw($content), + $expected, + 'Segments must match.', + ); + } + /** + * Ensures content normalised to `"\n"` splits into its lines, ignoring the last terminator. + * + * @param list $expected Expected lines. + */ + #[DataProvider(LinesProvider::class . '::lines')] + public function splitYieldsTheLines(string $content, array $expected): void + { + Assert::same( + Lines::split($content), + $expected, + 'Lines must match.', + ); + } +} diff --git a/tests/Merge/ListMergeStrategyTest.php b/tests/Merge/ListMergeStrategyTest.php new file mode 100644 index 0000000..98310ca --- /dev/null +++ b/tests/Merge/ListMergeStrategyTest.php @@ -0,0 +1,41 @@ + $class Expected strategy class. + */ + #[DataProvider(StrategyResolverProvider::class . '::kinds')] + public function forKindReturnsMatchingStrategy(MergeStrategyKind $kind, string $class): void + { + Assert::same( + StrategyResolver::forKind($kind)::class, + $class, + "Kind '{$kind->value}' must map to its strategy.", + ); + } + /** + * Ensures the default strategy follows the destination basename. + * + * @param class-string $class Expected strategy class. + */ + #[DataProvider(StrategyResolverProvider::class . '::destinations')] + public function forReturnsDefaultStrategyByBasename(string $destination, string $class): void + { + Assert::same( + StrategyResolver::for($destination)::class, + $class, + "Default strategy of '{$destination}' must match.", + ); + } +} diff --git a/tests/Merge/TextMergeStrategyTest.php b/tests/Merge/TextMergeStrategyTest.php new file mode 100644 index 0000000..54dbe3e --- /dev/null +++ b/tests/Merge/TextMergeStrategyTest.php @@ -0,0 +1,41 @@ +expects(self::once()) - ->method('addSubscriber') - ->with(self::isInstanceOf(EventSubscriber::class)); + $dispatcher = new RecordingEventDispatcher(); - $composer = self::createStub(Composer::class); - $composer->method('getEventDispatcher')->willReturn($dispatcher); + (new Plugin())->activate(self::composer($dispatcher), new NullIO()); - (new Plugin())->activate($composer, new NullIO()); + Assert::same( + array_column($dispatcher->calls, 0), + ['addSubscriber'], + "Only 'addSubscriber' must be called.", + ); + Assert::instanceOf( + $dispatcher->calls[0][1] ?? null, + EventSubscriber::class, + 'The registered subscriber must be an event subscriber.', + ); } - public function testDeactivateIsIdempotentWhenCalledTwice(): void + /** + * Ensures deactivation removes the registered subscriber once, however often it runs. + */ + public function deactivateRemovesTheRegisteredSubscriberOnlyOnce(): void { - $dispatcher = self::createMock(EventDispatcher::class); - - $dispatcher->expects(self::once())->method('addSubscriber'); - $dispatcher->expects(self::once())->method('removeListener'); - - $composer = self::createStub(Composer::class); - - $composer->method('getEventDispatcher')->willReturn($dispatcher); - + $dispatcher = new RecordingEventDispatcher(); + $composer = self::composer($dispatcher); $plugin = new Plugin(); + $plugin->activate($composer, new NullIO()); $plugin->deactivate($composer, new NullIO()); $plugin->deactivate($composer, new NullIO()); + + Assert::same( + array_column($dispatcher->calls, 0), + ['addSubscriber', 'removeListener'], + "A second deactivation must not call 'removeListener' again.", + ); + Assert::same( + $dispatcher->calls[1][1] ?? null, + $dispatcher->calls[0][1] ?? null, + 'The removed listener must be the registered subscriber.', + ); } - public function testDeactivateIsNoopWhenNotActivated(): void + /** + * Ensures deactivation without activation calls no dispatcher method. + */ + public function deactivateWithoutActivationLeavesTheDispatcherUntouched(): void { - $dispatcher = self::createMock(EventDispatcher::class); + $dispatcher = new RecordingEventDispatcher(); - $dispatcher->expects(self::never())->method('removeListener'); + (new Plugin())->deactivate(self::composer($dispatcher), new NullIO()); - $composer = self::createStub(Composer::class); - - $composer->method('getEventDispatcher')->willReturn($dispatcher); - - (new Plugin())->deactivate($composer, new NullIO()); + Assert::same( + $dispatcher->calls, + [], + 'No dispatcher method may be called.', + ); } - public function testDeactivateRemovesSubscriberAfterActivate(): void + /** + * Ensures uninstall leaves the subscriber registered. + */ + public function uninstallKeepsTheSubscriberRegistered(): void { - $dispatcher = self::createMock(EventDispatcher::class); - - $dispatcher->expects(self::once())->method('addSubscriber'); - $dispatcher - ->expects(self::once()) - ->method('removeListener') - ->with(self::isInstanceOf(EventSubscriber::class)); - - $composer = self::createStub(Composer::class); - - $composer->method('getEventDispatcher')->willReturn($dispatcher); - + $dispatcher = new RecordingEventDispatcher(); + $composer = self::composer($dispatcher); $plugin = new Plugin(); $plugin->activate($composer, new NullIO()); - $plugin->deactivate($composer, new NullIO()); - } - - public function testGetCapabilitiesReturnsEmptyArray(): void - { - self::assertCount( - 0, - (new Plugin())->getCapabilities(), - 'Plugin capabilities array is not empty.', - ); - } + $plugin->uninstall($composer, new NullIO()); - public function testPluginImplementsCapable(): void - { - self::assertInstanceOf( - Capable::class, - new Plugin(), - 'Plugin does not implement the Capable interface.', + Assert::same( + array_column($dispatcher->calls, 0), + ['addSubscriber'], + "Uninstall must not call 'removeListener'.", ); } - public function testPluginImplementsPluginInterface(): void + /** + * Returns a Composer instance that uses `$dispatcher`. + */ + private static function composer(RecordingEventDispatcher $dispatcher): Composer { - self::assertInstanceOf( - PluginInterface::class, - new Plugin(), - 'Plugin does not implement the PluginInterface.', - ); - } + $composer = new Composer(); - #[DoesNotPerformAssertions] - public function testUninstallIsNoop(): void - { - $composer = self::createStub(Composer::class); + $composer->setEventDispatcher($dispatcher); - // `uninstall()` is an explicit no-op per PluginInterface; this test guards against accidentally adding behavior - // that would throw during `composer remove`. - (new Plugin())->uninstall($composer, new NullIO()); + return $composer; } } diff --git a/tests/Provider/ApplicationRunProvider.php b/tests/Provider/ApplicationRunProvider.php new file mode 100644 index 0000000..11d7611 --- /dev/null +++ b/tests/Provider/ApplicationRunProvider.php @@ -0,0 +1,49 @@ +}> + */ + public static function commandsReadingTheLock(): iterable + { + yield 'diff' => [['command' => 'diff', '--all' => true]]; + yield 'eject' => [['command' => 'eject', 'file' => 'a.txt']]; + yield 'providers' => [['command' => 'providers']]; + yield 'prune' => [['command' => 'prune']]; + yield 'reapply' => [['command' => 'reapply']]; + yield 'status' => [['command' => 'status']]; + yield 'sync' => [['command' => 'sync']]; + } + + /** + * @return iterable, int}> + */ + public static function commandsSkippingADeniedProvider(): iterable + { + yield 'diff all' => [['command' => 'diff', '--all' => true], 1]; + yield 'diff file' => [['command' => 'diff', 'file' => 'd.txt'], 1]; + yield 'reapply' => [['command' => 'reapply'], 1]; + yield 'reapply force' => [['command' => 'reapply', '--force' => true], 1]; + yield 'status' => [['command' => 'status'], 0]; + } + + /** + * @return iterable}> + */ + public static function projectRootStarts(): iterable + { + yield 'nested current directory' => ['{root}/src/deep', ['command' => 'status']]; + yield 'short working directory option' => ['/', ['command' => 'status', '-d' => '{root}']]; + yield 'working directory option' => ['/', ['command' => 'status', '--working-dir' => '{root}/src']]; + } +} diff --git a/tests/Provider/ApplyPreviewerProvider.php b/tests/Provider/ApplyPreviewerProvider.php new file mode 100644 index 0000000..bba4bc8 --- /dev/null +++ b/tests/Provider/ApplyPreviewerProvider.php @@ -0,0 +1,126 @@ + + */ + public static function lineEndings(): iterable + { + yield 'CRLF against LF' => [true, "a\r\nb\r\n", "a\nb\n", true, true]; + yield 'missing destination' => [false, '', "a\n", true, false]; + yield 'identical content' => [true, "a\n", "a\n", false, false]; + } + + /** + * @return iterable< + * string, + * array{string, FileMode, MergeStrategyKind|null, string, string|null, array} + * > + */ + public static function modes(): iterable + { + yield 'append with the recorded strategy' => [ + 'list.cfg', + FileMode::Append, + MergeStrategyKind::ListFile, + "a\nb\n", + "a\nmine\n", + self::preview(true, "a\nmine\n", "a\nmine\n\nb\n", true, false), + ]; + yield 'append already satisfied' => [ + '.gitignore', + FileMode::Append, + null, + "a\n", + "mine\na\n", + self::preview(true, "mine\na\n", "mine\na\n", false, false), + ]; + yield 'replace of a missing destination' => [ + 'new.txt', + FileMode::Replace, + null, + "n\n", + null, + self::preview(false, '', "n\n", true, false), + ]; + yield 'prepend with the destination line ending' => [ + 'h.php', + FileMode::Prepend, + null, + " [ + 'ecs.php', + FileMode::Preserve, + null, + "stub\n", + "mine\n", + self::preview(true, "mine\n", "stub\n", true, true), + ]; + } + + /** + * Provides lock entries of a `replace` destination holding `mine\n` with the expected `userModified` flag. + * + * @return iterable + */ + public static function userModified(): iterable + { + $entry = [ + 'hash' => 'sha256:other', + 'provider' => 'p/a', + 'source' => 'stubs/a.txt', + 'mode' => 'replace', + ]; + $matching = [ + ...$entry, + 'hash' => 'sha256:' . hash('sha256', "mine\n"), + ]; + + yield 'adopted with a matching hash' => [[...$matching, 'adopted' => true], true]; + yield 'adopted' => [['adopted' => true, ...$entry], true]; + yield 'hash differs' => [$entry, true]; + yield 'hash matches' => [$matching, false]; + yield 'untracked' => [null, false]; + } + + /** + * Returns the expected preview values keyed by property. + * + * @return array + */ + private static function preview( + bool $exists, + string $current, + string $proposed, + bool $changes, + bool $informational, + ): array { + return [ + 'exists' => $exists, + 'current' => $current, + 'proposed' => $proposed, + 'changes' => $changes, + 'informational' => $informational, + ]; + } +} diff --git a/tests/Provider/ComposerFreeRuntimeProvider.php b/tests/Provider/ComposerFreeRuntimeProvider.php new file mode 100644 index 0000000..557b32e --- /dev/null +++ b/tests/Provider/ComposerFreeRuntimeProvider.php @@ -0,0 +1,22 @@ + + */ + public static function adapterOnlyReferences(): iterable + { + yield 'Composer adapter classes' => ['/\b(?:Scaffolder|EventSubscriber|ComposerIoWriter)\b(?!::)/']; + yield 'Composer classes other than InstalledVersions' => ['/Composer\\\\(?!InstalledVersions\b)[A-Za-z]+/']; + } +} diff --git a/tests/Provider/ConsoleMessageProvider.php b/tests/Provider/ConsoleMessageProvider.php new file mode 100644 index 0000000..a711420 --- /dev/null +++ b/tests/Provider/ConsoleMessageProvider.php @@ -0,0 +1,429 @@ +, string}> + */ + public static function cases(): iterable + { + $literals = self::literals(); + + foreach (Message::cases() as $case) { + yield $case->name => [ + $case, + ...$literals[$case->name] ?? throw new LogicException("Case '{$case->name}' has no pinned literal."), + ]; + + unset($literals[$case->name]); + } + + if ($literals !== []) { + throw new LogicException('Literals without a case: ' . implode(', ', array_keys($literals)) . '.'); + } + } + + /** + * @return array, string}> + */ + private static function literals(): array + { + return [ + 'COMMAND_CWD_UNRESOLVABLE' => [ + [], + '[scaffold] Unable to determine current working directory.', + ], + 'COMMAND_FILE_ERROR' => [ + ['a.txt', 'Stub not found: "/vendor/p/a/stubs/a.txt".'], + '[scaffold] "a.txt": Stub not found: "/vendor/p/a/stubs/a.txt".', + ], + 'COMMAND_FILE_NOT_TRACKED' => [ + ['a.txt'], + '[scaffold] "a.txt" is not tracked in scaffold-lock.json.', + ], + 'COMMAND_MANIFEST_NOT_FOUND' => [ + ['composer.json', '/project'], + '[scaffold] No composer.json found in "/project" or any parent directory.', + ], + 'COMMAND_PROVIDER_NOT_ALLOWED' => [ + ['a.txt', 'p/a'], + '[scaffold] "a.txt": provider "p/a" is not in extra.scaffold.allowed-packages; skipped.', + ], + 'COMMAND_UNSAFE_ENTRY' => [ + ['../a.txt', 'Destination path "../a.txt" contains a traversal segment.'], + '[scaffold] Unsafe lock entry for "../a.txt": Destination path "../a.txt" contains a traversal ' + . 'segment.', + ], + 'COMMAND_WORKING_DIR_NOT_FOUND' => [ + ['/missing'], + '[scaffold] Working directory "/missing" does not exist.', + ], + 'DIFF_CREATED_EMPTY' => [ + ['a.txt'], + '[scaffold] a.txt: would be created empty.', + ], + 'DIFF_EJECTED' => [ + ['a.txt'], + '[scaffold] a.txt: ejected; scaffold does not manage it (see reapply --force).', + ], + 'DIFF_LINE_ENDINGS_ONLY' => [ + ['a.txt'], + '[scaffold] a.txt: differs only in line endings.', + ], + 'DIFF_MANIFEST_NOT_LOADED' => [ + ['a.txt', 'p/a'], + '[scaffold] "a.txt": the manifest of provider "p/a" could not be loaded; skipped.', + ], + 'DIFF_NO_CHANGES' => [ + ['a.txt'], + '[scaffold] a.txt: no changes.', + ], + 'DIFF_ORPHAN' => [ + ['a.txt'], + '[scaffold] a.txt: orphan; no allowed provider ships it anymore.', + ], + 'DIFF_PREVIEW_HEADER' => [ + ['a.txt', 'replace', 'p/a', ''], + '[scaffold] a.txt (replace, p/a): changes applying the provider would make', + ], + 'DIFF_TARGET_AMBIGUOUS' => [ + [], + '[scaffold] Pass either a file or --all.', + ], + 'EJECT_ALREADY_EJECTED' => [ + ['a.txt'], + '[scaffold] "a.txt" is already ejected.', + ], + 'EJECT_CONFIRMATION_REQUIRED' => [ + ['a.txt'], + '[scaffold] Would eject "a.txt": it will not be managed until reapplied with --force. Run with --yes ' + . 'to confirm.', + ], + 'EJECT_EJECTED' => [ + ['a.txt'], + '[scaffold] Ejected "a.txt": it will not be managed until reapplied with --force. The file was not ' + . 'deleted from disk.', + ], + 'FRAGMENT_COMMAND' => [ + ['sync'], + 'sync: ', + ], + 'FRAGMENT_CONFLICT' => [ + [], + 'conflict', + ], + 'FRAGMENT_CONFLICT_FILE' => [ + [], + 'file has', + ], + 'FRAGMENT_CONFLICT_FILES' => [ + [], + 'files have', + ], + 'FRAGMENT_COUNT' => [ + [2, 'synced'], + '2 synced', + ], + 'FRAGMENT_COUNT_UNCHANGED' => [ + [8], + '8 unchanged', + ], + 'FRAGMENT_COUNT_WRITTEN' => [ + [3, 'files'], + '3 files written', + ], + 'FRAGMENT_DRY_RUN' => [ + [], + ' --dry-run', + ], + 'FRAGMENT_ENTRIES_LACK' => [ + [], + 'entries lack', + ], + 'FRAGMENT_ENTRY_LACKS' => [ + [], + 'entry lacks', + ], + 'FRAGMENT_ERROR' => [ + [], + 'error', + ], + 'FRAGMENT_ERRORS' => [ + [], + 'errors', + ], + 'FRAGMENT_FILE' => [ + [], + 'file', + ], + 'FRAGMENT_FILES' => [ + [], + 'files', + ], + 'FRAGMENT_ORPHAN' => [ + [], + 'orphan', + ], + 'FRAGMENT_OUTDATED' => [ + [], + 'outdated', + ], + 'FRAGMENT_PARENTHESIZED' => [ + ['modified'], + ' (modified)', + ], + 'FRAGMENT_PRESERVE_PREVIEW' => [ + [], + ' (preserve: applied only with reapply --force)', + ], + 'FRAGMENT_UNKNOWN_PROVIDER' => [ + [], + '?', + ], + 'FRAGMENT_USER_MODIFIED_PREVIEW' => [ + [], + ' (user-modified: scaffold skips it; use reapply --force)', + ], + 'FRAGMENT_WARNING' => [ + [], + 'warning', + ], + 'FRAGMENT_WARNINGS' => [ + [], + 'warnings', + ], + 'FRAGMENT_WOULD_BE_WRITTEN' => [ + [], + 'would be written', + ], + 'FRAGMENT_WRITTEN' => [ + [], + 'written', + ], + 'PROVIDERS_NONE' => [ + [], + '[scaffold] No providers tracked in scaffold-lock.json.', + ], + 'PRUNE_DELETED' => [ + ['a.txt', ''], + '[scaffold] Deleted "a.txt".', + ], + 'PRUNE_DIRECTORY_REMOVE_FAILED' => [ + ['/project/config'], + '[scaffold] Could not remove empty directory "/project/config".', + ], + 'PRUNE_DRY_RUN_SUMMARY' => [ + [2, 1, 0, 'errors'], + '[scaffold] prune --dry-run: 2 would be removed, 1 would be kept (modified), 0 errors; run with ' + . '--force to apply.', + ], + 'PRUNE_ENTRY_DROPPED' => [ + ['a.txt', 'missing'], + '[scaffold] Dropped the entry of "a.txt" (missing).', + ], + 'PRUNE_FILE_DELETE_FAILED' => [ + ['/project/a.txt'], + '[scaffold] Could not delete "/project/a.txt".', + ], + 'PRUNE_KEPT' => [ + ['a.txt', 'modified'], + '[scaffold] Kept "a.txt" (modified); it is yours now and no longer tracked.', + ], + 'PRUNE_NO_ORPHANS' => [ + [], + '[scaffold] No orphaned files.', + ], + 'PRUNE_SUMMARY' => [ + [2, 1, 0, 'errors'], + '[scaffold] prune: 2 removed, 1 kept (modified), 0 errors.', + ], + 'REAPPLY_ALREADY_UP_TO_DATE' => [ + ['a.txt'], + '[scaffold] "a.txt" is already up to date.', + ], + 'REAPPLY_APPLIED' => [ + ['a.txt'], + '[scaffold] Reapplied "a.txt".', + ], + 'REAPPLY_EJECTED' => [ + ['a.txt'], + '[scaffold] "a.txt" is ejected. Use --force to manage it again.', + ], + 'REAPPLY_FAILED' => [ + ['a.txt', 'Could not write "/project/a.txt".'], + '[scaffold] Could not reapply "a.txt": Could not write "/project/a.txt". Skipping.', + ], + 'REAPPLY_MERGE_STRATEGY_UNKNOWN' => [ + ['yaml', '.gitignore'], + '[scaffold] Unknown merge strategy "yaml" for ".gitignore"; using the default for its name.', + ], + 'REAPPLY_NO_MATCH' => [ + [], + '[scaffold] No tracked files matched the given filter.', + ], + 'REAPPLY_ORPHANED' => [ + ['a.txt'], + '[scaffold] "a.txt" is orphaned; run "vendor/bin/scaffold prune" to review.', + ], + 'REAPPLY_PRESERVE' => [ + ['a.txt'], + '[scaffold] "a.txt" uses mode "preserve". Use --force to overwrite.', + ], + 'REAPPLY_STUB_NOT_FOUND' => [ + ['/vendor/p/a/stubs/a.txt'], + '[scaffold] Stub not found: "/vendor/p/a/stubs/a.txt". Skipping.', + ], + 'REAPPLY_SUMMARY' => [ + ['', 3, 'written', 7, 1, ' (user-modified)', 0, 'errors'], + '[scaffold] reapply: 3 written, 7 unchanged, 1 skipped (user-modified), 0 errors.', + ], + 'REAPPLY_UNSAFE_ENTRY' => [ + ['../a.txt', 'Destination path "../a.txt" contains a traversal segment.'], + '[scaffold] Unsafe lock entry for "../a.txt": Destination path "../a.txt" contains a traversal ' + . 'segment. Skipping.', + ], + 'REAPPLY_USER_MODIFIED' => [ + ['a.txt'], + '[scaffold] "a.txt" is user-modified. Use --force to overwrite.', + ], + 'SCAFFOLD_ADOPTED_SKIPPED' => [ + ['a.txt'], + '[scaffold] User-modified file skipped: "a.txt".', + ], + 'SCAFFOLD_ALLOWED_ENTRY_IGNORED' => [ + [], + '[scaffold] Non-string entry in allowed-packages ignored.', + ], + 'SCAFFOLD_APPLY_FAILED' => [ + ['a.txt', 'Could not write "/project/a.txt".'], + '[scaffold] Error applying "a.txt": Could not write "/project/a.txt".', + ], + 'SCAFFOLD_AUTO_DISABLED' => [ + [], + '[scaffold] Auto-scaffold disabled via "extra.scaffold.auto"; run "vendor/bin/scaffold" manually.', + ], + 'SCAFFOLD_CONFIG_MISSING' => [ + [], + '[scaffold] No extra.scaffold configuration found. Skipping scaffold.', + ], + 'SCAFFOLD_CONFLICTS' => [ + [2, 'files have'], + '[scaffold] 2 files have provider updates you have not taken (conflict); run "vendor/bin/scaffold ' + . 'diff --all".', + ], + 'SCAFFOLD_NO_ALLOWED_PACKAGES' => [ + [], + '[scaffold] No allowed-packages configured. Skipping scaffold.', + ], + 'SCAFFOLD_ORPHAN_ENTRY' => [ + ['a.txt', 'p/a'], + '[scaffold] a.txt (p/a)', + ], + 'SCAFFOLD_ORPHAN_HEADER' => [ + [2, 'files'], + '[scaffold] 2 orphaned files no allowed provider ships anymore; run "vendor/bin/scaffold prune" to ' + . 'review.', + ], + 'SCAFFOLD_ORPHAN_MORE' => [ + [3], + '[scaffold] ... and 3 more', + ], + 'SCAFFOLD_OVERRIDE' => [ + ['a.txt', 'p/b', 'p/a'], + '[scaffold] "a.txt" from "p/b" overrides "p/a" (last provider in allowed-packages wins).', + ], + 'SCAFFOLD_PERMISSIONS_COPY_FAILED' => [ + ['/vendor/p/a/stubs/bin/run', '/project/bin/run'], + 'Could not copy permissions from "/vendor/p/a/stubs/bin/run" to "/project/bin/run".', + ], + 'SCAFFOLD_PREFIXED' => [ + ['User-modified file skipped: "a.txt".'], + '[scaffold] User-modified file skipped: "a.txt".', + ], + 'SCAFFOLD_PROVIDER_INSTALL_PATH_MISSING' => [ + ['p/a'], + '[scaffold] Provider "p/a" has no install path (metapackage); skipping.', + ], + 'SCAFFOLD_PROVIDER_MAPPINGS_EMPTY' => [ + ['p/a'], + '[scaffold] Provider "p/a" produced no file mappings; check its copy[] entries and excludes.', + ], + 'SCAFFOLD_PROVIDER_NOT_INSTALLED' => [ + ['p/a'], + '[scaffold] Provider "p/a" is allowed but not installed; check extra.scaffold.allowed-packages or ' + . 'require it.', + ], + 'SCAFFOLD_PROVIDER_ROOT_OUTSIDE_VENDOR' => [ + ['p/a'], + '[scaffold] Provider root for "p/a" resolves outside vendor dir; using default path.', + ], + 'SCAFFOLD_SUMMARY' => [ + ['', '3 files written, 8 unchanged, 1 conflict, 1 warning'], + '[scaffold] 3 files written, 8 unchanged, 1 conflict, 1 warning.', + ], + 'SCAFFOLD_UNTRACKED_OVERWRITTEN' => [ + ['a.txt'], + 'Overwrote untracked existing file "a.txt"; review it with git diff or run "scaffold eject a.txt ' + . '--yes" to keep your version.', + ], + 'SCAFFOLD_USER_MODIFIED_SKIPPED' => [ + ['a.txt'], + 'User-modified file skipped: "a.txt".', + ], + 'SCAFFOLD_VENDOR_DIR_UNRESOLVABLE' => [ + [], + '[scaffold] Unable to resolve vendor-dir from Composer config; aborting scaffold.', + ], + 'STATUS_FORMAT_UNKNOWN' => [ + ['xml'], + '[scaffold] Unknown format "xml"; use "table" or "json".', + ], + 'STATUS_NO_FILES' => [ + [], + '[scaffold] No files tracked in scaffold-lock.json.', + ], + 'STATUS_PROVIDER_DRIFT' => [ + ['p/a', '1.0.0', '1.1.0'], + '[scaffold] p/a: lock 1.0.0, installed 1.1.0 (run composer install).', + ], + 'STATUS_STUB_HASH_MISSING' => [ + [2, 'entries lack'], + '[scaffold] 2 entries lack stub-hash; run composer install to refresh.', + ], + 'STATUS_SUMMARY' => [ + [3, 'files', '2 synced, 1 modified'], + '[scaffold] 3 files: 2 synced, 1 modified.', + ], + 'SYNC_ABORTED' => [ + ['Could not write lock file "/project/scaffold-lock.json".'], + '[scaffold] Sync aborted: Could not write lock file "/project/scaffold-lock.json".', + ], + 'SYNC_DRY_RUN_SUMMARY' => [ + [2, 'files', 5, 1, 0, 'errors'], + '[scaffold] sync --dry-run: 2 files would change, 5 unchanged, 1 orphan, 0 errors.', + ], + 'SYNC_NO_ALLOWED_PACKAGES' => [ + [], + '[scaffold] No allowed-packages configured. Nothing to sync.', + ], + ]; + } +} diff --git a/tests/Provider/DefaultExcludesProvider.php b/tests/Provider/DefaultExcludesProvider.php index 164dbed..d24a32c 100644 --- a/tests/Provider/DefaultExcludesProvider.php +++ b/tests/Provider/DefaultExcludesProvider.php @@ -4,106 +4,140 @@ namespace PHPForge\Scaffold\Tests\Provider; +use PHPForge\Scaffold\Tests\Manifest\DefaultExcludesTest; + /** - * Data provider for {@see \PHPForge\Scaffold\Tests\Manifest\DefaultExcludesTest} test cases. + * Data provider for {@see DefaultExcludesTest} test cases. */ final class DefaultExcludesProvider { /** - * @phpstan-return list + * @return iterable + */ + public static function excludedPaths(): iterable + { + return self::rows( + [ + 'composer.json', + 'composer.lock', + 'vendor/autoload.php', + 'vendor/nested/pkg/file.php', + '.git', + '.git/HEAD', + '.github/workflows/ci.yml', + '.gitattributes', + '.gitignore', + 'tests/unit/SomeTest.php', + 'tests/functional/deep/Fixture.php', + 'phpunit.xml', + 'phpunit.xml.dist', + '.phpunit.cache/foo', + 'phpstan.neon', + 'phpstan.neon.dist', + 'phpstan.cache/bar', + 'infection.json5', + 'infection.log', + '.editorconfig', + '.php-cs-fixer.php', + '.php-cs-fixer.dist.php', + 'ecs.php', + 'psalm.xml', + 'README.md', + 'CHANGELOG.md', + 'LICENSE', + 'docs/providers.md', + 'scaffold.json', + 'scaffold-lock.json', + 'runtime/cache/foo', + 'runtime/.gitignore', + 'node_modules/pkg/index.js', + '.idea/workspace.xml', + '.DS_Store', + ], + ); + } + + /** + * @return iterable */ - public static function excludedPaths(): array + public static function includedPaths(): iterable { - return [ - ['composer.json'], - ['composer.lock'], - ['vendor/autoload.php'], - ['vendor/nested/pkg/file.php'], - ['.git/HEAD'], - ['.github/workflows/ci.yml'], - ['.gitattributes'], - ['.gitignore'], - ['tests/unit/SomeTest.php'], - ['tests/functional/deep/Fixture.php'], - ['phpunit.xml'], - ['phpunit.xml.dist'], - ['.phpunit.cache/foo'], - ['phpstan.neon'], - ['phpstan.neon.dist'], - ['phpstan.cache/bar'], - ['infection.json5'], - ['infection.log'], - ['.editorconfig'], - ['.php-cs-fixer.php'], - ['.php-cs-fixer.dist.php'], - ['ecs.php'], - ['psalm.xml'], - ['README.md'], - ['CHANGELOG.md'], - ['LICENSE'], - ['docs/providers.md'], - ['scaffold.json'], - ['scaffold-lock.json'], - ['runtime/cache/foo'], - ['runtime/.gitignore'], - ]; + return self::rows( + [ + 'src/controllers/SiteController.php', + 'src/models/User.php', + 'config/params.php', + 'config/web.php', + 'migrations/M2024_CreateUserTable.php', + 'public/index.php', + 'public/assets/.gitkeep', + 'yii', + 'rbac/items.php', + 'resources/mail/layouts/html.php', + '.vscode/settings.json', + '.gitlab-ci.yml', + '.github-actions.yml', + 'sub/.DS_Store', + ], + ); } /** - * @phpstan-return list + * @return iterable */ - public static function includedPaths(): array + public static function nonPrunableDirectories(): iterable { - return [ - ['src/controllers/SiteController.php'], - ['src/models/User.php'], - ['config/params.php'], - ['config/web.php'], - ['migrations/M2024_CreateUserTable.php'], - ['public/index.php'], - ['public/assets/.gitkeep'], - ['yii'], - ['rbac/items.php'], - ['resources/mail/layouts/html.php'], - ]; + return self::rows( + [ + 'src', + 'config', + 'migrations', + 'public', + 'rbac', + 'resources', + 'vendor/bin', + '.git/hooks', + 'tests/unit', + 'docs/nested', + '', + ], + ); } /** - * @phpstan-return list + * @return iterable */ - public static function nonPrunableDirectories(): array + public static function prunableDirectories(): iterable { - return [ - ['src'], - ['config'], - ['migrations'], - ['public'], - ['rbac'], - ['resources'], - ['vendor/bin'], - ['.git/hooks'], - ['tests/unit'], - ['docs/nested'], - [''], - ]; + return self::rows( + [ + 'vendor', + '.git', + '.github', + 'tests', + '.phpunit.cache', + 'phpunit.cache', + 'phpstan.cache', + '.infection', + 'docs', + 'runtime', + 'node_modules', + '.idea', + ], + ); } /** - * @phpstan-return list + * Returns one row per path, keyed by the path. + * + * @param list $paths Relative paths. + * + * @return iterable */ - public static function prunableDirectories(): array + private static function rows(array $paths): iterable { - return [ - ['vendor'], - ['.git'], - ['.github'], - ['tests'], - ['.phpunit.cache'], - ['phpunit.cache'], - ['phpstan.cache'], - ['.infection'], - ['docs'], - ['runtime'], - ]; + foreach ($paths as $path) { + yield $path === '' ? 'empty path' : $path => [$path]; + } } } diff --git a/tests/Provider/DiffColorizerProvider.php b/tests/Provider/DiffColorizerProvider.php new file mode 100644 index 0000000..ee9debc --- /dev/null +++ b/tests/Provider/DiffColorizerProvider.php @@ -0,0 +1,57 @@ + + */ + public static function lines(): iterable + { + yield 'added line in green' => [ + self::HEADERS . '+new', + self::STYLED_HEADERS . "\e[32m+new\e[0m", + ]; + yield 'body line starting with dashes in red' => [ + self::HEADERS . '--- section marker', + self::STYLED_HEADERS . "\e[31m--- section marker\e[0m", + ]; + yield 'context line unstyled' => [ + self::HEADERS . ' context', + self::STYLED_HEADERS . ' context', + ]; + yield 'file headers in bold' => [ + self::HEADERS, + self::STYLED_HEADERS, + ]; + yield 'hunk header in cyan' => [ + self::HEADERS . '@@ -1,2 +1,2 @@', + self::STYLED_HEADERS . "\e[36m@@ -1,2 +1,2 @@\e[0m", + ]; + yield 'no newline marker unstyled' => [ + self::HEADERS . '\\ No newline at end of file', + self::STYLED_HEADERS . '\\ No newline at end of file', + ]; + yield 'removed line in red' => [ + self::HEADERS . '-old', + self::STYLED_HEADERS . "\e[31m-old\e[0m", + ]; + } +} diff --git a/tests/Provider/EventSubscriberProvider.php b/tests/Provider/EventSubscriberProvider.php new file mode 100644 index 0000000..c69dafc --- /dev/null +++ b/tests/Provider/EventSubscriberProvider.php @@ -0,0 +1,23 @@ +}> + */ + public static function autoEnabledExtra(): iterable + { + yield 'no scaffold block' => [[]]; + yield 'non-array scaffold block' => [['scaffold' => 'not-an-array']]; + yield 'explicit auto true' => [['scaffold' => ['auto' => true]]]; + } +} diff --git a/tests/Provider/FileApplierProvider.php b/tests/Provider/FileApplierProvider.php new file mode 100644 index 0000000..7510553 --- /dev/null +++ b/tests/Provider/FileApplierProvider.php @@ -0,0 +1,39 @@ + + */ + public static function rejectedMappings(): iterable + { + yield 'provider not allowed' => [ + 'output.txt', + 'stubs/output.txt', + 'php-forge/unauthorized', + Message::PACKAGE_NOT_ALLOWED->getMessage('php-forge/unauthorized'), + ]; + yield 'destination with traversal' => [ + '../../../etc/passwd', + 'stubs/output.txt', + 'p/a', + Message::PATH_TRAVERSAL->getMessage('destination', '../../../etc/passwd'), + ]; + yield 'source with traversal' => [ + 'output.txt', + '../../../etc/shadow', + 'p/a', + Message::PATH_TRAVERSAL->getMessage('source', '../../../etc/shadow'), + ]; + } +} diff --git a/tests/Provider/GlobProvider.php b/tests/Provider/GlobProvider.php new file mode 100644 index 0000000..9140581 --- /dev/null +++ b/tests/Provider/GlobProvider.php @@ -0,0 +1,87 @@ +, string, MergeStrategyKind|null}> + */ + public static function lookups(): iterable + { + yield 'exact match wins over an earlier glob' => [ + ['conf/*' => MergeStrategyKind::Text, 'conf/app.cfg' => MergeStrategyKind::Ini], + 'conf/app.cfg', + MergeStrategyKind::Ini, + ]; + yield 'first matching glob wins' => [ + ['conf/*' => MergeStrategyKind::Text, '**/*.ini' => MergeStrategyKind::Ini], + 'conf/app.ini', + MergeStrategyKind::Text, + ]; + yield 'integer-like exact key' => [ + [123 => MergeStrategyKind::Ini], + '123', + MergeStrategyKind::Ini, + ]; + yield 'integer-like path against a glob' => [ + ['12*' => MergeStrategyKind::ListFile], + '123', + MergeStrategyKind::ListFile, + ]; + yield 'no match' => [ + ['*.ini' => MergeStrategyKind::Ini], + '.gitignore', + null, + ]; + } + + /** + * @return iterable + */ + public static function matches(): iterable + { + yield 'brace alternatives accept wildcards' => ['{src,lib}/**/*.{php,phtml}', 'lib/a/b.phtml', true]; + yield 'brace alternatives reject other prefixes' => ['{src,lib}/**/*.{php,phtml}', 'docs/a.php', false]; + yield 'brace empty alternative' => ['phpunit.xml{,.dist}', 'phpunit.xml', true]; + yield 'brace first alternative' => ['*.{php,js}', 'a.php', true]; + yield 'brace group is not literal' => ['*.{php,js}', 'a.{php,js}', false]; + yield 'brace second alternative' => ['*.{php,js}', 'a.js', true]; + yield 'brace suffix alternative' => ['phpunit.xml{,.dist}', 'phpunit.xml.dist', true]; + yield 'brace unlisted alternative' => ['*.{php,js}', 'a.css', false]; + yield 'brace without comma does not expand' => ['{a}', 'a', false]; + yield 'brace without comma is literal' => ['{a}', '{a}', true]; + yield 'double star crosses separators' => ['public/**', 'public/assets/css/app.css', true]; + yield 'double star slash matches a deep path' => ['**/foo', 'a/b/c/foo', true]; + yield 'double star slash matches a root file' => ['**/.gitignore', '.gitignore', true]; + yield 'exact path matches itself' => ['config/params.php', 'config/params.php', true]; + yield 'exact path rejects another file' => ['config/params.php', 'config/web.php', false]; + yield 'lone closing brace is literal' => ['a}', 'a}', true]; + yield 'nested braces do not expand recursively' => ['{a,{b,c}}', 'a', false]; + yield 'nested braces keep the outer braces literal' => ['{a,{b,c}}', '{a,b}', true]; + yield 'question mark does not match a separator' => ['yii?', 'yii/0', false]; + yield 'question mark matches one character' => ['yii?', 'yii0', true]; + yield 'single star does not cross a separator' => ['config/*.php', 'config/nested/params.php', false]; + yield 'single star matches the same level' => ['config/*.php', 'config/params.php', true]; + yield 'unclosed brace is literal' => ['{a', '{a', true]; + } + + /** + * @return iterable + */ + public static function regexes(): iterable + { + yield 'anchors the full path' => ['config/*.php', '#^config/[^/]*\.php$#']; + yield 'brace alternatives converted inside one group' => ['{a.b,*}', '#^(?:a\.b|[^/]*)$#']; + yield 'double star slash is an optional directory chain' => ['**/foo', '#^(?:.*/)?foo$#']; + yield 'escapes punctuation' => ['file.with.dots', '#^file\.with\.dots$#']; + } +} diff --git a/tests/Provider/LinesProvider.php b/tests/Provider/LinesProvider.php new file mode 100644 index 0000000..5553507 --- /dev/null +++ b/tests/Provider/LinesProvider.php @@ -0,0 +1,36 @@ +}> + */ + public static function lines(): iterable + { + yield 'empty content' => ['', []]; + yield 'single line without terminator' => ['a', ['a']]; + yield 'terminated lines' => ["a\nb\n", ['a', 'b']]; + yield 'trailing blank line' => ["a\n\n", ['a', '']]; + } + + /** + * @return iterable}> + */ + public static function segments(): iterable + { + yield 'CR line inside an LF line' => ["a\rb\n", [['a', "\r"], ['b', "\n"]]]; + yield 'CR-only lines' => ["a\rb\r", [['a', "\r"], ['b', "\r"]]]; + yield 'CRLF lines' => ["a\r\nb\r\n", [['a', "\r\n"], ['b', "\r\n"]]]; + yield 'empty content' => ['', []]; + yield 'LF lines without final terminator' => ["a\nb", [['a', "\n"], ['b', '']]]; + } +} diff --git a/tests/Provider/LockFileProvider.php b/tests/Provider/LockFileProvider.php new file mode 100644 index 0000000..ad24d81 --- /dev/null +++ b/tests/Provider/LockFileProvider.php @@ -0,0 +1,37 @@ + + */ + public static function invalidContents(): iterable + { + yield 'conflict marker inside a line' => [ + "{\"files\": \"a=======b\" invalid}\n", + Message::LOCK_INVALID_JSON->getMessage('{path}', 'Syntax error'), + ]; + yield 'Git conflict markers' => [ + "{\n<<<<<<< HEAD\n \"files\": {}\n=======\n \"files\": []\n>>>>>>> feature\n}\n", + Message::LOCK_CONFLICT_MARKERS->getMessage('{path}', 'Syntax error'), + ]; + yield 'JSON scalar' => [ + '"just a string"', + Message::LOCK_NOT_OBJECT->getMessage('{path}'), + ]; + yield 'malformed JSON' => [ + '{ invalid json }', + Message::LOCK_INVALID_JSON->getMessage('{path}', 'Syntax error'), + ]; + } +} diff --git a/tests/Provider/ManifestExpanderProvider.php b/tests/Provider/ManifestExpanderProvider.php new file mode 100644 index 0000000..18edc09 --- /dev/null +++ b/tests/Provider/ManifestExpanderProvider.php @@ -0,0 +1,187 @@ +, + * list, + * array, + * array, + * array{mode: array, merge: array}, + * }> + */ + public static function attributes(): iterable + { + yield 'merge strategy by exact path, then glob, then null' => [ + ['files/.editorconfig', 'files/conf/app.cfg', 'files/conf/db.cfg', 'files/.gitignore'], + [['from' => 'files', 'to' => '.']], + [], + [ + 'conf/*' => MergeStrategyKind::Text, + 'conf/app.cfg' => MergeStrategyKind::Ini, + '.editorconfig' => MergeStrategyKind::ListFile, + ], + [ + 'mode' => [ + '.editorconfig' => FileMode::Replace, + '.gitignore' => FileMode::Replace, + 'conf/app.cfg' => FileMode::Replace, + 'conf/db.cfg' => FileMode::Replace, + ], + 'merge' => [ + '.editorconfig' => MergeStrategyKind::ListFile, + '.gitignore' => null, + 'conf/app.cfg' => MergeStrategyKind::Ini, + 'conf/db.cfg' => MergeStrategyKind::Text, + ], + ], + ]; + yield 'mode by exact path declared after a matching glob' => [ + ['config/params.php'], + ['config/params.php'], + ['config/*.php' => FileMode::Preserve, 'config/params.php' => FileMode::Replace], + [], + ['mode' => ['config/params.php' => FileMode::Replace], 'merge' => ['config/params.php' => null]], + ]; + yield 'mode by exact path, then glob, then replace' => [ + ['config/web.php', 'config/params.php', 'src/controllers/SiteController.php'], + ['config', 'src'], + ['config/params.php' => FileMode::Preserve, 'config/*.php' => FileMode::Append], + [], + [ + 'mode' => [ + 'config/params.php' => FileMode::Preserve, + 'config/web.php' => FileMode::Append, + 'src/controllers/SiteController.php' => FileMode::Replace, + ], + 'merge' => [ + 'config/params.php' => null, + 'config/web.php' => null, + 'src/controllers/SiteController.php' => null, + ], + ], + ]; + } + + /** + * @return iterable, + * list, + * list, + * array, + * }> + */ + public static function copyLists(): iterable + { + yield 'default excludes in a walk of the root' => [ + ['src/controllers/SiteController.php', 'src/tests/SomeTest.php', 'composer.json', 'runtime/cache/x.log'], + ['.'], + [], + [ + 'src/controllers/SiteController.php' => 'src/controllers/SiteController.php', + 'src/tests/SomeTest.php' => 'src/tests/SomeTest.php', + ], + ]; + yield 'directory entry with a trailing separator and an exclude' => [ + ['config/keep.txt', 'config/skip.txt'], + ['config/'], + ['config/skip.txt'], + ['config/keep.txt' => 'config/keep.txt'], + ]; + yield 'directory entry with a from-to remap' => [ + ['metadata/.github/linters/actionlint.yml', 'metadata/.github/linters/.markdown-lint.yml'], + [['from' => 'metadata/.github', 'to' => '.github']], + [], + [ + '.github/linters/.markdown-lint.yml' => 'metadata/.github/linters/.markdown-lint.yml', + '.github/linters/actionlint.yml' => 'metadata/.github/linters/actionlint.yml', + ], + ]; + yield 'every file of a directory entry' => [ + ['src/controllers/SiteController.php', 'src/models/User.php'], + ['src'], + [], + [ + 'src/controllers/SiteController.php' => 'src/controllers/SiteController.php', + 'src/models/User.php' => 'src/models/User.php', + ], + ]; + yield 'exclude glob matching several files' => [ + ['src/a.txt', 'src/b.txt', 'src/c.php'], + ['src'], + ['src/*.txt'], + ['src/c.php' => 'src/c.php'], + ]; + yield 'explicit file under a default-excluded directory' => [ + ['runtime/.gitignore'], + ['runtime/.gitignore'], + [], + ['runtime/.gitignore' => 'runtime/.gitignore'], + ]; + yield 'file entry before a walk that reaches it again' => [ + ['a.php', 'b.php', 'c.php'], + ['a.php', '.'], + [], + ['a.php' => 'a.php', 'b.php' => 'b.php', 'c.php' => 'c.php'], + ]; + yield 'file entry with a from-to remap' => [ + ['metadata/.editorconfig'], + [['from' => 'metadata/.editorconfig', 'to' => '.editorconfig']], + [], + ['.editorconfig' => 'metadata/.editorconfig'], + ]; + yield 'file named like an excluded directory' => [ + ['secrets', 'vault/secrets/key.txt'], + ['.'], + ['secrets/**', 'vault/secrets/**'], + ['secrets' => 'secrets'], + ]; + yield 'file reached by a file and a directory entry' => [['yii'], ['yii', '.'], [], ['yii' => 'yii']]; + yield 'later entry overrides an earlier one in place' => [ + ['first/app.php', 'second/app.php', 'dir/app.php', 'dir/other.php'], + [ + ['from' => 'first/app.php', 'to' => 'app.php'], + ['from' => 'dir', 'to' => '.'], + ['from' => 'second/app.php', 'to' => 'app.php'], + ], + [], + ['app.php' => 'second/app.php', 'other.php' => 'dir/other.php'], + ]; + yield 'next directory entry after a walk' => [ + ['dir1/a.txt', 'dir2/b.txt'], + ['dir1', 'dir2'], + [], + ['dir1/a.txt' => 'dir1/a.txt', 'dir2/b.txt' => 'dir2/b.txt'], + ]; + yield 'repeated file entry' => [ + ['yii', 'other.txt'], + ['yii', 'yii', 'other.txt'], + [], + ['yii' => 'yii', 'other.txt' => 'other.txt'], + ]; + yield 'user exclude on top of the defaults' => [ + ['src/controllers/SiteController.php', 'src/controllers/Disabled.php'], + ['src'], + ['src/controllers/Disabled.php'], + ['src/controllers/SiteController.php' => 'src/controllers/SiteController.php'], + ]; + yield 'walk results in sorted order' => [ + ['mmm.php', 'zzz.php', 'aaa.php'], + ['.'], + [], + ['aaa.php' => 'aaa.php', 'mmm.php' => 'mmm.php', 'zzz.php' => 'zzz.php'], + ]; + } +} diff --git a/tests/Provider/ManifestLoaderProvider.php b/tests/Provider/ManifestLoaderProvider.php new file mode 100644 index 0000000..935e4ff --- /dev/null +++ b/tests/Provider/ManifestLoaderProvider.php @@ -0,0 +1,70 @@ +, Message|string}> + */ + public static function decodeFailures(): iterable + { + yield 'composer.json invalid JSON' => [ + 'composer.json', '{broken', + JsonException::class, + 'Syntax error', + ]; + yield 'composer.json missing' => [ + 'composer.json', + null, + RuntimeException::class, + Message::MANIFEST_PROVIDER_FILE_NOT_FOUND, + ]; + yield 'composer.json not an object' => [ + 'composer.json', + '3', + RuntimeException::class, + Message::MANIFEST_PROVIDER_FILE_NOT_OBJECT, + ]; + yield 'manifest file invalid JSON' => [ + 'manifest file', + '{ not valid json ', + JsonException::class, + 'Syntax error', + ]; + yield 'manifest file missing' => [ + 'manifest file', + null, + RuntimeException::class, + Message::MANIFEST_PROVIDER_FILE_NOT_FOUND, + ]; + yield 'manifest file not an object' => [ + 'manifest file', + '"just-a-string"', + RuntimeException::class, + Message::MANIFEST_PROVIDER_FILE_NOT_OBJECT, + ]; + } + + /** + * @return iterable + */ + public static function invalidReferences(): iterable + { + yield 'absolute path' => ['/etc/malicious.json', Message::MANIFEST_REFERENCE_NOT_RELATIVE]; + yield 'empty string' => ['', Message::MANIFEST_REFERENCE_EMPTY]; + yield 'not a string' => [42, Message::MANIFEST_REFERENCE_EMPTY]; + yield 'traversal' => ['../escape.json', Message::MANIFEST_REFERENCE_NOT_RELATIVE]; + } +} diff --git a/tests/Provider/ManifestSchemaProvider.php b/tests/Provider/ManifestSchemaProvider.php new file mode 100644 index 0000000..2bf877c --- /dev/null +++ b/tests/Provider/ManifestSchemaProvider.php @@ -0,0 +1,288 @@ +, bool, string}> + */ + public static function invalidManifests(): iterable + { + $external = 'copy, exclude, merge, modes'; + $inline = 'allowed-packages, auto, copy, exclude, manifest, merge, modes'; + + yield 'consumer key in manifest body' => [ + ['copy' => ['src'], 'auto' => false], + false, + Message::MANIFEST_KEY_UNKNOWN->getMessage('auto', $external), + ]; + yield 'excludes typo' => [ + ['copy' => ['src'], 'excludes' => ['a']], + false, + Message::MANIFEST_KEY_UNKNOWN->getMessage('excludes', $external), + ]; + yield 'integer-like unknown key' => [ + ['copy' => ['src'], 0 => 'x'], + false, + Message::MANIFEST_KEY_UNKNOWN->getMessage('0', $external), + ]; + yield 'legacy file-mapping' => [ + ['copy' => ['src'], 'file-mapping' => []], + false, + Message::MANIFEST_KEY_UNKNOWN->getMessage('file-mapping', $external), + ]; + yield 'mode typo' => [ + ['copy' => ['src'], 'mode' => ['a' => 'append']], + false, + Message::MANIFEST_KEY_UNKNOWN->getMessage('mode', $external), + ]; + yield 'unknown key in inline block' => [ + ['copy' => ['src'], 'allowed-package' => []], + true, + Message::MANIFEST_KEY_UNKNOWN->getMessage('allowed-package', $inline), + ]; + yield 'copy absolute entry' => [ + ['copy' => ['/etc']], + false, + Message::MANIFEST_ENTRY_ABSOLUTE->getMessage('copy', '/etc'), + ]; + yield 'copy absolute to' => [ + ['copy' => [['from' => 'metadata/foo', 'to' => '/etc/foo']]], + false, + Message::MANIFEST_ENTRY_ABSOLUTE->getMessage('copy.to', '/etc/foo'), + ]; + yield 'copy associative object' => [ + ['copy' => ['from' => 'metadata/.gitignore', 'to' => '.gitignore']], + false, + Message::MANIFEST_COPY_NOT_LIST->getMessage(), + ]; + yield 'copy empty entry' => [ + ['copy' => ['']], + false, + Message::MANIFEST_ENTRY_EMPTY->getMessage('copy'), + ]; + yield 'copy empty list' => [ + ['copy' => []], + false, + Message::MANIFEST_COPY_EMPTY->getMessage(), + ]; + yield 'copy entry neither string nor object' => [ + ['copy' => [42]], + false, + Message::MANIFEST_COPY_ENTRY_INVALID->getMessage(), + ]; + yield 'copy from traversal' => [ + ['copy' => [['from' => '../escape', 'to' => 'escape']]], + false, + Message::MANIFEST_ENTRY_TRAVERSAL->getMessage('copy.from', '../escape'), + ]; + yield 'copy missing' => [ + [], + false, + Message::MANIFEST_COPY_MISSING->getMessage(), + ]; + yield 'copy not array' => [ + ['copy' => 'src'], + false, + Message::MANIFEST_COPY_MISSING->getMessage(), + ]; + yield 'copy traversal entry' => [ + ['copy' => ['../escape']], + false, + Message::MANIFEST_ENTRY_TRAVERSAL->getMessage('copy', '../escape'), + ]; + yield 'exclude not array' => [ + ['copy' => ['src'], 'exclude' => 'not-an-array'], + false, + Message::MANIFEST_EXCLUDE_NOT_ARRAY->getMessage(), + ]; + yield 'exclude traversal entry' => [ + ['copy' => ['src'], 'exclude' => ['../bad']], + false, + Message::MANIFEST_ENTRY_TRAVERSAL->getMessage('exclude', '../bad'), + ]; + yield 'merge list' => [ + ['copy' => ['src'], 'merge' => ['ini']], + false, + Message::MANIFEST_MAP_NOT_OBJECT->getMessage('merge'), + ]; + yield 'merge scalar' => [ + ['copy' => ['src'], 'merge' => 'ini'], + false, + Message::MANIFEST_MAP_NOT_OBJECT->getMessage('merge'), + ]; + yield 'merge traversal pattern' => [ + ['copy' => ['src'], 'merge' => ['../.gitignore' => 'list']], + false, + Message::MANIFEST_ENTRY_TRAVERSAL->getMessage('merge', '../.gitignore'), + ]; + yield 'merge unknown strategy' => [ + ['copy' => ['src'], 'merge' => ['.editorconfig' => 'yaml']], + false, + Message::MANIFEST_MAP_VALUE_INVALID->getMessage( + 'merge', + '.editorconfig', + 'strategy', + 'yaml', + 'ini, list, text', + ), + ]; + yield 'merge value not string' => [ + ['copy' => ['src'], 'merge' => ['.gitignore' => ['list']]], + false, + Message::MANIFEST_MAP_VALUE_NOT_STRING->getMessage('merge', '.gitignore'), + ]; + yield 'modes empty pattern' => [ + ['copy' => ['src'], 'modes' => ['' => 'preserve']], + false, + Message::MANIFEST_ENTRY_EMPTY->getMessage('modes'), + ]; + yield 'modes scalar' => [ + ['copy' => ['src'], 'modes' => 'invalid'], + false, + Message::MANIFEST_MAP_NOT_OBJECT->getMessage('modes'), + ]; + yield 'modes traversal pattern' => [ + ['copy' => ['src'], 'modes' => ['../escape' => 'preserve']], + false, + Message::MANIFEST_ENTRY_TRAVERSAL->getMessage('modes', '../escape'), + ]; + yield 'modes unknown mode' => [ + ['copy' => ['src'], 'modes' => ['config/*.php' => 'unknown-mode']], + false, + Message::MANIFEST_MAP_VALUE_INVALID->getMessage( + 'modes', + 'config/*.php', + 'mode', + 'unknown-mode', + 'append, prepend, preserve, replace', + ), + ]; + yield 'modes value not string' => [ + ['copy' => ['src'], 'modes' => ['config/*.php' => 123]], + false, + Message::MANIFEST_MAP_VALUE_NOT_STRING->getMessage('modes', 'config/*.php'), + ]; + } + + /** + * @return iterable, bool, array}> + */ + public static function validManifests(): iterable + { + yield 'backslash separators' => [ + ['copy' => ['config\\web.php', ['from' => 'stubs\\app\\.env', 'to' => 'app\\.env']]], + false, + self::validated( + [ + ['from' => 'config/web.php', 'to' => 'config/web.php'], + ['from' => 'stubs/app/.env', 'to' => 'app/.env'], + ], + ), + ]; + yield 'colon past the drive-letter position' => [ + ['copy' => ['some/module:file.php']], + false, + self::validated([['from' => 'some/module:file.php', 'to' => 'some/module:file.php']]), + ]; + yield 'consumer keys in inline block' => [ + ['copy' => ['src'], 'manifest' => 'x.json', 'allowed-packages' => [], 'auto' => false], + true, + self::validated([['from' => 'src', 'to' => 'src']]), + ]; + yield 'empty merge object' => [ + ['copy' => ['src'], 'merge' => []], + false, + self::validated([['from' => 'src', 'to' => 'src']]), + ]; + yield 'every exclude entry' => [ + ['copy' => ['src'], 'exclude' => ['first.php', 'second.php', 'third.php']], + false, + self::validated([['from' => 'src', 'to' => 'src']], ['first.php', 'second.php', 'third.php']), + ]; + yield 'every mode' => [ + [ + 'copy' => ['src'], + 'modes' => [ + 'replace.php' => 'replace', + 'preserve.php' => 'preserve', + 'append.txt' => 'append', + 'prepend.txt' => 'prepend', + ], + ], + false, + self::validated( + [['from' => 'src', 'to' => 'src']], + modes: [ + 'replace.php' => FileMode::Replace, + 'preserve.php' => FileMode::Preserve, + 'append.txt' => FileMode::Append, + 'prepend.txt' => FileMode::Prepend, + ], + ), + ]; + yield 'from-to entries' => [ + [ + 'copy' => [ + ['from' => 'metadata/.editorconfig', 'to' => '.editorconfig'], + ['from' => 'metadata/.gitignore', 'to' => '.gitignore'], + ], + ], + false, + self::validated( + [ + ['from' => 'metadata/.editorconfig', 'to' => '.editorconfig'], + ['from' => 'metadata/.gitignore', 'to' => '.gitignore'], + ], + ), + ]; + yield 'integer-like mode pattern' => [ + ['copy' => ['123'], 'modes' => ['123' => 'preserve']], + false, + self::validated([['from' => '123', 'to' => '123']], modes: [123 => FileMode::Preserve]), + ]; + yield 'merge strategies' => [ + ['copy' => ['src'], 'merge' => ['.editorconfig' => 'ini', '**/.*ignore' => 'list', '123' => 'text']], + false, + self::validated( + [['from' => 'src', 'to' => 'src']], + merge: [ + '.editorconfig' => MergeStrategyKind::Ini, + '**/.*ignore' => MergeStrategyKind::ListFile, + 123 => MergeStrategyKind::Text, + ], + ), + ]; + yield 'minimal manifest' => [ + ['copy' => ['src', 'config']], + false, + self::validated([['from' => 'src', 'to' => 'src'], ['from' => 'config', 'to' => 'config']]), + ]; + } + + /** + * Returns the validated structure of a manifest. + * + * @param list $copy Normalised `copy` entries. + * @param list $exclude `exclude` patterns. + * @param array $modes Resolved `modes` map. + * @param array $merge Resolved `merge` map. + * + * @return array Validated manifest. + */ + private static function validated(array $copy, array $exclude = [], array $modes = [], array $merge = []): array + { + return ['copy' => $copy, 'exclude' => $exclude, 'modes' => $modes, 'merge' => $merge]; + } +} diff --git a/tests/Provider/MergeStrategyProvider.php b/tests/Provider/MergeStrategyProvider.php new file mode 100644 index 0000000..b80cf8c --- /dev/null +++ b/tests/Provider/MergeStrategyProvider.php @@ -0,0 +1,519 @@ + + */ + public static function iniCases(): iterable + { + $provider = self::fixture('ini/provider.txt'); + + $cases = [ + 'php-forge/scaffold (brace section, unset value)' => [ + $provider, + self::fixture('ini/consumer-scaffold.txt'), + self::fixture('ini/consumer-scaffold.expected.txt'), + ], + 'consumer identical to provider' => [ + $provider, + $provider, + $provider, + ], + 'yii2-extensions/app-inertia-react (five sections missing)' => [ + $provider, + self::fixture('ini/consumer-app-inertia-react.txt'), + self::fixture('ini/consumer-app-inertia-react.expected.txt'), + ], + 'custom indent_size and custom section' => [ + $provider, + self::fixture('ini/consumer-custom-sections.txt'), + self::fixture('ini/consumer-custom-sections.expected.txt'), + ], + ]; + + yield from $cases; + yield from self::crlfVariants($cases); + yield 'empty consumer' => [ + $provider, + '', + $provider, + ]; + yield 'first preamble occurrence of a duplicated key wins' => [ + "a = 1\na = 2\n\n[*]\n", + "[*]\n", + "a = 1\n\n[*]\n", + ]; + yield 'first section occurrence of a duplicated key wins' => [ + "[*]\na = 1\na = 2\n", + "[*]\n", + "[*]\na = 1\n", + ]; + yield 'missing key lands in the first occurrence of a duplicated section' => [ + "[*]\na = 1\nb = 2\nc = 3\n", + "[*]\na = 1\n\n[*.md]\nx = 1\n\n[*]\nb = 2\n", + "[*]\na = 1\nc = 3\n\n[*.md]\nx = 1\n\n[*]\nb = 2\n", + ]; + yield 'numeric key present in the consumer section is kept' => [ + "[numbers]\n2 = provider\n", + "[numbers]\n1 = one\n\n[numbers]\n2 = consumer\n", + "[numbers]\n1 = one\n\n[numbers]\n2 = consumer\n", + ]; + yield 'header with a trailing semicolon comment keeps its consumer values' => [ + "[numbers]\nsize = 2\n", + "[numbers] ; local settings\nsize = 4\n", + "[numbers] ; local settings\nsize = 4\n", + ]; + yield 'missing key lands in a section whose header has a trailing hash comment' => [ + "[numbers]\nsize = 2\nmode = x\n", + "[numbers]# local\nsize = 4\n", + "[numbers]# local\nsize = 4\nmode = x\n", + ]; + yield 'appended section keeps the trailing comment of its header' => [ + "[*.md] ; docs\nb = 2\n", + "[*]\n", + "[*]\n\n[*.md] ; docs\nb = 2\n", + ]; + yield 'text after a closing bracket that is no comment makes no header' => [ + "[a] x\nk = 1\n", + "root = true\n", + "root = true\nk = 1\n", + ]; + yield 'comment lead travels with its appended section' => [ + "[*]\na = 1\n\n# Markdown\n[*.md]\nb = 2\n", + "[*]\na = 1\n", + "[*]\na = 1\n\n# Markdown\n[*.md]\nb = 2\n", + ]; + yield 'comment on the first provider line leads the first section' => [ + "# c\n[*.md]\nb = 1\n", + "[*]\n", + "[*]\n\n# c\n[*.md]\nb = 1\n", + ]; + yield 'indented comment counts as a lead line' => [ + " # lead\n[*.md]\nb = 1\n", + "[*]\n", + "[*]\n\n # lead\n[*.md]\nb = 1\n", + ]; + yield 'lead of a middle section moves with it' => [ + "[a]\nx = 1\n# lead b\n[b]\ny = 1\n[c]\nz = 1\n", + "root = true\n", + "root = true\n\n[a]\nx = 1\n\n# lead b\n[b]\ny = 1\n\n[c]\nz = 1\n", + ]; + yield 'comment right after a header leads the next section' => [ + "[a]\n# lead b\n[b]\ny = 1\n", + "root = true\n", + "root = true\n\n[a]\n\n# lead b\n[b]\ny = 1\n", + ]; + yield 'section after a repeated provider section is still appended' => [ + "[*.md]\na = 1\n\n[*.md]\nb = 2\n\n[*.js]\nc = 3\n", + "root = true\n", + "root = true\n\n[*.md]\na = 1\nb = 2\n\n[*.js]\nc = 3\n", + ]; + yield 'second provider occurrence adds only its new keys' => [ + "[*.md]\na = 1\n\n[*.md]\na = 9\nb = 2\n", + "root = true\n", + "root = true\n\n[*.md]\na = 1\nb = 2\n", + ]; + yield 'comment holding an equals sign is no key' => [ + "[*]\n# a = 1\n", + "[*]\n", + "[*]\n", + ]; + yield 'indented comment holding an equals sign is no key' => [ + "[*]\n # a = 1\n", + "[*]\n", + "[*]\n", + ]; + yield 'only key lines are inserted' => [ + "[*]\n; comment\nno-equals\n= x\na = 1\n", + "[*]\n", + "[*]\na = 1\n", + ]; + yield 'key right after the header of a keyless consumer section' => [ + "[*]\na = 1\n", + "[*]\n# note\n\n[*.md]\nb = 2\n", + "[*]\na = 1\n# note\n\n[*.md]\nb = 2\n", + ]; + yield 'key after the last consumer key of its section' => [ + "[*]\nc = 3\n", + "[*]\na = 1\nb = 2\n", + "[*]\na = 1\nb = 2\nc = 3\n", + ]; + yield 'preamble key after the last consumer preamble key' => [ + "root = true\nfoo = bar\n\n[*]\n", + "# c\nroot = false\n\n[*]\n", + "# c\nroot = false\nfoo = bar\n\n[*]\n", + ]; + yield 'preamble key at the top, separated from the first section' => [ + "root = true\n\n[*]\na = 1\n", + "[*]\na = 1\n", + "root = true\n\n[*]\na = 1\n", + ]; + yield 'preamble key at the top of a keyless consumer preamble' => [ + "root = true\n", + "# editorconfig.org\n\n[*]\n", + "root = true\n# editorconfig.org\n\n[*]\n", + ]; + yield 'inserted preamble key is trimmed' => [ + " root = true\n\n[*]\n", + "[*]\n", + "root = true\n\n[*]\n", + ]; + yield 'empty provider' => ['', "[*]\nb = 2\n", "[*]\nb = 2\n"]; + yield 'key differing only in case keeps the consumer value' => [ + "[*]\nindent_size = 4\n", + "[*]\nINDENT_SIZE = 2\n", + "[*]\nINDENT_SIZE = 2\n", + ]; + yield 'key names are trimmed' => [ + "[*]\na=1\n", + "[*]\na = 2\n", + "[*]\na = 2\n", + ]; + yield 'indented header is the same section' => [ + "[*.md]\nb = 2\n", + " [*.md]\nb = 2\n", + " [*.md]\nb = 2\n", + ]; + yield 'no trailing newline on either side' => [ + "[*]\na = 1", + "[*]\nb = 2", + "[*]\nb = 2\na = 1", + ]; + yield 'value ending in a bracket stays a key' => [ + "[*]\nlist = [a]\n", + "[*]\n", + "[*]\nlist = [a]\n", + ]; + yield 'line starting with a bracket stays a key' => [ + "[*]\n[a]b = 1\n", + "[*]\n", + "[*]\n[a]b = 1\n", + ]; + yield 'CR-only consumer' => [ + "[*]\na = 1\n", + "[*]\rb = 2\r", + "[*]\rb = 2\ra = 1\r", + ]; + yield 'whitespace-only lines ending an appended section are dropped' => [ + "[a]\nx=1\n \n[b]\ny=2\n", + "[c]\nz=3\n", + "[c]\nz=3\n\n[a]\nx=1\n\n[b]\ny=2\n", + ]; + yield 'consumer unset value wins and a missing section is appended whole' => [ + "[*.md]\nindent_size = 2\ntrim_trailing_whitespace = false\n\n[*.js]\nindent_size = 2\n", + "[*.md]\nindent_size = unset\n", + "[*.md]\nindent_size = unset\ntrim_trailing_whitespace = false\n\n[*.js]\nindent_size = 2\n", + ]; + } + + /** + * @return iterable + */ + public static function listCases(): iterable + { + $v1 = self::fixture('list/provider-v1.txt'); + $v2 = self::fixture('list/provider-v2.txt'); + + $cases = [ + 'php-forge/scaffold (custom headers, negation) with v1' => [ + $v1, + self::fixture('list/consumer-scaffold.txt'), + self::fixture('list/consumer-scaffold.v1.expected.txt'), + ], + 'php-forge/scaffold (custom headers, negation) with v2' => [ + $v2, + self::fixture('list/consumer-scaffold.txt'), + self::fixture('list/consumer-scaffold.v2.expected.txt'), + ], + 'consumer identical to v1' => [ + $v1, + $v1, + $v1, + ], + 'consumer identical to v1 with v2' => [ + $v2, + $v1, + $v2, + ], + 'every entry present in a different order' => [ + $v1, + self::fixture('list/consumer-reordered.txt'), + self::fixture('list/consumer-reordered.txt'), + ], + ]; + + yield from $cases; + yield from self::crlfVariants($cases); + yield 'no trailing newline with v1' => [ + $v1, + rtrim($v1, "\n"), + rtrim($v1, "\n"), + ]; + yield 'no trailing newline with v2' => [ + $v2, + rtrim($v1, "\n"), + $v2, + ]; + yield 'empty consumer' => [ + $v1, + '', + $v1, + ]; + // Known limitation: the appended '*.log' follows the consumer '!keep.log', and since the last matching rule + // wins, 'keep.log' becomes ignored again. The merge does not reorder consumer rules. + yield 'entry appended after a consumer negation' => [ + "# logs\n*.log\n", + "build\n!keep.log\n", + "build\n!keep.log\n\n# logs\n*.log\n", + ]; + yield 'group without comment appended as entries only' => [ + "a\n\nb\nc\n", + "a\n", + "a\n\nb\nc\n", + ]; + yield 'every uncommented group appended' => [ + "a\n\nb\n", + "x\n", + "x\n\na\n\nb\n", + ]; + yield 'entry repeated in the provider added once' => [ + "# one\nx\n\n# two\nx\ny\n", + "z\n", + "z\n\n# one\nx\n\n# two\ny\n", + ]; + yield 'entry after the matching comment header without entries' => [ + "# cache\n.cache\n", + "# cache\n# (if present)\n\nother\n", + "# cache\n# (if present)\n.cache\n\nother\n", + ]; + yield 'entry after the entries below a multi-line comment' => [ + "# vendor\nvendor\ncomposer.lock\n", + "# vendor\n# more\nvendor\n", + "# vendor\n# more\nvendor\ncomposer.lock\n", + ]; + yield 'entry stays inside the matching group' => [ + "# tools\n.idea\n.vscode\n", + "# tools\n.idea\n# other\nfoo\n", + "# tools\n.idea\n.vscode\n# other\nfoo\n", + ]; + yield 'comment after entries starts a new provider group' => [ + "# a\nx\nnew-x\n# b\ny\n", + "# a\nx\n\n# b\ny\n", + "# a\nx\nnew-x\n\n# b\ny\n", + ]; + yield 'CR-only consumer' => [ + "# b\nb\n", + "a\r", + "a\r\r# b\rb\r", + ]; + yield 'consumer entry with surrounding spaces is present' => [ + "x\n", + " x \n", + " x \n", + ]; + yield 'provider entry with surrounding spaces is trimmed' => [ + " x \n", + "x\n", + "x\n", + ]; + yield 'provider header with trailing spaces matches the consumer header' => [ + "# cache \n.cache\n", + "# cache\nother\n", + "# cache\nother\n.cache\n", + ]; + yield 'consumer header with trailing spaces matches the provider header' => [ + "# cache\n.cache\n", + "# cache \nother\n", + "# cache \nother\n.cache\n", + ]; + yield 'whitespace-only consumer line ends the matching group' => [ + "# cache\n.cache\n", + "# cache\nfoo\n \nbar\n", + "# cache\nfoo\n.cache\n \nbar\n", + ]; + yield 'consecutive provider comments head one group' => [ + "# a\n# b\nx\n", + "y\n", + "y\n\n# a\n# b\nx\n", + ]; + yield 'differing comments alone change nothing' => [ + "# Local AI agent config (if present)\n.claude\n", + "# AI agents\n.claude\n", + "# AI agents\n.claude\n", + ]; + } + + /** + * @return iterable + */ + public static function textCases(): iterable + { + $provider = self::fixture('text/provider.txt'); + + $cases = [ + 'env-like file' => [ + $provider, + self::fixture('text/consumer.txt'), + self::fixture('text/consumer.expected.txt'), + ], + ]; + + yield from $cases; + yield from self::crlfVariants($cases); + yield 'empty consumer' => [ + $provider, + '', + $provider, + ]; + yield 'existing trailing blank line serves as the separator' => [ + "b\n", + "a\n\n", + "a\n\nb\n", + ]; + yield 'trailing whitespace is ignored' => [ + "alpha \n", + "alpha\n", + "alpha\n", + ]; + yield 'consumer trailing whitespace is ignored' => [ + "alpha\n", + "alpha \n", + "alpha \n", + ]; + yield 'leading whitespace is significant' => [ + " alpha\n", + "alpha\n", + "alpha\n\n alpha\n", + ]; + yield 'no trailing newline on either side' => [ + 'b', + 'a', + "a\n\nb", + ]; + yield 'blank provider lines are not content' => [ + "a\n\n\nb\n", + "a\n", + "a\n\nb\n", + ]; + yield 'consumer without trailing newline is terminated' => [ + "b\n", + 'a', + "a\n\nb\n", + ]; + yield 'shared line terminated before the appended block' => [ + "alpha\nbeta\n", + 'alpha', + "alpha\n\nbeta\n", + ]; + yield 'only missing lines appended' => [ + "alpha\nbeta\ngamma\n", + "alpha\nbeta\n", + "alpha\nbeta\n\ngamma\n", + ]; + yield 'missing line appended' => [ + "alpha\nbeta\n", + "alpha\n", + "alpha\n\nbeta\n", + ]; + yield 'consumer additions kept' => [ + "alpha\nbeta\n", + "alpha\nproject-specific-line\n", + "alpha\nproject-specific-line\n\nbeta\n", + ]; + yield 'CR-only consumer' => [ + "alpha\nbeta\n", + "alpha\r", + "alpha\r\rbeta\r", + ]; + yield 'mixed line endings kept, appended lines use the dominant one' => [ + "alpha\ngamma\nbeta\n", + "alpha\nbeta\r\n", + "alpha\nbeta\r\n\r\ngamma\r\n", + ]; + yield 'empty provider' => [ + '', + "alpha\n", + "alpha\n", + ]; + yield 'consumer differing only by the final newline' => [ + "alpha\n", + 'alpha', + 'alpha', + ]; + yield 'provider ending with a blank line' => [ + "alpha\n\n", + '', + "alpha\n\n", + ]; + yield 'CRLF consumer holding every provider line' => [ + "alpha\nbeta\n", + "alpha\r\nbeta\r\n", + "alpha\r\nbeta\r\n", + ]; + yield 'consumer holding every provider line and more' => [ + "alpha\nbeta\n", + "alpha\nbeta\ngamma\n", + "alpha\nbeta\ngamma\n", + ]; + yield 'provider lines in a different order' => [ + "alpha\nbeta\n", + "beta\nalpha\n", + "beta\nalpha\n", + ]; + } + + /** + * Returns the cases with consumer and expected output converted to CRLF; the provider stays LF. + * + * @param array $cases Cases to convert. + * + * @return iterable Converted cases keyed with a ` (CRLF)` suffix. + */ + private static function crlfVariants(array $cases): iterable + { + foreach ($cases as $name => [$provider, $consumer, $expected]) { + yield "{$name} (CRLF)" => [ + $provider, + str_replace("\n", "\r\n", $consumer), + str_replace("\n", "\r\n", $expected), + ]; + } + } + + /** + * Reads a fixture file from `tests/Fixtures/merge`. + * + * @param string $path Path relative to `tests/Fixtures/merge`. + * + * @throws RuntimeException if the fixture cannot be read. + * + * @return string Fixture content. + */ + private static function fixture(string $path): string + { + $content = file_get_contents(__DIR__ . '/../Fixtures/merge/' . $path); + + if ($content === false) { + throw new RuntimeException(sprintf('Could not read merge fixture "%s".', $path)); + } + + return $content; + } +} diff --git a/tests/Provider/MessageProvider.php b/tests/Provider/MessageProvider.php new file mode 100644 index 0000000..c61051a --- /dev/null +++ b/tests/Provider/MessageProvider.php @@ -0,0 +1,300 @@ +, string}> + */ + public static function cases(): array + { + return [ + 'CONFIG_MANIFEST_INVALID_JSON' => [ + Message::CONFIG_MANIFEST_INVALID_JSON, + ['/project/composer.json', 'Syntax error'], + 'Project manifest "/project/composer.json" is not valid JSON: Syntax error.', + ], + 'CONFIG_MANIFEST_NOT_FOUND' => [ + Message::CONFIG_MANIFEST_NOT_FOUND, + ['/project/composer.json'], + 'Project manifest "/project/composer.json" not found.', + ], + 'CONFIG_MANIFEST_NOT_OBJECT' => [ + Message::CONFIG_MANIFEST_NOT_OBJECT, + ['/project/composer.json'], + 'Project manifest "/project/composer.json" does not contain a JSON object.', + ], + 'CONFIG_MANIFEST_UNREADABLE' => [ + Message::CONFIG_MANIFEST_UNREADABLE, + ['/project/composer.json'], + 'Could not read project manifest "/project/composer.json".', + ], + 'FILESYSTEM_FAILED' => [ + Message::FILESYSTEM_FAILED, + ['Could not read "/project/a.txt".', 'file_get_contents(/project/a.txt): Failed to open stream'], + 'Could not read "/project/a.txt". Reason: file_get_contents(/project/a.txt): Failed to open stream.', + ], + 'LOCK_CONFLICT_MARKERS' => [ + Message::LOCK_CONFLICT_MARKERS, + ['/project/scaffold-lock.json', 'Syntax error'], + 'Lock file "/project/scaffold-lock.json" contains Git conflict markers and is not valid JSON ' + . '(Syntax error). Resolve the merge conflict and run the command again.', + ], + 'LOCK_ENCODE_FAILED' => [ + Message::LOCK_ENCODE_FAILED, + ['/project/scaffold-lock.json', 'Malformed UTF-8 characters, possibly incorrectly encoded'], + 'Could not encode lock file "/project/scaffold-lock.json": Malformed UTF-8 characters, possibly ' + . 'incorrectly encoded.', + ], + 'LOCK_HASH_FAILED' => [ + Message::LOCK_HASH_FAILED, + ['/project/a.txt'], + 'Could not hash file "/project/a.txt".', + ], + 'LOCK_INVALID_JSON' => [ + Message::LOCK_INVALID_JSON, + ['/project/scaffold-lock.json', 'Syntax error'], + 'Lock file "/project/scaffold-lock.json" is not valid JSON: Syntax error.', + ], + 'LOCK_NOT_OBJECT' => [ + Message::LOCK_NOT_OBJECT, + ['/project/scaffold-lock.json'], + 'Lock file "/project/scaffold-lock.json" does not contain a valid JSON object.', + ], + 'LOCK_MODE_UNKNOWN' => [ + Message::LOCK_MODE_UNKNOWN, + ['copy'], + 'Unknown mode "copy" in scaffold-lock.json.', + ], + 'LOCK_UNREADABLE' => [ + Message::LOCK_UNREADABLE, + ['/project/scaffold-lock.json'], + 'Could not read lock file "/project/scaffold-lock.json".', + ], + 'LOCK_UNWRITABLE' => [ + Message::LOCK_UNWRITABLE, + ['/project/scaffold-lock.json'], + 'Could not write lock file "/project/scaffold-lock.json".', + ], + 'MANIFEST_COPY_EMPTY' => [ + Message::MANIFEST_COPY_EMPTY, + [], + 'Manifest "copy" must declare at least one path.', + ], + 'MANIFEST_COPY_ENTRY_INVALID' => [ + Message::MANIFEST_COPY_ENTRY_INVALID, + [], + 'Manifest "copy" entries must be either a string or an object with "from" and "to" keys.', + ], + 'MANIFEST_COPY_ENTRY_NOT_FOUND' => [ + Message::MANIFEST_COPY_ENTRY_NOT_FOUND, + ['missing-dir', '/vendor/p/a'], + 'Scaffold copy entry "missing-dir" does not exist under provider root "/vendor/p/a".', + ], + 'MANIFEST_COPY_MISSING' => [ + Message::MANIFEST_COPY_MISSING, + [], + 'Manifest is missing required key "copy" or it is not an array.', + ], + 'MANIFEST_COPY_NOT_LIST' => [ + Message::MANIFEST_COPY_NOT_LIST, + [], + 'Manifest "copy" must be a sequential list of entries, not an associative object.', + ], + 'MANIFEST_ENTRY_ABSOLUTE' => [ + Message::MANIFEST_ENTRY_ABSOLUTE, + ['copy', '/etc'], + 'Manifest "copy" entry "/etc" must be a relative path.', + ], + 'MANIFEST_ENTRY_EMPTY' => [ + Message::MANIFEST_ENTRY_EMPTY, + ['exclude'], + 'Manifest "exclude" entries must be non-empty strings.', + ], + 'MANIFEST_ENTRY_TRAVERSAL' => [ + Message::MANIFEST_ENTRY_TRAVERSAL, + ['modes', '../escape'], + 'Manifest "modes" entry "../escape" must not contain path traversal segments.', + ], + 'MANIFEST_EXCLUDE_NOT_ARRAY' => [ + Message::MANIFEST_EXCLUDE_NOT_ARRAY, + [], + 'Manifest "exclude" must be an array when present.', + ], + 'MANIFEST_KEY_UNKNOWN' => [ + Message::MANIFEST_KEY_UNKNOWN, + ['mode', 'copy, exclude, merge, modes'], + 'Manifest contains unknown key "mode". Allowed keys: copy, exclude, merge, modes.', + ], + 'MANIFEST_MAP_NOT_OBJECT' => [ + Message::MANIFEST_MAP_NOT_OBJECT, + ['merge'], + 'Manifest "merge" must be an object when present.', + ], + 'MANIFEST_MAP_VALUE_INVALID' => [ + Message::MANIFEST_MAP_VALUE_INVALID, + ['modes', 'config/*.php', 'mode', 'copy', 'append, prepend, preserve, replace'], + 'Manifest "modes" value for pattern "config/*.php" has invalid mode "copy". Allowed: append, prepend, ' + . 'preserve, replace.', + ], + 'MANIFEST_MAP_VALUE_NOT_STRING' => [ + Message::MANIFEST_MAP_VALUE_NOT_STRING, + ['merge', '.gitignore'], + 'Manifest "merge" value for pattern ".gitignore" must be a string.', + ], + 'MANIFEST_PROVIDER_FILE_NOT_FOUND' => [ + Message::MANIFEST_PROVIDER_FILE_NOT_FOUND, + ['p/a', 'composer.json', '/vendor/p/a/composer.json'], + 'Provider "p/a": composer.json not found at "/vendor/p/a/composer.json".', + ], + 'MANIFEST_PROVIDER_FILE_NOT_OBJECT' => [ + Message::MANIFEST_PROVIDER_FILE_NOT_OBJECT, + ['p/a', 'manifest file', '/vendor/p/a/scaffold.json'], + 'Provider "p/a": manifest file "/vendor/p/a/scaffold.json" must decode to an object.', + ], + 'MANIFEST_PROVIDER_FILE_UNREADABLE' => [ + Message::MANIFEST_PROVIDER_FILE_UNREADABLE, + ['p/a', 'manifest file', '/vendor/p/a/scaffold.json'], + 'Provider "p/a": could not read manifest file "/vendor/p/a/scaffold.json".', + ], + 'MANIFEST_REFERENCE_EMPTY' => [ + Message::MANIFEST_REFERENCE_EMPTY, + ['p/a'], + 'Provider "p/a": "manifest" must be a non-empty string.', + ], + 'MANIFEST_REFERENCE_NOT_RELATIVE' => [ + Message::MANIFEST_REFERENCE_NOT_RELATIVE, + ['p/a'], + 'Provider "p/a": "manifest" must be a relative path inside the provider root.', + ], + 'MODE_COPY_FAILED' => [ + Message::MODE_COPY_FAILED, + ['/vendor/p/a/stubs/a.txt', '/project/a.txt'], + 'Could not copy "/vendor/p/a/stubs/a.txt" to "/project/a.txt".', + ], + 'MODE_DESTINATION_UNREADABLE' => [ + Message::MODE_DESTINATION_UNREADABLE, + ['/project/a.txt'], + 'Could not read destination file "/project/a.txt".', + ], + 'MODE_SOURCE_UNREADABLE' => [ + Message::MODE_SOURCE_UNREADABLE, + ['/vendor/p/a/stubs/a.txt'], + 'Could not read source file "/vendor/p/a/stubs/a.txt".', + ], + 'MODE_WRITE_FAILED' => [ + Message::MODE_WRITE_FAILED, + ['/project/a.txt'], + 'Could not write to "/project/a.txt".', + ], + 'PACKAGE_NOT_ALLOWED' => [ + Message::PACKAGE_NOT_ALLOWED, + ['p/a'], + 'Package "p/a" is not authorized to scaffold files. Add it to extra.scaffold.allowed-packages.', + ], + 'PATH_ABSOLUTE' => [ + Message::PATH_ABSOLUTE, + ['destination', '/etc/passwd'], + 'Absolute path is not allowed in destination: "/etc/passwd".', + ], + 'PATH_DIRECTORY_CREATE_FAILED' => [ + Message::PATH_DIRECTORY_CREATE_FAILED, + ['/project/config'], + 'Could not create directory "/project/config".', + ], + 'PATH_PROJECT_ROOT_INACCESSIBLE' => [ + Message::PATH_PROJECT_ROOT_INACCESSIBLE, + ['/missing'], + 'Project root does not exist or is not accessible: "/missing".', + ], + 'PATH_PROVIDER_ROOT_INACCESSIBLE' => [ + Message::PATH_PROVIDER_ROOT_INACCESSIBLE, + ['/missing'], + 'Provider root does not exist or is not accessible: "/missing".', + ], + 'PATH_RESERVED' => [ + Message::PATH_RESERVED, + ['scaffold-lock.json'], + 'Destination "scaffold-lock.json" is reserved for the scaffold lock file.', + ], + 'PATH_SYMLINK_ESCAPE' => [ + Message::PATH_SYMLINK_ESCAPE, + ['Destination', 'link'], + 'Destination path escapes the root via symlink: "link".', + ], + 'PATH_SYMLINK_UNRESOLVABLE' => [ + Message::PATH_SYMLINK_UNRESOLVABLE, + ['Source', 'link.txt'], + 'Source path is a symlink that cannot be resolved: "link.txt".', + ], + 'PATH_TRAVERSAL' => [ + Message::PATH_TRAVERSAL, + ['source', '../stubs/a.txt'], + 'Path traversal detected in source: "../stubs/a.txt".', + ], + 'PROVIDER_INSTALL_PATH_MISSING' => [ + Message::PROVIDER_INSTALL_PATH_MISSING, + ['php-forge/meta'], + 'Provider "php-forge/meta" has no install path.', + ], + 'REGEX_FAILED' => [ + Message::REGEX_FAILED, + ['Backtrack limit exhausted'], + 'Regular expression failed: Backtrack limit exhausted.', + ], + 'SCAFFOLD_ABORTED' => [ + Message::SCAFFOLD_ABORTED, + ['Could not read lock file "/project/scaffold-lock.json".'], + '[scaffold] Scaffolding aborted: Could not read lock file "/project/scaffold-lock.json".', + ], + 'SCAFFOLD_FILES_FAILED' => [ + Message::SCAFFOLD_FILES_FAILED, + [2, 'files failed'], + '[scaffold] 2 files failed while scaffolding; see the messages above.', + ], + 'SCAFFOLD_FRAGMENT_FAILED_FILE' => [ + Message::SCAFFOLD_FRAGMENT_FAILED_FILE, + [], + 'file failed', + ], + 'SCAFFOLD_FRAGMENT_FAILED_FILES' => [ + Message::SCAFFOLD_FRAGMENT_FAILED_FILES, + [], + 'files failed', + ], + 'SCAFFOLD_MANIFEST_LOAD_FAILED' => [ + Message::SCAFFOLD_MANIFEST_LOAD_FAILED, + ['p/a', 'Manifest "copy" must declare at least one path.'], + '[scaffold] Failed to load manifest for "p/a": Manifest "copy" must declare at least one path.', + ], + 'SERVICE_CURRENT_FILE_UNREADABLE' => [ + Message::SERVICE_CURRENT_FILE_UNREADABLE, + ['/project/a.txt'], + 'Could not read current file "/project/a.txt".', + ], + 'SERVICE_STATUS_ENCODE_FAILED' => [ + Message::SERVICE_STATUS_ENCODE_FAILED, + ['Malformed UTF-8 characters, possibly incorrectly encoded'], + 'Could not encode the status report: Malformed UTF-8 characters, possibly incorrectly encoded.', + ], + 'SERVICE_STUB_NOT_FOUND' => [ + Message::SERVICE_STUB_NOT_FOUND, + ['/vendor/p/a/stubs/a.txt'], + 'Stub not found: "/vendor/p/a/stubs/a.txt".', + ], + 'SERVICE_STUB_UNREADABLE' => [ + Message::SERVICE_STUB_UNREADABLE, + ['/vendor/p/a/stubs/a.txt'], + 'Could not read stub "/vendor/p/a/stubs/a.txt".', + ], + ]; + } +} diff --git a/tests/Provider/ModeProvider.php b/tests/Provider/ModeProvider.php new file mode 100644 index 0000000..741b87c --- /dev/null +++ b/tests/Provider/ModeProvider.php @@ -0,0 +1,239 @@ + + */ + public static function copyModes(): iterable + { + yield 'preserve' => [new PreserveMode(), FileMode::Preserve]; + yield 'replace' => [new ReplaceMode(), FileMode::Replace]; + } + + /** + * @return iterable + */ + public static function missingDestinations(): iterable + { + foreach (self::modes() as $name => [$mode, $fileMode]) { + yield "{$name} without lock hash" => [$mode, $fileMode, null]; + yield "{$name} with stale lock hash" => [$mode, $fileMode, 'sha256:stale']; + } + } + + /** + * @return iterable + */ + public static function missingSources(): iterable + { + $read = Message::FILESYSTEM_FAILED->getMessage( + Message::MODE_SOURCE_UNREADABLE->getMessage('{source}'), + 'file_get_contents({source}): Failed to open stream: No such file or directory', + ); + $copy = Message::FILESYSTEM_FAILED->getMessage( + Message::MODE_COPY_FAILED->getMessage('{source}', '{destination}'), + 'copy({source}): Failed to open stream: No such file or directory', + ); + + yield 'append' => [new AppendMode(), FileMode::Append, $read]; + yield 'prepend' => [new PrependMode(), FileMode::Prepend, $read]; + yield 'preserve' => [new PreserveMode(), FileMode::Preserve, $copy]; + yield 'replace' => [new ReplaceMode(), FileMode::Replace, $copy]; + } + + /** + * @return iterable + */ + public static function modes(): iterable + { + yield 'append' => [new AppendMode(), FileMode::Append]; + yield 'prepend' => [new PrependMode(), FileMode::Prepend]; + yield 'preserve' => [new PreserveMode(), FileMode::Preserve]; + yield 'replace' => [new ReplaceMode(), FileMode::Replace]; + } + + /** + * @return iterable + */ + public static function prependBlocks(): iterable + { + yield 'missing destination' => [ + "a\n", + null, + "a\n", + ]; + yield 'empty destination' => [ + "# header\r\n", + '', + "# header\r\n", + ]; + yield 'block before existing content' => [ + 'PREPENDED', + 'EXISTING', + "PREPENDED\nEXISTING", + ]; + yield 'stub without trailing newline' => [ + 'prepended ', + 'existing', + "prepended \nexisting", + ]; + yield 'destination line ending' => [ + "a\nb\n", + "x\r\n", + "a\r\nb\r\nx\r\n", + ]; + yield 'empty stub' => [ + '', + "x\n", + null, + ]; + yield 'empty stub with empty destination' => [ + '', + '', + null, + ]; + yield 'block at the start' => [ + "# header\n", + "# header\nbody\n", + null, + ]; + yield 'block at the end' => [ + "# footer\n", + "body\n# footer\n", + null, + ]; + yield 'block moved by the user' => [ + "# header\n# line 2\n", + "intro\n# header\n# line 2\nbody", + null, + ]; + yield 'block present after line ending normalisation' => [ + "# header\n# line 2\n", + "# header\r\n# line 2\r\nbody\r\n", + null, + ]; + } + + /** + * @return iterable + */ + public static function replaceDecisions(): iterable + { + yield 'tracked and unmodified' => [ + self::hashOf(self::EXISTING), + self::EXISTING, + self::STUB, + ApplyOutcome::Written, + self::STUB, + self::hashOf(self::STUB), + null, + ]; + yield 'tracked and modified by the user' => [ + self::hashOf('content recorded at scaffold time'), + self::EXISTING, + self::STUB, + ApplyOutcome::Skipped, + self::EXISTING, + '', + ConsoleMessage::SCAFFOLD_USER_MODIFIED_SKIPPED->getMessage('output.txt'), + ]; + yield 'untracked with different content' => [ + null, + self::EXISTING, + self::STUB, + ApplyOutcome::Written, + self::STUB, + self::hashOf(self::STUB), + ConsoleMessage::SCAFFOLD_UNTRACKED_OVERWRITTEN->getMessage('output.txt'), + ]; + yield 'untracked with identical content' => [ + null, + self::STUB, + self::STUB, + ApplyOutcome::Written, + self::STUB, + self::hashOf(self::STUB), + null, + ]; + } + + /** + * @return iterable + */ + public static function unreadableDestinations(): iterable + { + $read = Message::MODE_DESTINATION_UNREADABLE->getMessage('{destination}') + . ' Reason: file_get_contents('; + $hash = Message::LOCK_HASH_FAILED->getMessage('{destination}') . ' Reason: hash_file('; + + yield 'append' => [new AppendMode(), FileMode::Append, $read]; + yield 'prepend' => [new PrependMode(), FileMode::Prepend, $read]; + yield 'preserve' => [new PreserveMode(), FileMode::Preserve, $hash]; + yield 'replace' => [new ReplaceMode(), FileMode::Replace, $hash]; + } + + /** + * @return iterable + */ + public static function unwritableDestinations(): iterable + { + $write = Message::FILESYSTEM_FAILED->getMessage( + Message::MODE_WRITE_FAILED->getMessage('{destination}'), + 'file_put_contents({destination}): Failed to open stream: No such file or directory', + ); + $copy = Message::FILESYSTEM_FAILED->getMessage( + Message::MODE_COPY_FAILED->getMessage('{source}', '{destination}'), + 'copy({destination}): Failed to open stream: No such file or directory', + ); + + yield 'append' => [new AppendMode(), FileMode::Append, $write]; + yield 'prepend' => [new PrependMode(), FileMode::Prepend, $write]; + yield 'preserve' => [new PreserveMode(), FileMode::Preserve, $copy]; + yield 'replace' => [new ReplaceMode(), FileMode::Replace, $copy]; + } + + /** + * Returns the lock hash of `$content` in the `sha256:` format of {@see \PHPForge\Scaffold\Scaffold\Lock\Hasher}. + * + * @param string $content File content. + * + * @return string Prefixed SHA-256 hash. + */ + private static function hashOf(string $content): string + { + return 'sha256:' . hash('sha256', $content); + } +} diff --git a/tests/Provider/PathResolverProvider.php b/tests/Provider/PathResolverProvider.php new file mode 100644 index 0000000..30b7250 --- /dev/null +++ b/tests/Provider/PathResolverProvider.php @@ -0,0 +1,198 @@ + + */ + public static function joins(): iterable + { + yield 'destination with leading separator' => [ + 'destination', + '/tmp/foo', + '/bar', + '/tmp/foo' . DIRECTORY_SEPARATOR . 'bar', + ]; + yield 'destination with leading backslash' => [ + 'destination', + '/tmp/foo', + '\\bar', + '/tmp/foo' . DIRECTORY_SEPARATOR . 'bar', + ]; + yield 'project root with trailing separator' => [ + 'destination', + '/tmp/foo/', + 'bar', + '/tmp/foo' . DIRECTORY_SEPARATOR . 'bar', + ]; + yield 'project root with trailing backslash' => [ + 'destination', + '/tmp/foo\\', + 'bar', + '/tmp/foo' . DIRECTORY_SEPARATOR . 'bar', + ]; + yield 'source with leading separator' => [ + 'source', + '/tmp/provider', + '/file.txt', + '/tmp/provider' . DIRECTORY_SEPARATOR . 'file.txt', + ]; + yield 'source with leading backslash' => [ + 'source', + '/tmp/provider', + '\\file.txt', + '/tmp/provider' . DIRECTORY_SEPARATOR . 'file.txt', + ]; + yield 'provider path with trailing separator' => [ + 'source', + '/tmp/provider/', + 'file.txt', + '/tmp/provider' . DIRECTORY_SEPARATOR . 'file.txt', + ]; + yield 'provider path with trailing backslash' => [ + 'source', + '/tmp/provider\\', + 'file.txt', + '/tmp/provider' . DIRECTORY_SEPARATOR . 'file.txt', + ]; + } + + /** + * @return iterable + */ + public static function permissions(): iterable + { + yield 'permissive umask keeps the executable bit' => [0o755, 0o644, 0o022, 0o755]; + yield 'restrictive umask drops the group and other bits' => [0o755, 0o600, 0o077, 0o700]; + yield 'zero umask copies the source bits exactly' => [0o640, 0o600, 0o000, 0o640]; + } + + /** + * @return iterable, string, mixed, string, string, string|null}> + */ + public static function providerRoots(): iterable + { + $outside = Message::SCAFFOLD_PROVIDER_ROOT_OUTSIDE_VENDOR->getMessage('pkg/name'); + + yield 'lock entry missing' => [ + [], + '{tmp}', + null, + '', + '{real}{/}pkg/name', + null, + ]; + yield 'lock entry not an array' => [ + [], + '{tmp}', + 'vendor/pkg/name', + '', + '{real}{/}pkg/name', + null, + ]; + yield 'lock path not a string' => [ + [], + '{tmp}', + ['path' => 1], + '', + '{real}{/}pkg/name', + null, + ]; + yield 'lock path equal to the vendor directory' => [ + [], + '{tmp}', + ['path' => '{tmp}'], + '', + '{real}', + null, + ]; + yield 'absolute lock path inside vendor' => [ + ['pkg/name'], + '{tmp}', + ['path' => '{tmp}/pkg/name'], + '', + '{real}{/}pkg{/}name', + null, + ]; + yield 'absolute lock path inside vendor with a project root' => [ + ['vendor/pkg/name'], + '{tmp}/vendor', + ['path' => '{real}/vendor/pkg/name'], + '{tmp}/unrelated-project-root', + '{real}{/}vendor{/}pkg{/}name', + null, + ]; + yield 'relative lock path expanded against the project root' => [ + ['vendor/pkg/name'], + '{tmp}/vendor', + ['path' => 'vendor/pkg/name'], + '{tmp}', + '{real}{/}vendor{/}pkg{/}name', + null, + ]; + yield 'project root with trailing separator' => [ + ['proj/vendor'], + '{real}/proj/vendor', + ['path' => 'vendor/pkg/name-missing'], + '{real}/proj/', + '{real}/proj{/}vendor/pkg/name-missing', + null, + ]; + yield 'missing lock path with backslash separators inside vendor' => [ + ['vendor'], + '{tmp}/vendor', + ['path' => '{real}\\vendor\\pkg\\name-missing'], + '', + '{real}\\vendor\\pkg\\name-missing', + null, + ]; + yield 'missing lock path differing from vendor only in case' => [ + ['vendor'], + '{tmp}/vendor', + ['path' => '{real}/VENDOR/pkg/name-missing'], + '', + DIRECTORY_SEPARATOR === '\\' ? '{real}/VENDOR/pkg/name-missing' : '{real}{/}vendor{/}pkg/name', + DIRECTORY_SEPARATOR === '\\' ? null : $outside, + ]; + yield 'lock path escaping vendor' => [ + ['pkg/name'], + '{tmp}', + ['path' => '/etc'], + '', + '{real}{/}pkg/name', + $outside, + ]; + yield 'lock path sharing a string prefix with vendor' => [ + ['vendor', 'vendorsibling'], + '{tmp}/vendor', + ['path' => '{tmp}/vendorsibling'], + '', + '{real}{/}vendor{/}pkg/name', + $outside, + ]; + } + + /** + * @return iterable + */ + public static function within(): iterable + { + yield 'case-insensitive, other casing' => ['/project/vendor/foo', '/Project/vendor', true, true]; + yield 'case-insensitive, other path' => ['/elsewhere/vendor/foo', '/Project/vendor', true, false]; + yield 'case-insensitive, sibling sharing a string prefix' => ['/Project/vendorx', '/project/vendor', true, false]; + yield 'case-sensitive, other casing' => ['/project/vendor/foo', '/Project/vendor', false, false]; + yield 'case-sensitive, same casing' => ['/Project/vendor/foo', '/Project/vendor', false, true]; + yield 'equal paths' => ['/Project/vendor', '/Project/vendor', false, true]; + yield 'mixed separators' => ['C:\\Project/vendor\\foo', 'C:/Project\\vendor', false, true]; + } +} diff --git a/tests/Provider/PathValidatorProvider.php b/tests/Provider/PathValidatorProvider.php new file mode 100644 index 0000000..9940602 --- /dev/null +++ b/tests/Provider/PathValidatorProvider.php @@ -0,0 +1,270 @@ +, array}> + */ + public static function acceptedPaths(): iterable + { + yield 'relative destination' => [ + 'destination', + 'config/params.php', + [], + [], + ]; + yield 'nested relative destination' => [ + 'destination', + 'resources/js/Pages/Home.vue', + [], + [], + ]; + yield 'dot file' => [ + 'destination', + '.gitignore', + [], + [], + ]; + yield 'empty destination' => [ + 'destination', + '', + [], + [], + ]; + yield 'destination with trailing separator' => [ + 'destination', + 'config/', + [], + [], + ]; + yield 'lock file name below a directory' => [ + 'destination', + 'config/scaffold-lock.json', + [], + [], + ]; + yield 'deep missing destination' => [ + 'destination', + 'a/b/c/d/does-not-exist.txt', + [], + [], + ]; + yield 'missing file in an existing directory' => [ + 'destination', + 'sub/missing-file.txt', + ['root/sub'], + [], + ]; + yield 'dangling link to a missing file inside the root' => [ + 'destination', + 'link.txt', + ['root/real'], + ['root/link.txt' => 'real/missing.txt'], + ]; + yield 'link looping back to the root' => [ + 'destination', + 'loop/missing-file.txt', + [], + ['root/loop' => '{tmp}/root'], + ]; + yield 'relative source' => [ + 'source', + 'stubs/params.php', + [], + [], + ]; + yield 'empty source' => [ + 'source', + '', + [], + [], + ]; + yield 'dangling link chain inside the root' => [ + 'source', + 'first', + [], + ['root/first' => '{tmp}/root/second', 'root/second' => 'missing.txt'], + ]; + } + + /** + * @return iterable + */ + public static function paths(): iterable + { + yield 'relative path' => ['config/app.php', false, false]; + yield 'dot file' => ['.gitignore', false, false]; + yield 'POSIX absolute' => ['/etc/passwd', true, false]; + yield 'backslash absolute' => ['\\server\\share', true, false]; + yield 'drive absolute' => ['C:\\Windows\\file', true, false]; + yield 'drive relative' => ['c:file', true, false]; + yield 'drive letter mid-path' => ['nested/C:/file.txt', false, false]; + yield 'traversal at start' => ['../etc/passwd', false, true]; + yield 'traversal in the middle' => ['config/../../etc/passwd', false, true]; + yield 'backslash traversal' => ['config\\..\\etc', false, true]; + yield 'trailing traversal' => ['config/..', false, true]; + yield 'double dot inside a name' => ['foo..bar', false, false]; + yield 'absolute with traversal' => ['/a/../b', true, true]; + } + + /** + * @return iterable, array, string}> + */ + public static function rejectedPaths(): iterable + { + yield 'absolute destination' => [ + 'destination', + '/etc/passwd', + [], + [], + Message::PATH_ABSOLUTE->getMessage('destination', '/etc/passwd'), + ]; + yield 'destination with traversal' => [ + 'destination', + '../../../etc/passwd', + [], + [], + Message::PATH_TRAVERSAL->getMessage('destination', '../../../etc/passwd'), + ]; + yield 'absolute source' => [ + 'source', + '/etc/shadow', + [], + [], + Message::PATH_ABSOLUTE->getMessage('source', '/etc/shadow'), + ]; + yield 'source with traversal' => [ + 'source', + '../stubs/params.php', + [], + [], + Message::PATH_TRAVERSAL->getMessage('source', '../stubs/params.php'), + ]; + + foreach ( + [ + 'scaffold-lock.json', + './scaffold-lock.json', + 'scaffold-lock.json/nested.txt', + 'SCAFFOLD-LOCK.JSON', + 'scaffold-lock.json\\nested.txt', + ] as $reserved) { + yield "reserved destination '{$reserved}'" => [ + 'destination', + $reserved, + [], + [], + Message::PATH_RESERVED->getMessage($reserved), + ]; + } + + yield 'destination link escaping the root' => [ + 'destination', + 'escape', + ['outside'], + ['root/escape' => '{tmp}/outside'], + Message::PATH_SYMLINK_ESCAPE->getMessage('Destination', 'escape'), + ]; + yield 'destination link to a directory sharing the root prefix' => [ + 'destination', + 'link', + ['rootsibling'], + ['root/link' => '{tmp}/rootsibling'], + Message::PATH_SYMLINK_ESCAPE->getMessage('Destination', 'link'), + ]; + yield 'missing destination below a link escaping the root' => [ + 'destination', + 'escape/missing/file.txt', + ['outside'], + ['root/escape' => '{tmp}/outside'], + Message::PATH_SYMLINK_ESCAPE->getMessage('Destination', 'escape/missing/file.txt'), + ]; + yield 'missing destination below a link to a directory sharing the root prefix' => [ + 'destination', + 'link/missing-leaf.txt', + ['rootsibling'], + ['root/link' => '{tmp}/rootsibling'], + Message::PATH_SYMLINK_ESCAPE->getMessage('Destination', 'link/missing-leaf.txt'), + ]; + yield 'dangling destination link escaping the root' => [ + 'destination', + 'rep.txt', + ['outside'], + ['root/rep.txt' => '{tmp}/outside/OUTSIDE_TARGET.txt'], + Message::PATH_SYMLINK_ESCAPE->getMessage('Destination', 'rep.txt'), + ]; + yield 'dangling destination link with trailing separator escaping the root' => [ + 'destination', + 'rep.txt/', + ['outside'], + ['root/rep.txt' => '{tmp}/outside/OUTSIDE_TARGET.txt'], + Message::PATH_SYMLINK_ESCAPE->getMessage('Destination', 'rep.txt/'), + ]; + yield 'dangling destination link chain escaping the root' => [ + 'destination', + 'first', + ['outside'], + ['root/first' => 'second', 'root/second' => '{tmp}/outside/target.txt'], + Message::PATH_SYMLINK_ESCAPE->getMessage('Destination', 'first'), + ]; + yield 'dangling destination link into a missing directory' => [ + 'destination', + 'link.txt', + [], + ['root/link.txt' => 'missing-dir/target.txt'], + Message::PATH_SYMLINK_UNRESOLVABLE->getMessage('Destination', 'link.txt'), + ]; + yield 'dangling destination link chain longer than the hop limit' => [ + 'destination', + 'link0', + [], + self::linkChain(), + Message::PATH_SYMLINK_UNRESOLVABLE->getMessage('Destination', 'link0'), + ]; + yield 'source link escaping the root' => [ + 'source', + 'escape', + ['outside'], + ['root/escape' => '{tmp}/outside'], + Message::PATH_SYMLINK_ESCAPE->getMessage('Source', 'escape'), + ]; + yield 'dangling source link escaping the root' => [ + 'source', + 'stub.txt', + [], + ['root/stub.txt' => '{tmp}/secret.txt'], + Message::PATH_SYMLINK_ESCAPE->getMessage('Source', 'stub.txt'), + ]; + } + + /** + * Returns a chain of dangling links `link0` -> `link1` -> ... ending in a missing file, one hop over the limit. + * + * @return array Link targets keyed by link path. + */ + private static function linkChain(): array + { + $links = []; + + for ($hop = 0; $hop < self::TOO_MANY_HOPS; $hop++) { + $links["root/link{$hop}"] = $hop + 1 === self::TOO_MANY_HOPS ? 'missing.txt' : 'link' . ($hop + 1); + } + + return $links; + } +} diff --git a/tests/Provider/PostCreateProjectProvider.php b/tests/Provider/PostCreateProjectProvider.php new file mode 100644 index 0000000..9ea324b --- /dev/null +++ b/tests/Provider/PostCreateProjectProvider.php @@ -0,0 +1,32 @@ + + */ + public static function installEvents(): iterable + { + yield 'post-install-cmd' => [ScriptEvents::POST_INSTALL_CMD]; + yield 'post-update-cmd' => [ScriptEvents::POST_UPDATE_CMD]; + } + + /** + * @return iterable + */ + public static function scaffoldEvents(): iterable + { + yield 'post-create-project-cmd' => [ScriptEvents::POST_CREATE_PROJECT_CMD]; + yield from self::installEvents(); + } +} diff --git a/tests/Provider/ProvidersServiceProvider.php b/tests/Provider/ProvidersServiceProvider.php new file mode 100644 index 0000000..f7f6be4 --- /dev/null +++ b/tests/Provider/ProvidersServiceProvider.php @@ -0,0 +1,63 @@ +, array, array}> + */ + public static function counts(): iterable + { + yield 'empty lock' => [ + [], + [], + [], + ]; + yield 'files aggregated per provider' => [ + [], + ['a.txt' => 'pkg/a', 'b.txt' => 'pkg/a', 'c.txt' => 'pkg/b'], + ['pkg/a' => 2, 'pkg/b' => 1], + ]; + yield 'provider metadata without files' => [ + ['pkg/with-files' => '0.1.0', 'pkg/zero-files' => '0.1.0'], + ['a.txt' => 'pkg/with-files'], + ['pkg/with-files' => 1, 'pkg/zero-files' => 0], + ]; + } + + /** + * @return iterable, array, string}> + */ + public static function tables(): iterable + { + yield 'no providers' => [ + [], + [], + Message::PROVIDERS_NONE->getMessage() . PHP_EOL, + ]; + yield 'one provider' => [ + [], + ['a.txt' => 'pkg/a'], + 'Provider Files' . PHP_EOL + . '---------------' . PHP_EOL + . 'pkg/a 1' . PHP_EOL, + ]; + yield 'columns as wide as their longest cell' => [ + ['pkg/zero-files' => '0.1.0'], + ['a.txt' => 'pkg/a', 'b.txt' => 'pkg/a'], + 'Provider Files' . PHP_EOL + . '---------------------' . PHP_EOL + . 'pkg/zero-files 0' . PHP_EOL + . 'pkg/a 2' . PHP_EOL, + ]; + } +} diff --git a/tests/Provider/PruneCommandProvider.php b/tests/Provider/PruneCommandProvider.php new file mode 100644 index 0000000..ab271f2 --- /dev/null +++ b/tests/Provider/PruneCommandProvider.php @@ -0,0 +1,45 @@ +, int, array{'old.txt': bool, 'edited.txt': bool}}> + */ + public static function options(): iterable + { + yield 'preview' => [ + [], + 0, + ['old.txt' => true, 'edited.txt' => true], + ]; + yield 'preview with delete modified' => [ + ['--delete-modified' => true], + 0, + ['old.txt' => true, 'edited.txt' => true], + ]; + yield 'preview with exit code' => [ + ['--exit-code' => true], + 1, + ['old.txt' => true, 'edited.txt' => true], + ]; + yield 'force' => [ + ['--force' => true], + 0, + ['old.txt' => false, 'edited.txt' => true], + ]; + yield 'force with delete modified' => [ + ['--force' => true, '--delete-modified' => true], + 0, + ['old.txt' => false, 'edited.txt' => false], + ]; + } +} diff --git a/tests/Provider/ReapplyCommandProvider.php b/tests/Provider/ReapplyCommandProvider.php new file mode 100644 index 0000000..b0c8bcc --- /dev/null +++ b/tests/Provider/ReapplyCommandProvider.php @@ -0,0 +1,26 @@ +, int, string}> + */ + public static function inputs(): iterable + { + yield 'dry run with force' => [['--dry-run' => true, '--force' => true], 0, "user-edited\n"]; + yield 'file with force' => [['file' => 'config/params.php', '--force' => true], 0, "original\n"]; + yield 'file without force' => [['file' => 'config/params.php'], 0, "user-edited\n"]; + yield 'matching provider with force' => [['--provider' => 'pkg/name', '--force' => true], 0, "original\n"]; + yield 'other provider with force' => [['--provider' => 'pkg/other', '--force' => true], 1, "user-edited\n"]; + yield 'untracked file' => [['file' => 'missing.php', '--force' => true], 1, "user-edited\n"]; + } +} diff --git a/tests/Provider/ReapplyServiceProvider.php b/tests/Provider/ReapplyServiceProvider.php new file mode 100644 index 0000000..b757d04 --- /dev/null +++ b/tests/Provider/ReapplyServiceProvider.php @@ -0,0 +1,50 @@ + + */ + public static function dryRunExitCodes(): iterable + { + $unchanged = Message::DIFF_NO_CHANGES->getMessage('a.txt') . PHP_EOL + . ExpectedSummary::reapplyDryRun(0, 1, 0, 0) . PHP_EOL; + $changed = Message::DIFF_PREVIEW_HEADER->getMessage('a.txt', 'replace', 'p/a', '') . PHP_EOL + . "--- a/a.txt\n+++ b/a.txt\n@@ -1 +1 @@\n-v1\n+v2" . PHP_EOL + . ExpectedSummary::reapplyDryRun(1, 0, 0, 0) . PHP_EOL; + + yield 'unchanged with exit code' => ["v1\n", true, 0, $unchanged]; + yield 'changed with exit code' => ["v2\n", true, 1, $changed]; + yield 'changed without exit code' => ["v2\n", false, 0, $changed]; + } + + /** + * @return iterable File and provider filters that match no tracked file. + */ + public static function unmatchedFilters(): iterable + { + yield 'file filter' => ['missing.php', '']; + yield 'provider filter' => ['', 'p/missing']; + yield 'file and provider filters' => ['missing.php', 'p/missing']; + } + + /** + * @return iterable, string, string}> + */ + public static function unsafeEntries(): iterable + { + yield 'unsafe destination' => ['../escape.php', [], 'destination', '../escape.php']; + yield 'unsafe source' => ['a.txt', ['source' => '../escape.txt'], 'source', '../escape.txt']; + } +} diff --git a/tests/Provider/ScaffoldRunnerProvider.php b/tests/Provider/ScaffoldRunnerProvider.php new file mode 100644 index 0000000..1ee6ff6 --- /dev/null +++ b/tests/Provider/ScaffoldRunnerProvider.php @@ -0,0 +1,60 @@ + + */ + public static function providerPaths(): iterable + { + yield 'install path inside the project root' => [ + '{tmp}/project/vendor/pkg', + '{tmp}/project', + 'vendor/pkg', + ]; + yield 'install path equal to the project root' => [ + '{tmp}/project', + '{tmp}/project', + '', + ]; + yield 'install path outside the project root' => [ + '{tmp}/outside/pkg', + '{tmp}/project', + '{real}/outside/pkg', + ]; + yield 'project root with trailing separator' => [ + '{tmp}/project/vendor/pkg', + '{tmp}/project/', + 'vendor/pkg', + ]; + yield 'filesystem root as project root' => [ + '{tmp}/project/pkg', + '{root}', + '{rel}/project/pkg', + ]; + yield 'backslash in the install path' => [ + '{tmp}/project/subdir\\pkg', + '{tmp}/project/subdir', + 'pkg', + ]; + yield 'backslash in the project root' => [ + '{tmp}/project/subdir/pkg', + '{tmp}/project\\subdir', + 'pkg', + ]; + yield 'project root differing in case' => [ + '{tmp}/project/pkg', + '{tmp}/Project', + DIRECTORY_SEPARATOR === '\\' ? 'pkg' : '{real}/project/pkg', + ]; + } +} diff --git a/tests/Provider/ScaffoldSummaryProvider.php b/tests/Provider/ScaffoldSummaryProvider.php new file mode 100644 index 0000000..98c578c --- /dev/null +++ b/tests/Provider/ScaffoldSummaryProvider.php @@ -0,0 +1,184 @@ + + */ + public static function reapplyLines(): iterable + { + $single = new ReapplySummary(); + + $single->written = 3; + $single->unchanged = 7; + $single->errors = 1; + $single->skip('user-modified'); + + yield 'single skip reason without its count' => [ + $single, + false, + Message::REAPPLY_SUMMARY->getMessage( + '', + 3, + Message::FRAGMENT_WRITTEN->getMessage(), + 7, + 1, + Message::FRAGMENT_PARENTHESIZED->getMessage('user-modified'), + 1, + Message::FRAGMENT_ERROR->getMessage(), + ), + ]; + + $several = new ReapplySummary(); + + $several->written = 3; + $several->unchanged = 7; + $several->errors = 2; + + $several->skip('user-modified'); + $several->skip('preserve'); + + yield 'several skip reasons with their counts in a dry run' => [ + $several, + true, + Message::REAPPLY_SUMMARY->getMessage( + Message::FRAGMENT_DRY_RUN->getMessage(), + 3, + Message::FRAGMENT_WOULD_BE_WRITTEN->getMessage(), + 7, + 2, + Message::FRAGMENT_PARENTHESIZED->getMessage( + implode( + ', ', + [ + Message::FRAGMENT_COUNT->getMessage(1, 'user-modified'), + Message::FRAGMENT_COUNT->getMessage(1, 'preserve'), + ], + ), + ), + 2, + Message::FRAGMENT_ERRORS->getMessage(), + ), + ]; + + yield 'nothing skipped' => [ + new ReapplySummary(), + false, + Message::REAPPLY_SUMMARY->getMessage( + '', + 0, + Message::FRAGMENT_WRITTEN->getMessage(), + 0, + 0, + '', + 0, + Message::FRAGMENT_ERRORS->getMessage(), + ), + ]; + } + + /** + * @return iterable + */ + public static function scaffoldLines(): iterable + { + yield 'nothing happened' => [ + self::summary(), + null, + ]; + yield 'only unchanged files' => [ + self::summary(unchanged: 8), + null, + ]; + yield 'one written file' => [ + self::summary(written: 1, unchanged: 8), + ExpectedSummary::line(1, 8), + ]; + yield 'written files and warnings' => [ + self::summary(written: 3, unchanged: 8, warnings: 2), + ExpectedSummary::line(3, 8, ExpectedSummary::part(2, Message::FRAGMENT_WARNINGS)), + ]; + yield 'one warning only' => [ + self::summary(unchanged: 8, warnings: 1), + ExpectedSummary::line(0, 8, ExpectedSummary::part(1, Message::FRAGMENT_WARNING)), + ]; + yield 'outdated only' => [ + self::summary(outdated: 1), + ExpectedSummary::line(0, 0, ExpectedSummary::part(1, Message::FRAGMENT_OUTDATED)), + ]; + yield 'conflicts only' => [ + self::summary(conflict: 2), + ExpectedSummary::line(0, 0, ExpectedSummary::part(2, Message::FRAGMENT_CONFLICT)), + ]; + yield 'orphan only' => [ + self::summary(orphan: 1), + ExpectedSummary::line(0, 0, ExpectedSummary::part(1, Message::FRAGMENT_ORPHAN)), + ]; + yield 'one error only' => [ + self::summary(errors: 1), + ExpectedSummary::line(0, 0, ExpectedSummary::part(1, Message::FRAGMENT_ERROR)), + ]; + yield 'every count, in order' => [ + self::summary(written: 1, unchanged: 4, outdated: 1, conflict: 2, orphan: 3, warnings: 1, errors: 2), + ExpectedSummary::line( + 1, + 4, + ExpectedSummary::part(1, Message::FRAGMENT_OUTDATED), + ExpectedSummary::part(2, Message::FRAGMENT_CONFLICT), + ExpectedSummary::part(3, Message::FRAGMENT_ORPHAN), + ExpectedSummary::part(1, Message::FRAGMENT_WARNING), + ExpectedSummary::part(2, Message::FRAGMENT_ERRORS), + ), + ]; + } + + /** + * Returns a scaffold summary with the given counters. + * + * @param int $written Number of written files. + * @param int $unchanged Number of unchanged files. + * @param int $outdated Number of outdated files. + * @param int $conflict Number of conflicts. + * @param int $orphan Number of orphans. + * @param int $warnings Number of warnings. + * @param int $errors Number of errors. + * + * @return ScaffoldSummary Summary with the counters set. + */ + private static function summary( + int $written = 0, + int $unchanged = 0, + int $outdated = 0, + int $conflict = 0, + int $orphan = 0, + int $warnings = 0, + int $errors = 0, + ): ScaffoldSummary { + $summary = new ScaffoldSummary(); + + $summary->written = $written; + $summary->unchanged = $unchanged; + $summary->outdated = $outdated; + $summary->conflict = $conflict; + $summary->orphan = $orphan; + $summary->warnings = $warnings; + $summary->errors = $errors; + + return $summary; + } +} diff --git a/tests/Provider/ScaffolderProvider.php b/tests/Provider/ScaffolderProvider.php new file mode 100644 index 0000000..4de8c25 --- /dev/null +++ b/tests/Provider/ScaffolderProvider.php @@ -0,0 +1,76 @@ +, string, string}> + */ + public static function allowedOrders(): iterable + { + yield 'override listed last' => [ + ['php-forge/base', 'php-forge/override'], + 'php-forge/override', + 'php-forge/base', + ]; + yield 'base listed last' => [ + ['php-forge/override', 'php-forge/base'], + 'php-forge/base', + 'php-forge/override', + ]; + } + + /** + * @return iterable + */ + public static function mergedFiles(): iterable + { + yield 'append' => ['append', '*.log', 'vendor/', "vendor/\n\n*.log"]; + yield 'prepend' => ['prepend', 'header', 'existing', "header\nexisting"]; + } + + /** + * @return iterable + */ + public static function prefixMatches(): iterable + { + yield 'case-sensitive, same casing' => ['/Project/vendor/foo', '/Project/', false, true]; + yield 'case-sensitive, other casing' => ['/project/vendor/foo', '/Project/', false, false]; + yield 'case-insensitive, other casing' => ['/project/vendor/foo', '/Project/', true, true]; + yield 'case-insensitive, other path' => ['/elsewhere/vendor/foo', '/Project/', true, false]; + } + + /** + * @return iterable, array}> + */ + public static function providersWithoutMappings(): iterable + { + yield 'no scaffold block' => [[], []]; + yield 'only default-excluded entries' => [ + ['scaffold' => ['copy' => ['.github/linters']]], + ['.github/linters/actionlint.yml' => 'x'], + ]; + } + + /** + * @return iterable, string}> + */ + public static function rootsWithoutProviders(): iterable + { + yield 'no scaffold block' => [[], Message::SCAFFOLD_CONFIG_MISSING->getMessage()]; + yield 'no allowed-packages key' => [['scaffold' => []], Message::SCAFFOLD_NO_ALLOWED_PACKAGES->getMessage()]; + yield 'empty allowed-packages' => [ + ['scaffold' => ['allowed-packages' => []]], + Message::SCAFFOLD_NO_ALLOWED_PACKAGES->getMessage(), + ]; + } +} diff --git a/tests/Provider/StatusServiceProvider.php b/tests/Provider/StatusServiceProvider.php new file mode 100644 index 0000000..2e0bbe3 --- /dev/null +++ b/tests/Provider/StatusServiceProvider.php @@ -0,0 +1,230 @@ +, int}> + */ + public static function states(): iterable + { + yield 'append with consumer additions' => [ + static function (InspectionProject $project): void { + $project + ->provider('p/a', ['.gitignore' => "/vendor\n"], ['.gitignore' => 'append']) + ->file('.gitignore', "/vendor\n") + ->track('.gitignore', 'p/a', 'append') + ->file('.gitignore', "/vendor\n/my-build\n"); + }, + ['.gitignore' => 'synced'], + 0, + ]; + yield 'append without the new provider entry' => [ + static function (InspectionProject $project): void { + $project + ->provider('p/a', ['.gitignore' => "/vendor\n"], ['.gitignore' => 'append']) + ->file('.gitignore', "/vendor\n") + ->track('.gitignore', 'p/a', 'append') + ->stub('p/a', '.gitignore', "/vendor\n/.config/gh\n"); + }, + ['.gitignore' => 'outdated'], + 1, + ]; + yield 'prepend with the block' => [ + static function (InspectionProject $project): void { + $project + ->provider('p/a', ['h.php' => " 'prepend']) + ->file('h.php', "track('h.php', 'p/a', 'prepend'); + }, + ['h.php' => 'synced'], + 0, + ]; + yield 'prepend without the new block' => [ + static function (InspectionProject $project): void { + $project + ->provider('p/a', ['h.php' => " 'prepend']) + ->file('h.php', "track('h.php', 'p/a', 'prepend') + ->stub('p/a', 'h.php', " 'outdated'], + 1, + ]; + yield 'preserve unchanged' => [ + static function (InspectionProject $project): void { + self::preserve($project); + }, + ['ecs.php' => 'synced'], + 0, + ]; + yield 'preserve with a new stub' => [ + static function (InspectionProject $project): void { + self::preserve($project)->stub('p/a', 'ecs.php', "v2\n"); + }, + ['ecs.php' => 'outdated'], + 1, + ]; + yield 'preserve edited by the consumer' => [ + static function (InspectionProject $project): void { + self::preserve($project)->stub('p/a', 'ecs.php', "v2\n")->file('ecs.php', "mine\n"); + }, + ['ecs.php' => 'modified'], + 1, + ]; + yield 'preserve without stub hash differing from the stub' => [ + static function (InspectionProject $project): void { + $project + ->provider('p/a', ['ecs.php' => "v1\n"], ['ecs.php' => 'preserve']) + ->file('ecs.php', "mine\n") + ->track('ecs.php', 'p/a', 'preserve', ['stub-hash' => null]); + }, + ['ecs.php' => 'synced'], + 0, + ]; + yield 'replace unchanged' => [ + static function (InspectionProject $project): void { + self::replace($project); + }, + ['a.txt' => 'synced'], + 0, + ]; + yield 'replace edited by the consumer' => [ + static function (InspectionProject $project): void { + self::replace($project)->file('a.txt', "mine\n"); + }, + ['a.txt' => 'modified'], + 1, + ]; + yield 'replace edited by the consumer with a new stub' => [ + static function (InspectionProject $project): void { + self::replace($project)->file('a.txt', "mine\n")->stub('p/a', 'a.txt', "v2\n"); + }, + ['a.txt' => 'conflict'], + 1, + ]; + yield 'replace with a new stub' => [ + static function (InspectionProject $project): void { + self::replace($project)->stub('p/a', 'a.txt', "v2\n"); + }, + ['a.txt' => 'outdated'], + 1, + ]; + yield 'replace without stub hash differing from the stub' => [ + static function (InspectionProject $project): void { + $project + ->provider('p/a', ['a.txt' => "v1\n"]) + ->file('a.txt', "v1\n") + ->track('a.txt', 'p/a', extra: ['stub-hash' => null]) + ->stub('p/a', 'a.txt', "v2\n"); + }, + ['a.txt' => 'outdated'], + 1, + ]; + yield 'missing destination' => [ + static function (InspectionProject $project): void { + self::replace($project)->delete('a.txt'); + }, + ['a.txt' => 'missing'], + 1, + ]; + yield 'ejected entry without a file on disk' => [ + static function (InspectionProject $project): void { + $project + ->provider('p/a', ['a.txt' => "a\n"]) + ->track('a.txt', 'p/a', extra: ['ejected' => true]); + }, + ['a.txt' => 'ejected'], + 0, + ]; + yield 'destination that is a directory' => [ + static function (InspectionProject $project): void { + $project + ->provider('p/a', ['a.txt' => "a\n"]) + ->track('a.txt', 'p/a'); + + mkdir("{$project->root}/a.txt"); + }, + ['a.txt' => 'error'], + 1, + ]; + yield 'provider manifest that cannot be loaded' => [ + static function (InspectionProject $project): void { + self::replace($project)->file('vendor/p/a/composer.json', '{"extra": {"scaffold": {"copy": "nope"}}}'); + }, + ['a.txt' => 'error'], + 1, + ]; + yield 'unsafe destination before the orphan check' => [ + static function (InspectionProject $project): void { + self::replace($project)->track('../escape.php', 'p/a'); + }, + ['../escape.php' => 'error', 'a.txt' => 'synced'], + 1, + ]; + yield 'provider not allowed' => [ + static function (InspectionProject $project): void { + self::replace($project) + ->provider('p/denied', ['d.txt' => "d\n"]) + ->file('d.txt', "d\n") + ->track('d.txt', 'p/denied'); + }, + ['a.txt' => 'synced', 'd.txt' => 'orphan'], + 1, + ]; + yield 'provider not installed' => [ + static function (InspectionProject $project): void { + self::replace($project)->installed(['other/pkg' => '1.0.0']); + }, + ['a.txt' => 'orphan'], + 1, + ]; + yield 'provider no longer ships the file' => [ + static function (InspectionProject $project): void { + $project + ->provider('p/a', ['a.txt' => "v1\n", 'old.txt' => "old\n"]) + ->file('a.txt', "v1\n") + ->file('old.txt', "old\n") + ->track('a.txt', 'p/a') + ->track('old.txt', 'p/a') + ->provider('p/a', ['a.txt' => "v1\n"]); + }, + ['a.txt' => 'synced', 'old.txt' => 'orphan'], + 1, + ]; + } + + /** + * Tracks `ecs.php` in `preserve` mode, identical to its stub. + */ + private static function preserve(InspectionProject $project): InspectionProject + { + return $project + ->provider('p/a', ['ecs.php' => "v1\n"], ['ecs.php' => 'preserve']) + ->file('ecs.php', "v1\n") + ->track('ecs.php', 'p/a', 'preserve'); + } + + /** + * Tracks `a.txt` in `replace` mode, identical to its stub. + */ + private static function replace(InspectionProject $project): InspectionProject + { + return $project + ->provider('p/a', ['a.txt' => "v1\n"]) + ->file('a.txt', "v1\n") + ->track('a.txt', 'p/a'); + } +} diff --git a/tests/Provider/StrategyResolverProvider.php b/tests/Provider/StrategyResolverProvider.php new file mode 100644 index 0000000..b5b71f1 --- /dev/null +++ b/tests/Provider/StrategyResolverProvider.php @@ -0,0 +1,45 @@ +}> + */ + public static function destinations(): iterable + { + yield 'codespell ignore list' => ['.codespellignore', ListMergeStrategy::class]; + yield 'Docker ignore list' => ['.dockerignore', ListMergeStrategy::class]; + yield 'dotenv template' => ['.env.dist', TextMergeStrategy::class]; + yield 'EditorConfig backup' => ['.editorconfig.bak', TextMergeStrategy::class]; + yield 'EditorConfig' => ['.editorconfig', IniMergeStrategy::class]; + yield 'ESLint ignore list' => ['.eslintignore', ListMergeStrategy::class]; + yield 'Git ignore list' => ['.gitignore', ListMergeStrategy::class]; + yield 'ignore list name without leading dot' => ['gitignore', TextMergeStrategy::class]; + yield 'markdownlint ignore list' => ['.markdownlintignore', ListMergeStrategy::class]; + yield 'nested Git attributes list' => ['sub/dir/.gitattributes', ListMergeStrategy::class]; + yield 'nested INI file' => ['config/php.ini', IniMergeStrategy::class]; + yield 'npm ignore list' => ['.npmignore', ListMergeStrategy::class]; + yield 'Prettier ignore list' => ['.prettierignore', ListMergeStrategy::class]; + yield 'Stylelint ignore list' => ['.stylelintignore', ListMergeStrategy::class]; + } + + /** + * @return iterable}> + */ + public static function kinds(): iterable + { + yield 'ini' => [MergeStrategyKind::Ini, IniMergeStrategy::class]; + yield 'list' => [MergeStrategyKind::ListFile, ListMergeStrategy::class]; + yield 'text' => [MergeStrategyKind::Text, TextMergeStrategy::class]; + } +} diff --git a/tests/Provider/SymfonyOutputWriterProvider.php b/tests/Provider/SymfonyOutputWriterProvider.php new file mode 100644 index 0000000..e81fa72 --- /dev/null +++ b/tests/Provider/SymfonyOutputWriterProvider.php @@ -0,0 +1,24 @@ + + */ + public static function writes(): iterable + { + yield 'stderr falls back to the primary output' => ['writeStderr', false, false, 'plain fallback']; + yield 'stderr goes to the console error output' => ['writeStderr', true, true, 'error line']; + yield 'stdout keeps angle-bracket tokens' => ['writeStdout', false, false, '']; + yield 'stdout keeps style tags when decorated' => ['writeStdout', false, true, 'hello']; + } +} diff --git a/tests/Provider/VendorDirResolverProvider.php b/tests/Provider/VendorDirResolverProvider.php new file mode 100644 index 0000000..1a9a85f --- /dev/null +++ b/tests/Provider/VendorDirResolverProvider.php @@ -0,0 +1,60 @@ + + */ + public static function environmentValues(): iterable + { + yield 'absolute path with trailing separator' => ['/opt/shared-vendor/', '/opt/shared-vendor']; + yield 'absolute POSIX path ending in a drive root' => ['/foo/C:/', '/foo/C:']; + yield 'relative path with a drive letter in the middle' => ['prefix/C:/suffix', '{root}/prefix/C:/suffix']; + yield 'relative path' => ['custom-vendor', '{root}/custom-vendor']; + yield 'Windows absolute path' => ['C:\\opt\\vendor', 'C:\\opt\\vendor']; + yield 'Windows drive root with backslash' => ['C:\\', 'C:\\']; + yield 'Windows drive root with forward slash' => ['D:/', 'D:/']; + yield 'Windows drive-relative path' => ['C:vendor', '{root}/C:vendor']; + } + + /** + * @return iterable, string, string}> + */ + public static function manifestSettings(): iterable + { + yield 'absolute vendor-dir' => [ + ['config' => ['vendor-dir' => '/opt/shared-vendor']], + '', + '/opt/shared-vendor', + ]; + yield 'relative vendor-dir' => [ + ['config' => ['vendor-dir' => 'third-party']], + '', + '{root}/third-party', + ]; + yield 'missing vendor-dir' => [ + ['name' => 'test/no-vendor-dir-config'], + '', + '{root}/vendor', + ]; + yield 'empty vendor-dir' => [ + ['config' => ['vendor-dir' => '']], + '', + '{root}/vendor', + ]; + yield 'trailing separators on root and vendor-dir' => [ + ['config' => ['vendor-dir' => 'custom/']], + '/', + '{root}/custom', + ]; + } +} diff --git a/tests/Scaffold/ApplierTest.php b/tests/Scaffold/ApplierTest.php deleted file mode 100644 index 39ea3a3..0000000 --- a/tests/Scaffold/ApplierTest.php +++ /dev/null @@ -1,255 +0,0 @@ -expectException(RuntimeException::class); - $this->expectExceptionMessage('destination'); - - // Traversal is caught before the realpath check; no real project dir needed. - $this->makeApplier()->apply( - $this->makeMapping(destination: '../../../etc/passwd'), - "{$this->tempDir}/project", - new ReplaceMode(), - null, - ); - } - - public function testNoWarningWrittenForSkippedPreserveFile(): void - { - $projectDir = "{$this->tempDir}/project"; - - mkdir($projectDir, 0o777, recursive: true); - file_put_contents($projectDir . '/output.txt', 'existing'); - - $this->makeSourceFile(); - $io = $this->createMock(IOInterface::class); - - $io->expects(self::never())->method('writeError'); - - $applier = new Applier( - new PackageAllowlist(['php-forge/test']), - new PathValidator(), - new Hasher(), - $io, - ); - - $applier->apply($this->makeMapping(), $projectDir, new PreserveMode(), null); - } - - public function testPreserveModeSkipsExistingFile(): void - { - $projectDir = "{$this->tempDir}/project"; - - mkdir($projectDir, 0o777, recursive: true); - file_put_contents($projectDir . '/output.txt', 'existing'); - - $this->makeSourceFile('stub'); - - $result = $this->makeApplier()->apply( - $this->makeMapping(), - $projectDir, - new PreserveMode(), - null, - ); - - self::assertSame( - ApplyOutcome::Skipped, - $result->outcome, - 'PreserveMode must skip writing the file if it already exists.', - ); - self::assertSame( - 'existing', - file_get_contents($projectDir . '/output.txt'), - 'PreserveMode must not overwrite existing files.', - ); - } - - public function testSourceTraversalThrows(): void - { - // 'validateDestination' runs first and needs the project dir to exist. - $projectDir = "{$this->tempDir}/project"; - - mkdir($projectDir, 0o777, recursive: true); - - $this->expectException(RuntimeException::class); - $this->expectExceptionMessage('source'); - - $this->makeApplier()->apply( - $this->makeMapping(source: '../../../etc/shadow'), - $projectDir, - new ReplaceMode(), - null, - ); - } - - public function testUnauthorizedProviderThrows(): void - { - $this->expectException(RuntimeException::class); - $this->expectExceptionMessage('php-forge/unauthorized'); - - $this->makeApplier([])->apply( - $this->makeMapping(providerName: 'php-forge/unauthorized'), - "{$this->tempDir}/project", - new ReplaceMode(), - null, - ); - } - - public function testUserModifiedFileForwardsWarningToIo(): void - { - $projectDir = "{$this->tempDir}/project"; - - mkdir($projectDir, 0o777, recursive: true); - file_put_contents($projectDir . '/output.txt', 'user-modified content'); - - $this->makeSourceFile('stub content'); - $io = $this->createMock(IOInterface::class); - - $io->expects(self::once()) - ->method('writeError') - ->with( - self::callback( - static fn(mixed $message): bool => is_string($message) - && str_starts_with($message, '[scaffold] ') - && str_contains($message, 'User-modified file skipped'), - ), - ); - - $applier = new Applier( - new PackageAllowlist(['php-forge/test']), - new PathValidator(), - new Hasher(), - $io, - ); - - $result = $applier->apply( - $this->makeMapping(), - $projectDir, - new ReplaceMode(), - 'sha256:' . hash('sha256', 'completely-different-content'), - ); - - self::assertSame( - ApplyOutcome::Skipped, - $result->outcome, - 'ReplaceMode must skip writing the file if it has been modified by the user.', - ); - } - - public function testValidReplaceModeWritesFile(): void - { - $projectDir = "{$this->tempDir}/project"; - - mkdir($projectDir, 0o777, recursive: true); - - $this->makeSourceFile(); - $result = $this->makeApplier()->apply( - $this->makeMapping(), - $projectDir, - new ReplaceMode(), - null, - ); - - self::assertSame( - ApplyOutcome::Written, - $result->outcome, - 'ReplaceMode must write the file if it does not exist or has not been modified by the user.', - ); - self::assertFileExists( - "$projectDir/output.txt", - 'ReplaceMode must create the file if it does not exist.', - ); - } - - protected function setUp(): void - { - $this->setUpTempDirectory(); - } - - protected function tearDown(): void - { - $this->tearDownTempDirectory(); - } - - /** - * Creates an instance of Applier with a specified allowlist for testing. - * - * @param list $allowedPackages List of allowed package names for the Applier's PackageAllowlist; defaults - * to ['php-forge/test']. - * - * @return Applier Configured Applier instance for testing, with the specified allowlist and a NullIO for output. - */ - private function makeApplier(array $allowedPackages = ['php-forge/test']): Applier - { - return new Applier( - new PackageAllowlist($allowedPackages), - new PathValidator(), - new Hasher(), - new NullIO(), - ); - } - - /** - * Builds a {@see FileMapping} fixture wired to the test provider path for use in the applier scenarios. - * - * @param string $destination Destination path relative to the project root. - * @param string $source Relative source path inside the provider root. - * @param string $providerName Provider package name for the mapping. - * - * @return FileMapping File mapping used for the test, with the specified destination, source, and provider. - */ - private function makeMapping( - string $destination = 'output.txt', - string $source = 'stubs/source.txt', - string $providerName = 'php-forge/test', - ): FileMapping { - return new FileMapping( - destination: $destination, - source: $source, - mode: FileMode::Replace, - providerName: $providerName, - providerPath: $this->tempDir . '/provider', - ); - } - - /** - * Creates the provider's stub file with the specified content. - * - * Does not touch the project's current destination file; tests that need a pre-existing destination create it - * directly from the scenario under test. - * - * @param string $content Content to write to the provider's stub file. - */ - private function makeSourceFile(string $content = 'stub content'): void - { - $path = "{$this->tempDir}/provider/stubs/source.txt"; - - $this->ensureTestDirectory(dirname($path)); - - file_put_contents($path, $content); - } -} diff --git a/tests/Scaffold/ExpectedStateTest.php b/tests/Scaffold/ExpectedStateTest.php new file mode 100644 index 0000000..5c31326 --- /dev/null +++ b/tests/Scaffold/ExpectedStateTest.php @@ -0,0 +1,208 @@ +tempDir)) + ->composer(['p/a']) + ->provider('p/a', ['a.txt' => "a\n"]) + ->file('vendor/p/a/composer.json', '{broken'); + + $state = ExpectedState::build($project->context(), []); + + Assert::same( + [$state->hasFailed('p/a'), $state->mapping('a.txt'), $state->warnings], + [true, null, [Message::SCAFFOLD_MANIFEST_LOAD_FAILED->getMessage('p/a', 'Syntax error')]], + 'Failed provider must be marked, contribute no mapping and be reported.', + ); + } + + public function lastAllowedProviderWinsPerDestination(): void + { + $project = (new InspectionProject($this->tempDir)) + ->composer(['p/a', 'p/b']) + ->provider('p/a', ['shared.txt' => "a\n", 'a.txt' => "a\n"]) + ->provider('p/b', ['shared.txt' => "b\n"]); + + $state = ExpectedState::build($project->context(), []); + + Assert::same( + [ + $state->mapping('shared.txt')?->providerName, + $state->mapping('a.txt')?->providerName, + $state->hasFailed('p/a'), + $state->warnings, + ], + ['p/b', 'p/a', false, []], + 'Later provider must win the shared destination without failures or warnings.', + ); + } + + public function notAllowedAndNotInstalledProvidersAreIgnored(): void + { + $project = (new InspectionProject($this->tempDir)) + ->composer(['p/a', 'p/missing']) + ->provider('p/a', ['a.txt' => "a\n"]) + ->provider('p/denied', ['d.txt' => "d\n"]); + + $state = ExpectedState::build($project->context(), []); + + Assert::same( + [$state->mapping('d.txt'), $state->hasFailed('p/missing'), $state->mapping('a.txt')?->providerName], + [null, false, 'p/a'], + 'Only the allowed and installed provider must contribute.', + ); + } + + public function orphanReportListsTenOrphansAndCountsTheOthers(): void + { + $names = array_map( + static fn(int $index): string => "f{$index}.txt", + range(0, 11), + ); + + $lines = (new ExpectedState([])) + ->orphanReport( + array_fill_keys( + $names, + [ + 'hash' => 'sha256:x', + 'provider' => 'p/a', + 'source' => 's', + 'mode' => 'replace', + ], + ), + ); + + Assert::same( + $lines, + [ + ConsoleMessage::SCAFFOLD_ORPHAN_HEADER->getMessage(12, ConsoleMessage::FRAGMENT_FILES->getMessage()), + ...array_map( + static fn(string $name): string => ConsoleMessage::SCAFFOLD_ORPHAN_ENTRY->getMessage($name, 'p/a'), + array_slice($names, 0, 10), + ), + ConsoleMessage::SCAFFOLD_ORPHAN_MORE->getMessage(2), + ], + "Header, ten files and the remainder line of '2' expected.", + ); + } + + public function orphanReportListsTenOrphansWithoutRemainderLine(): void + { + $names = array_map( + static fn(int $index): string => "f{$index}.txt", + range(0, 9), + ); + + $lines = (new ExpectedState([])) + ->orphanReport( + array_fill_keys( + $names, + [ + 'hash' => 'sha256:x', + 'provider' => 'p/a', + 'source' => 's', + 'mode' => 'replace', + ], + ), + ); + + Assert::same( + $lines, + [ + ConsoleMessage::SCAFFOLD_ORPHAN_HEADER->getMessage(10, ConsoleMessage::FRAGMENT_FILES->getMessage()), + ...array_map( + static fn(string $name): string => ConsoleMessage::SCAFFOLD_ORPHAN_ENTRY->getMessage($name, 'p/a'), + $names, + ), + ], + 'Header and ten files expected, without a remainder line.', + ); + } + + /** + * Ensures ejected, shipped and failed-provider entries are not orphans, even when the failed provider comes first. + */ + public function orphansExcludeEjectedShippedAndFailedProviderEntries(): void + { + $project = (new InspectionProject($this->tempDir)) + ->composer(['p/broken', 'p/a']) + ->provider('p/a', ['a.txt' => "a\n"]) + ->provider('p/broken', ['b.txt' => "b\n"]) + ->file('vendor/p/broken/composer.json', '{broken'); + + $state = ExpectedState::build($project->context(), []); + + $entry = [ + 'hash' => 'sha256:x', + 'source' => 's', + 'mode' => 'replace', + ]; + + Assert::same( + [ + array_keys( + $state->orphans( + [ + 'a.txt' => [...$entry, 'provider' => 'p/a'], + 'gone.txt' => [...$entry, 'provider' => 'p/a'], + 123 => [...$entry, 'provider' => 'p/a'], + 'ejected.txt' => [...$entry, 'provider' => 'p/a', 'ejected' => true], + 'b.txt' => [...$entry, 'provider' => 'p/broken'], + 'old.txt' => [...$entry, 'provider' => 'p/removed'], + ], + ), + ), + $state->failedProviders(), + array_keys($state->all()), + ], + [['gone.txt', 123, 'old.txt'], ['p/broken'], ['a.txt']], + 'Only unshipped, non-ejected entries of loadable providers must be orphans.', + ); + } + + /** + * Ensures a provider root outside vendor is reported and the default root still loads the manifest. + */ + public function providerRootWarningIsCollected(): void + { + $project = (new InspectionProject($this->tempDir)) + ->composer(['p/a']) + ->provider('p/a', ['a.txt' => "a\n"]); + + $state = ExpectedState::build($project->context(), ['p/a' => ['path' => '/elsewhere/p/a']]); + + Assert::same( + [$state->warnings, $state->mapping('a.txt')?->providerName], + [[ConsoleMessage::SCAFFOLD_PROVIDER_ROOT_OUTSIDE_VENDOR->getMessage('p/a')], 'p/a'], + 'Root warning must be collected and the default root must still load the manifest.', + ); + } +} diff --git a/tests/Scaffold/FileApplierTest.php b/tests/Scaffold/FileApplierTest.php new file mode 100644 index 0000000..0767a09 --- /dev/null +++ b/tests/Scaffold/FileApplierTest.php @@ -0,0 +1,137 @@ +tempDir)) + ->stub('p/a', 'output.txt', 'stub content') + ->file('output.txt', 'user-modified content'); + + $out = new BufferedOutputWriter(); + + $result = $this->applier($out)->apply( + $this->mapping('output.txt', 'stubs/output.txt', 'p/a'), + $this->tempDir, + new ReplaceMode(), + 'sha256:' . hash('sha256', 'completely-different-content'), + ); + + Assert::same( + [$result->outcome, $out->stderrBuffer], + [ + ApplyOutcome::Skipped, + Message::SCAFFOLD_PREFIXED->getMessage( + Message::SCAFFOLD_USER_MODIFIED_SKIPPED->getMessage('output.txt'), + ) . PHP_EOL, + ], + "User-modified file must be 'Skipped' and its warning written to stderr.", + ); + } + + /** + * Ensures the mode result is returned and nothing is written to stderr when the mode has no warning. + */ + public function returnsModeResultWithoutOutputWhenModeHasNoWarning(): void + { + (new InspectionProject($this->tempDir)) + ->stub('p/a', 'output.txt', 'stub') + ->file('output.txt', 'existing'); + + $out = new BufferedOutputWriter(); + + $result = $this->applier($out)->apply( + $this->mapping('output.txt', 'stubs/output.txt', 'p/a'), + $this->tempDir, + new PreserveMode(), + null, + ); + + FileAssert::contentSame("{$this->tempDir}/output.txt", 'existing', 'Existing file must not be overwritten.'); + Assert::same( + [$result->outcome, $out->stderrBuffer], + [ApplyOutcome::Skipped, ''], + "Preserved file must be 'Skipped' without any stderr output.", + ); + } + + /** + * Ensures a mapping of a provider that is not allowed, or with a traversal path, is rejected before any mode runs. + */ + #[DataProvider(FileApplierProvider::class . '::rejectedMappings')] + public function throwRuntimeExceptionForRejectedMapping( + string $destination, + string $source, + string $providerName, + string $message, + ): void { + Expect::exception(RuntimeException::class) + ->withMessage($message); + + $this->applier(new BufferedOutputWriter())->apply( + $this->mapping($destination, $source, $providerName), + $this->tempDir, + new ReplaceMode(), + null, + ); + } + + /** + * Creates a {@see FileApplier} that allows the `p/a` provider and writes warnings to `$out`. + * + * @param BufferedOutputWriter $out Output sink of the mode warnings. + * + * @return FileApplier Applier configured for the test. + */ + private function applier(BufferedOutputWriter $out): FileApplier + { + return new FileApplier(new ProjectConfig(['p/a']), new PathValidator(), $out); + } + + /** + * Returns the replace mapping of `$destination` to `$source` in the provider directory of `p/a`. + * + * @param string $destination Destination path relative to the project root. + * @param string $source Source path relative to the provider root. + * @param string $providerName Provider package name. + * + * @return FileMapping Mapping used for the test. + */ + private function mapping(string $destination, string $source, string $providerName): FileMapping + { + return new FileMapping($destination, $source, FileMode::Replace, $providerName, "{$this->tempDir}/vendor/p/a"); + } +} diff --git a/tests/Scaffold/Lock/HasherTest.php b/tests/Scaffold/Lock/HasherTest.php index 72a44f8..492e3ac 100644 --- a/tests/Scaffold/Lock/HasherTest.php +++ b/tests/Scaffold/Lock/HasherTest.php @@ -4,162 +4,87 @@ namespace PHPForge\Scaffold\Tests\Scaffold\Lock; +use PHPForge\Scaffold\Exception\Message; use PHPForge\Scaffold\Scaffold\Lock\Hasher; use PHPForge\Scaffold\Tests\Support\TempDirectoryTrait; -use PHPUnit\Framework\Attributes\Group; -use PHPUnit\Framework\TestCase; use RuntimeException; -use Xepozz\InternalMocker\MockerState; +use Testo\Assert; +use Testo\Codecov\Covers; +use Testo\Data\DataSet; +use Testo\Expect; +use Testo\Test; -use function strlen; +use function file_put_contents; /** * Unit tests for {@see Hasher} file hash computation. */ -#[Group('scaffold')] -#[Group('lock')] -final class HasherTest extends TestCase +#[Test] +#[Covers(Hasher::class)] +final class HasherTest { use TempDirectoryTrait; - public function testEqualsIsCaseSensitive(): void + #[DataSet(['hello', 'sha256:2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824'], 'content')] + #[DataSet(['', 'sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855'], 'empty file')] + public function hashReturnsPrefixedSha256Digest(string $content, string $expected): void { - self::assertFalse( - (new Hasher())->equals('sha256:ABC', 'sha256:abc'), - 'Hash comparison should be case-sensitive', + file_put_contents( + "{$this->tempDir}/file.txt", + $content, ); - } - - public function testEqualsReturnsFalseForDifferentHashes(): void - { - self::assertFalse( - (new Hasher())->equals('sha256:abc', 'sha256:xyz'), - 'Hash comparison should return false for different hashes', - ); - } - public function testEqualsReturnsTrueForIdenticalHashes(): void - { - self::assertTrue( - (new Hasher())->equals('sha256:abc', 'sha256:abc'), - 'Hash comparison should return true for identical hashes', + Assert::same( + Hasher::hash("{$this->tempDir}/file.txt"), + $expected, + 'Hash must be the prefixed SHA-256 digest.', ); } - public function testHashDiffersAfterContentChange(): void + public function throwRuntimeExceptionWhenFileIsMissing(): void { - $file = "{$this->tempDir}/file.txt"; - - file_put_contents($file, 'original'); - - $hasher = new Hasher(); + $file = "{$this->tempDir}/nonexistent.txt"; - $before = $hasher->hash($file); + Expect::exception(RuntimeException::class) + ->withMessage( + Message::FILESYSTEM_FAILED->getMessage( + Message::LOCK_HASH_FAILED->getMessage($file), + "hash_file({$file}): Failed to open stream: No such file or directory", + ), + ); - file_put_contents($file, 'modified'); - - self::assertNotSame( - $before, - $hasher->hash($file), - 'Hash should differ after file content changes', - ); + Hasher::hash($file); } - public function testHashOfNonExistentFileThrows(): void - { - $this->expectException(RuntimeException::class); - - (new Hasher())->hash("{$this->tempDir}/nonexistent.txt"); - } - - public function testHashOfSameContentIsIdempotent(): void - { - $file = "{$this->tempDir}/file.txt"; - - file_put_contents($file, 'deterministic content'); - - $hasher = new Hasher(); - - self::assertSame( - $hasher->hash($file), - $hasher->hash($file), - 'Hash should be idempotent for the same content', - ); - } - - public function testHashReturnsSha256PrefixedString(): void - { - $file = $this->tempDir . '/file.txt'; - - file_put_contents($file, 'hello'); - - $hash = (new Hasher())->hash($file); - - self::assertStringStartsWith( - 'sha256:', - $hash, - "Hash should start with 'sha256:' prefix", - ); - // 'sha256:' (7) + 64 hex chars - self::assertSame( - 7 + 64, - strlen($hash), - "Hash length should be '71' characters", - ); - } - - public function testHashThrowsWhenFileExistsButIsUnreadable(): void + public function throwRuntimeExceptionWhenFileIsUnreadable(): void { $file = "{$this->tempDir}/unreadable.txt"; - file_put_contents($file, 'content'); - - // Force `is_readable()` inside the Lock namespace to report false while the file still exists. - MockerState::addCondition( - 'PHPForge\\Scaffold\\Scaffold\\Lock', - 'is_readable', - [$file], - false, + file_put_contents( + $file, + 'content', ); - $this->expectException(RuntimeException::class); - $this->expectExceptionMessage('file is unreadable or does not exist'); + $this->restrictFileAccess($file, 0o000); - (new Hasher())->hash($file); - } + Expect::exception(RuntimeException::class) + ->withMessage( + Message::FILESYSTEM_FAILED->getMessage( + Message::LOCK_HASH_FAILED->getMessage($file), + "hash_file({$file}): Failed to open stream: Permission denied", + ), + ); - public function testHashThrowsWhenHashFileReturnsFalse(): void - { - $file = "{$this->tempDir}/broken-hash.txt"; - - file_put_contents($file, 'content'); - - // Real file is readable; force `hash_file()` itself to report false to hit the post-read failure branch. - MockerState::addCondition( - 'PHPForge\\Scaffold\\Scaffold\\Lock', - 'hash_file', - [ - 'sha256', - $file, - false, - [], - ], - false, - ); - - $this->expectException(RuntimeException::class); - $this->expectExceptionMessage('file is unreadable or does not exist'); - - (new Hasher())->hash($file); + Hasher::hash($file); } - protected function setUp(): void + public function throwRuntimeExceptionWhenPathIsADirectory(): void { - $this->setUpTempDirectory(); - } + Expect::exception(RuntimeException::class) + ->withMessageContaining( + Message::LOCK_HASH_FAILED->getMessage($this->tempDir) . ' Reason: hash_file(', + ); - protected function tearDown(): void - { - $this->tearDownTempDirectory(); + Hasher::hash($this->tempDir); } } diff --git a/tests/Scaffold/Lock/LockFileTest.php b/tests/Scaffold/Lock/LockFileTest.php index 6713d97..046abb4 100644 --- a/tests/Scaffold/Lock/LockFileTest.php +++ b/tests/Scaffold/Lock/LockFileTest.php @@ -4,76 +4,66 @@ namespace PHPForge\Scaffold\Tests\Scaffold\Lock; -use JsonException; +use PHPForge\Scaffold\Exception\Message; use PHPForge\Scaffold\Scaffold\Lock\LockFile; -use PHPForge\Scaffold\Tests\Support\TempDirectoryTrait; -use PHPUnit\Framework\Attributes\Group; -use PHPUnit\Framework\TestCase; +use PHPForge\Scaffold\Tests\Provider\LockFileProvider; +use PHPForge\Scaffold\Tests\Support\{FileAssert, TempDirectoryTrait}; use RuntimeException; -use Xepozz\InternalMocker\MockerState; +use Testo\Assert; +use Testo\Codecov\Covers; +use Testo\Data\{DataProvider, DataSet}; +use Testo\Expect; +use Testo\Test; + +use function file_get_contents; +use function file_put_contents; +use function glob; +use function mkdir; +use function preg_match; +use function preg_quote; +use function str_contains; +use function str_replace; +use function unlink; /** - * Unit tests for {@see LockFile} read/write operations and hash lookup. + * Unit tests for {@see LockFile} read/write operations, deterministic formatting, and error reporting. + * + * {@see LockFileProvider} for test case data providers. */ -#[Group('scaffold')] -#[Group('lock')] -final class LockFileTest extends TestCase +#[Test] +#[Covers(LockFile::class)] +final class LockFileTest { use TempDirectoryTrait; - public function testExistsReturnsFalseWhenFileAbsent(): void - { - self::assertFalse( - (new LockFile($this->tempDir))->exists(), - 'Lock file should not exist before being created', - ); - } - - public function testExistsReturnsTrueAfterWrite(): void + public function existsOnlyAfterWrite(): void { $lock = new LockFile($this->tempDir); + $before = $lock->exists(); + $lock->write(['providers' => [], 'files' => []]); - self::assertTrue( - $lock->exists(), - 'Lock file should exist after being created', + Assert::same( + [$before, $lock->exists()], + [false, true], + "Lock must exist only after 'write()'.", ); } - public function testGetHashAtScaffoldReturnsNullForUntrackedDestination(): void + public function getPathJoinsProjectRootWithOneSeparator(): void { - $lock = new LockFile($this->tempDir); - - $lock->write( + Assert::same( + [(new LockFile($this->tempDir))->getPath(), (new LockFile('/tmp/project/'))->getPath()], [ - 'providers' => [], - 'files' => [ - 'config/params.php' => [ - 'hash' => 'sha256:abc', - 'provider' => 'p/n', - 'source' => 'stubs/a.php', - 'mode' => 'replace', - ], - ], + $this->tempDir . DIRECTORY_SEPARATOR . 'scaffold-lock.json', + '/tmp/project' . DIRECTORY_SEPARATOR . 'scaffold-lock.json', ], - ); - - self::assertNull( - $lock->getHashAtScaffold('config/web.php'), - "Return 'null' for untracked destination", - ); - } - - public function testGetHashAtScaffoldReturnsNullWhenMissing(): void - { - self::assertNull( - (new LockFile($this->tempDir))->getHashAtScaffold('config/params.php'), - "Return 'null' when hash is missing", + 'Lock path must hold one separator before the file name.', ); } - public function testGetHashAtScaffoldReturnsRecordedHash(): void + public function readCachesResultAfterFirstCall(): void { $lock = new LockFile($this->tempDir); @@ -81,324 +71,303 @@ public function testGetHashAtScaffoldReturnsRecordedHash(): void [ 'providers' => [], 'files' => [ - 'config/params.php' => [ - 'hash' => 'sha256:deadbeef', - 'provider' => 'p/n', - 'source' => 'stubs/a.php', - 'mode' => 'replace', - ], + 'a.txt' => ['hash' => 'sha256:abc', 'provider' => 'pkg/a', 'source' => 'stubs/a.txt', 'mode' => 'replace'], ], ], ); - self::assertSame( - 'sha256:deadbeef', - $lock->getHashAtScaffold('config/params.php'), - 'Return the recorded hash for the tracked destination', + $first = $lock->read(); + + unlink($lock->getPath()); + + Assert::same( + $lock->read(), + $first, + 'Cached data must be returned without reading the file again.', ); } - public function testGetPathReturnsExpectedPath(): void + public function readPreservesIntegerLikeDestinationsAfterWrite(): void { - self::assertSame( - rtrim($this->tempDir, '/\\') . DIRECTORY_SEPARATOR . 'scaffold-lock.json', - (new LockFile($this->tempDir))->getPath(), - 'Return the expected lock file path', + $entry = [ + 'hash' => 'sha256:abc', + 'provider' => 'pkg/name', + 'source' => '0', + 'mode' => 'replace', + ]; + + $lock = new LockFile($this->tempDir); + + $lock->write(['providers' => [], 'files' => [0 => $entry, 1 => $entry]]); + + Assert::true( + str_contains((string) file_get_contents($lock->getPath()), '"0": {'), + "Integer-like destination '0' must stay a JSON object key.", + ); + Assert::same( + $lock->read()['files']['1'] ?? null, + $entry, + 'Entry must be readable by its string name.', ); } - public function testGetPathStripsTrailingSlashFromProjectRoot(): void + public function readReturnsEmptyStructureWhenFileIsMissing(): void { - self::assertSame( - '/tmp/project' . DIRECTORY_SEPARATOR . 'scaffold-lock.json', - (new LockFile('/tmp/project/'))->getPath(), - 'Trailing separator on the project root must not produce a double separator in the lock file path.', + Assert::same( + (new LockFile($this->tempDir))->read(), + ['providers' => [], 'files' => []], + 'Missing lock must read as empty providers and files.', ); } - public function testReadCachesResultAfterFirstCall(): void + public function readReturnsWhatWasWritten(): void { - $lock = new LockFile($this->tempDir); - - $lock->write( - [ - 'providers' => [], - 'files' => [ - 'a.txt' => [ - 'hash' => 'sha256:abc', - 'provider' => 'pkg/a', - 'source' => 'stubs/a.txt', - 'mode' => 'replace', - ], - ], + $data = [ + 'providers' => ['pkg/name' => ['path' => '/vendor/pkg/name']], + 'files' => [ + 'config/params.php' => ['hash' => 'sha256:abc', 'provider' => 'pkg/name', 'mode' => 'preserve'], ], - ); + ]; - $first = $lock->read(); + (new LockFile($this->tempDir))->write($data); - // Remove the file from disk subsequent reads must still hit the in-memory cache. - unlink($this->tempDir . '/scaffold-lock.json'); - - self::assertSame( - $first, - $lock->read(), - 'Must return the cached data without touching the filesystem again.', + Assert::same( + (new LockFile($this->tempDir))->read(), + $data, + 'Lock data must survive a write/read round trip.', ); } - public function testReadPreservesProvidersEntries(): void + public function throwRuntimeExceptionWhenDataCannotBeEncoded(): void { $lock = new LockFile($this->tempDir); - $lock->write( - [ - 'providers' => [ - 'pkg/name' => ['path' => '/vendor/pkg/name'], - ], - 'files' => [], - ], - ); + Expect::exception(RuntimeException::class) + ->withMessage( + Message::LOCK_ENCODE_FAILED->getMessage( + $lock->getPath(), + 'Malformed UTF-8 characters, possibly incorrectly encoded', + ), + ) + ->withCode(0); - $data = $lock->read(); - - self::assertArrayHasKey( - 'providers', - $data, - "Must include the 'providers' key in the returned structure.", - ); - self::assertSame( - ['path' => '/vendor/pkg/name'], - $data['providers']['pkg/name'] ?? null, - 'Provider entries persisted on disk must be preserved by read.', - ); + $lock->write(['providers' => ["bad\xB1name" => []], 'files' => []]); } - public function testReadReturnsDefaultStructureWhenMissing(): void + #[DataProvider(LockFileProvider::class . '::invalidContents')] + public function throwRuntimeExceptionWhenLockContentIsInvalid(string $content, string $message): void { - $data = (new LockFile($this->tempDir))->read(); + $lock = new LockFile($this->tempDir); - self::assertSame( - [], - $data['providers'], - 'Return empty providers array when lock file is missing', - ); - self::assertSame( - [], - $data['files'], - 'Return empty files array when lock file is missing', + file_put_contents( + $lock->getPath(), + $content, ); - } - - public function testReadThrowsOnMalformedJson(): void - { - file_put_contents($this->tempDir . '/scaffold-lock.json', '{ invalid json }'); - $this->expectException(JsonException::class); + Expect::exception(RuntimeException::class) + ->withMessage( + str_replace('{path}', $lock->getPath(), $message), + ) + ->withCode(0); - (new LockFile($this->tempDir))->read(); + $lock->read(); } - public function testReadThrowsWhenFileGetContentsFails(): void + public function throwRuntimeExceptionWhenLockFileIsUnreadable(): void { $lock = new LockFile($this->tempDir); - // Ask the LockFile for the exact path so the mocker match honors the platform's DIRECTORY_SEPARATOR. $path = $lock->getPath(); - file_put_contents($path, '{"providers":{},"files":{}}'); - - MockerState::addCondition( - 'PHPForge\\Scaffold\\Scaffold\\Lock', - 'file_get_contents', - [$path, false, null, 0, null], - false, + file_put_contents( + $path, + '{"providers":{},"files":{}}', ); - $this->expectException(RuntimeException::class); - $this->expectExceptionMessage('Could not read lock file'); - - $lock->read(); - } - - public function testReadThrowsWhenJsonDecodesToNonObject(): void - { - // Valid JSON, but it decodes to a scalar `is_array($decoded)` must be `false`, triggering the structural check. - file_put_contents($this->tempDir . '/scaffold-lock.json', '"just a string"'); + $this->restrictFileAccess($path, 0o000); - $this->expectException(RuntimeException::class); - $this->expectExceptionMessage('does not contain a valid JSON object'); + Expect::exception(RuntimeException::class) + ->withMessage( + Message::FILESYSTEM_FAILED->getMessage( + Message::LOCK_UNREADABLE->getMessage($path), + "file_get_contents({$path}): Failed to open stream: Permission denied", + ), + ); - (new LockFile($this->tempDir))->read(); + $lock->read(); } - public function testWriteAndReadRoundTrip(): void + public function throwRuntimeExceptionWhenRenameFails(): void { $lock = new LockFile($this->tempDir); - $lock->write( - [ - 'providers' => [], - 'files' => [ - 'config/params.php' => [ - 'hash' => 'sha256:abc', - 'provider' => 'pkg/name', - 'mode' => 'preserve', - ], - ], - ], - ); + $path = $lock->getPath(); - $data = $lock->read(); + // A non-empty directory at the lock path makes the rename of the temporary file fail. + mkdir("{$path}/entry", 0o777, true); - $entry = $data['files']['config/params.php'] ?? null; + $message = null; - if ($entry === null) { - self::fail("Expected 'config/params.php' entry in lock file."); + try { + $lock->write(['providers' => [], 'files' => []]); + } catch (RuntimeException $e) { + $message = $e->getMessage(); } - self::assertSame( - 'sha256:abc', - $entry['hash'], - 'Hash should match the value written to the lock file', + Assert::same( + preg_match( + '/^' . preg_quote(Message::LOCK_UNWRITABLE->getMessage($path) . ' Reason: rename(', '/') + . '.+\.$/', + (string) $message, + ), + 1, + "Failed 'rename()' must surface with the lock path and its reason.", ); - self::assertSame( - 'pkg/name', - $entry['provider'], - 'Provider should match the value written to the lock file', - ); - self::assertSame( - 'preserve', - $entry['mode'], - 'Mode should match the value written to the lock file', + Assert::same( + glob("{$path}*"), + [$path], + 'No temporary file may remain after a failed rename.', ); } - public function testWriteProducesValidJson(): void + public function throwRuntimeExceptionWhenWritingTemporaryFileFails(): void { - $lock = new LockFile($this->tempDir); + $lock = new LockFile("{$this->tempDir}/missing"); - $lock->write(['providers' => [], 'files' => []]); + Expect::exception(RuntimeException::class) + ->withMessageMatchingRegex( + '/^' . preg_quote( + Message::LOCK_UNWRITABLE->getMessage($lock->getPath()) . ' Reason: file_put_contents(', + '/', + ) + . '.+\): Failed to open stream: No such file or directory\.$/', + ); - $raw = file_get_contents($this->tempDir . '/scaffold-lock.json'); + $lock->write(['providers' => [], 'files' => []]); + } - self::assertNotFalse( - $raw, - 'Failed to read the lock file', - ); + public function writeEncodesEmptyMapsAsObjects(): void + { + $lock = new LockFile($this->tempDir); - $decoded = json_decode($raw, associative: true); + $lock->write(['providers' => [], 'files' => []]); - self::assertIsArray( - $decoded, - 'Decoded JSON should be an array', + FileAssert::contentSame( + $lock->getPath(), + "{\n \"providers\": {},\n \"files\": {}\n}\n", + "Empty maps must be '{}' and the file must end with one newline.", ); } - public function testWriteThrowsWhenPersistenceFails(): void + public function writePreservesUnknownEntryKeysOfRewrittenEntries(): void { $lock = new LockFile($this->tempDir); - $path = $lock->getPath(); - - $tmp = "{$path}.tmp"; + file_put_contents( + $lock->getPath(), + '{"providers": {}, "files": {' + . '"a.txt": {"hash": "sha256:old", "provider": "p/a", "source": "a.txt", "mode": "replace", "ejected": true,' + . ' "future": [1]},' + . '"b.txt": {"hash": "sha256:b", "provider": "p/a", "source": "b.txt", "mode": "replace", "other": true}' + . '}}', + ); - // Simulate `file_put_contents` succeeding but `rename` failing, exercising the cleanup + throw branch. - MockerState::addCondition( - 'PHPForge\\Scaffold\\Scaffold\\Lock', - 'rename', + $lock->read(); + $lock->write( [ - $tmp, - $path, - null, + 'providers' => [], + 'files' => [ + 'a.txt' => [ + 'hash' => 'sha256:new', + 'provider' => 'p/a', + 'source' => 'a.txt', + 'mode' => 'replace', + 'stub-hash' => 'sha256:stub', + 'adopted' => true, + ], + ], ], - false, ); - $this->expectException(RuntimeException::class); - $this->expectExceptionMessage('Could not write lock file'); - - $lock->write(['providers' => [], 'files' => []]); + Assert::same( + $lock->read()['files'], + [ + 'a.txt' => [ + 'hash' => 'sha256:new', + 'provider' => 'p/a', + 'source' => 'a.txt', + 'mode' => 'replace', + 'stub-hash' => 'sha256:stub', + 'adopted' => true, + 'future' => [1], + ], + ], + 'Only unknown entry keys may survive the rewrite.', + ); } - public function testWriteUnlinksOrphanTmpFileAfterPersistenceFailure(): void + #[DataSet([true], 'after read')] + #[DataSet([false], 'without prior read')] + public function writePreservesUnknownTopLevelKeys(bool $readFirst): void { $lock = new LockFile($this->tempDir); - $path = $lock->getPath(); - - $tmp = "{$path}.tmp"; - - MockerState::addCondition( - 'PHPForge\\Scaffold\\Scaffold\\Lock', - 'rename', - [ - $tmp, - $path, - null, - ], - false, + file_put_contents( + $lock->getPath(), + '{"version": 2, "providers": {}, "files": {}, "ejected": ["a.txt"]}', ); - $caught = null; - - try { - $lock->write(['providers' => [], 'files' => []]); - } catch (RuntimeException $e) { - $caught = $e; - } + $lock->write($readFirst ? $lock->read() : ['providers' => [], 'files' => []]); - self::assertNotNull( - $caught, - 'The forced rename failure must still surface as a RuntimeException so the caller can react.', - ); - self::assertFileDoesNotExist( - $tmp, - "After 'rename' fails, the cleanup branch must 'unlink' the orphan '.tmp' sidecar to avoid stale content.", + FileAssert::contentSame( + $lock->getPath(), + "{\n \"providers\": {},\n \"files\": {},\n \"version\": 2,\n \"ejected\": [\n" + . " \"a.txt\"\n ]\n}\n", + 'Unknown top-level keys must survive a rewrite.', ); } - public function testWriteUsesUnescapedSlashes(): void + public function writeSortsKeysInByteOrder(): void { + $entry = [ + 'hash' => 'h', + 'provider' => 'p/b', + 'source' => 's', + 'mode' => 'replace', + ]; + $lock = new LockFile($this->tempDir); $lock->write( [ - 'providers' => [], - 'files' => [ - 'config/params.php' => [ - 'hash' => 'sha256:abc', - 'provider' => 'pkg/name', - 'mode' => 'replace', - ], + 'providers' => [ + 'p/b' => ['version' => '1.0.0', 'path' => 'vendor/p/b'], + 'p/a' => ['version' => '2.0.0', 'path' => 'vendor/p/a'], ], + 'files' => ['b.txt' => $entry, 'B.txt' => $entry, '.a' => $entry, '10' => $entry, '9' => $entry], ], ); - $raw = file_get_contents($this->tempDir . '/scaffold-lock.json'); - - self::assertNotFalse( - $raw, - 'Failed to read the lock file', + $expectedEntry = "{\n \"hash\": \"h\",\n \"provider\": \"p/b\",\n" + . " \"source\": \"s\",\n \"mode\": \"replace\"\n }"; + + FileAssert::contentSame( + $lock->getPath(), + "{\n \"providers\": {\n" + . " \"p/a\": {\n \"version\": \"2.0.0\",\n" + . " \"path\": \"vendor/p/a\"\n },\n" + . " \"p/b\": {\n \"version\": \"1.0.0\",\n" + . " \"path\": \"vendor/p/b\"\n }\n" + . " },\n" + . " \"files\": {\n" + . " \".a\": {$expectedEntry},\n" + . " \"10\": {$expectedEntry},\n" + . " \"9\": {$expectedEntry},\n" + . " \"B.txt\": {$expectedEntry},\n" + . " \"b.txt\": {$expectedEntry}\n" + . " }\n" + . "}\n", + 'Keys must be sorted in byte order, independent of insertion order.', ); - self::assertStringContainsString( - 'config/params.php', - $raw, - 'File paths should be written with unescaped slashes', - ); - self::assertStringNotContainsString( - 'config\/params.php', - $raw, - 'File paths should not contain escaped slashes', - ); - } - - protected function setUp(): void - { - $this->setUpTempDirectory(); - } - - protected function tearDown(): void - { - $this->tearDownTempDirectory(); } } diff --git a/tests/Scaffold/MappingMergerTest.php b/tests/Scaffold/MappingMergerTest.php new file mode 100644 index 0000000..67cae3c --- /dev/null +++ b/tests/Scaffold/MappingMergerTest.php @@ -0,0 +1,45 @@ + $other, '123' => $numeric], + 'Last mapping must win and an integer-like destination must be kept.', + ); + } +} diff --git a/tests/Scaffold/Modes/AppendModeTest.php b/tests/Scaffold/Modes/AppendModeTest.php index 6fe2761..c1a47ac 100644 --- a/tests/Scaffold/Modes/AppendModeTest.php +++ b/tests/Scaffold/Modes/AppendModeTest.php @@ -5,982 +5,99 @@ namespace PHPForge\Scaffold\Tests\Scaffold\Modes; use PHPForge\Scaffold\Manifest\{FileMapping, FileMode}; +use PHPForge\Scaffold\Merge\MergeStrategyKind; use PHPForge\Scaffold\Scaffold\Lock\Hasher; use PHPForge\Scaffold\Scaffold\Modes\{AppendMode, ApplyOutcome}; -use PHPForge\Scaffold\Tests\Support\TempDirectoryTrait; -use PHPUnit\Framework\TestCase; -use RuntimeException; -use Xepozz\InternalMocker\MockerState; +use PHPForge\Scaffold\Tests\Support\{InspectionProject, TempDirectoryTrait}; +use Testo\Assert; +use Testo\Codecov\Covers; +use Testo\Test; + +use function file_get_contents; /** - * Unit tests for {@see AppendMode} scaffold file application strategy. + * Unit tests for {@see AppendMode} merging the stub into an existing destination with its merge strategy. + * + * The strategies own the merge rules; the shared mode behavior lives in {@see ModeContractTest}. */ -final class AppendModeTest extends TestCase +#[Test] +#[Covers(AppendMode::class)] +final class AppendModeTest { use TempDirectoryTrait; - public function testAppendsOnlyMissingLines(): void - { - $projectDir = "{$this->tempDir}/project"; - - mkdir($projectDir, 0o777, recursive: true); - file_put_contents($projectDir . '/output.txt', "alpha\nbeta\n"); - - $this->makeSourceFile("alpha\nbeta\ngamma\n"); - - (new AppendMode())->apply( - $this->makeMapping(), - $projectDir, - new Hasher(), - null, - ); - - self::assertSame( - "alpha\nbeta\ngamma\n", - file_get_contents($projectDir . '/output.txt'), - 'AppendMode must append only the lines not already present in the destination.', - ); - } - - public function testAppendsRepeatedProviderLinesWhenDestinationHasFewer(): void - { - $projectDir = "{$this->tempDir}/project"; - - mkdir($projectDir, 0o777, recursive: true); - - // Destination has one 'alpha'; stub has two. The second occurrence must be appended (multiplicity-preserving). - file_put_contents($projectDir . '/output.txt', "alpha\n"); - - $this->makeSourceFile("alpha\nalpha\n"); - - (new AppendMode())->apply( - $this->makeMapping(), - $projectDir, - new Hasher(), - null, - ); - - self::assertSame( - "alpha\nalpha\n", - file_get_contents($projectDir . '/output.txt'), - 'AppendMode must preserve provider line multiplicity instead of treating destination lines as a set.', - ); - } - - public function testAppendsTrailingNewlineWhenProviderLinesLandAtEnd(): void - { - $projectDir = "{$this->tempDir}/project"; - - mkdir($projectDir, 0o777, recursive: true); - - // Destination lacks a trailing newline; provider lines merged at the end must terminate the file with one. - file_put_contents($projectDir . '/output.txt', 'alpha'); - - $this->makeSourceFile("alpha\nbeta\n"); - - (new AppendMode())->apply( - $this->makeMapping(), - $projectDir, - new Hasher(), - null, - ); - - self::assertSame( - "alpha\nbeta\n", - file_get_contents($projectDir . '/output.txt'), - 'AppendMode must newline-terminate the file when provider lines land at the end.', - ); - } - - public function testCreatesIntermediateDirectories(): void - { - $this->makeSourceFile(relative: 'stubs/nested/deep.txt'); - - $result = (new AppendMode())->apply( - $this->makeMapping('a/b/c/deep.txt', 'stubs/nested/deep.txt'), - "{$this->tempDir}/project", - new Hasher(), - null, - ); - - self::assertSame( - ApplyOutcome::Written, - $result->outcome, - 'AppendMode must create intermediate directories when they do not exist.', - ); - self::assertFileExists( - "{$this->tempDir}/project/a/b/c/deep.txt", - 'AppendMode must create the file in the expected location.', - ); - } - - public function testEmitsAppendedLinesUsingCREolWhenDestinationUsesCR(): void - { - $projectDir = "{$this->tempDir}/project"; - - mkdir($projectDir, 0o777, recursive: true); - - // Legacy Mac-style CR-only destination. - file_put_contents($projectDir . '/output.txt', "alpha\r"); - - $this->makeSourceFile("alpha\nbeta\n"); - - (new AppendMode())->apply( - $this->makeMapping(), - $projectDir, - new Hasher(), - null, - ); - - self::assertSame( - "alpha\rbeta\r", - file_get_contents($projectDir . '/output.txt'), - 'AppendMode must emit appended lines using CR when the destination uses CR-only EOL.', - ); - } - - public function testEmitsAppendedLinesUsingCRLFEolWhenDestinationUsesCRLF(): void - { - $projectDir = "{$this->tempDir}/project"; - - mkdir($projectDir, 0o777, recursive: true); - - // Windows-style CRLF destination. - file_put_contents($projectDir . '/output.txt', "alpha\r\n"); - - $this->makeSourceFile("alpha\nbeta\n"); - - (new AppendMode())->apply( - $this->makeMapping(), - $projectDir, - new Hasher(), - null, - ); - - self::assertSame( - "alpha\r\nbeta\r\n", - file_get_contents($projectDir . '/output.txt'), - 'AppendMode must emit appended lines using CRLF when the destination uses CRLF EOL.', - ); - } - - public function testHandlesEmptyStub(): void - { - $projectDir = "{$this->tempDir}/project"; - - mkdir($projectDir, 0o777, recursive: true); - file_put_contents($projectDir . '/output.txt', "alpha\n"); - - // Empty stub yields zero provider lines; the destination must remain untouched. - $this->makeSourceFile(''); - - $result = (new AppendMode())->apply( - $this->makeMapping(), - $projectDir, - new Hasher(), - null, - ); - - self::assertSame( - ApplyOutcome::Skipped, - $result->outcome, - "AppendMode must return 'ApplyOutcome::Skipped' when the stub is empty.", - ); - self::assertSame( - "alpha\n", - file_get_contents($projectDir . '/output.txt'), - 'AppendMode must leave the destination untouched when the stub is empty.', - ); - } - - public function testInsertsConsecutiveMissingProviderLinesBeforeSharedAnchor(): void - { - $projectDir = "{$this->tempDir}/project"; - - mkdir($projectDir, 0o777, recursive: true); - file_put_contents($projectDir . '/output.txt', "head\ntail\n"); - - // Two consecutive missing provider lines must both be flushed before the shared anchor, in stub order. - $this->makeSourceFile("head\nmid1\nmid2\ntail\n"); - - (new AppendMode())->apply( - $this->makeMapping(), - $projectDir, - new Hasher(), - null, - ); - - self::assertSame( - "head\nmid1\nmid2\ntail\n", - file_get_contents($projectDir . '/output.txt'), - 'Every buffered provider line must be flushed, in order.', - ); - } - - public function testInsertsContextuallyInCrOnlyDestination(): void - { - $projectDir = "{$this->tempDir}/project"; - - mkdir($projectDir, 0o777, recursive: true); - - // Legacy Mac CR-only destination with a mid-file insertion: every existing CR terminator must survive, - // including the final one, which no end-of-file separator would repair. - file_put_contents($projectDir . '/output.txt', "alpha\rbeta\r"); - - $this->makeSourceFile("alpha\ngamma\nbeta\n"); - - (new AppendMode())->apply( - $this->makeMapping(), - $projectDir, - new Hasher(), - null, - ); - - self::assertSame( - "alpha\rgamma\rbeta\r", - file_get_contents($projectDir . '/output.txt'), - 'All CR terminators must survive a mid-file insertion.', - ); - } - - public function testInsertsMissingProviderLineAtContextualPosition(): void - { - $projectDir = "{$this->tempDir}/project"; - - mkdir($projectDir, 0o777, recursive: true); - file_put_contents($projectDir . '/output.txt', "alpha\nbeta\n"); - - // Provider declares an explicit empty line between 'alpha' and 'beta'. The LCS alignment must insert it - // between the shared anchors instead of dumping it at the end of the file. - $this->makeSourceFile("alpha\n\nbeta\n"); - - (new AppendMode())->apply( - $this->makeMapping(), - $projectDir, - new Hasher(), - null, - ); - - self::assertSame( - "alpha\n\nbeta\n", - file_get_contents($projectDir . '/output.txt'), - 'AppendMode must insert the missing empty line between its shared anchors.', - ); - } - - public function testInsertsMissingProviderLinesBeforeSharedAnchor(): void - { - $projectDir = "{$this->tempDir}/project"; - - mkdir($projectDir, 0o777, recursive: true); - - // Consumer replaced the middle section; the missing provider line must land after the consumer block and - // before the next shared anchor, never at the end of the file. - file_put_contents($projectDir . '/output.txt', "head\ncustom\ntail\n"); - - $this->makeSourceFile("head\nmiddle\ntail\n"); - - (new AppendMode())->apply( - $this->makeMapping(), - $projectDir, - new Hasher(), - null, - ); - - self::assertSame( - "head\ncustom\nmiddle\ntail\n", - file_get_contents($projectDir . '/output.txt'), - 'AppendMode must keep consumer lines first and flush provider lines before the shared anchor.', - ); - } - - public function testInsertsOnlyMissingOccurrenceWhenDuplicateLinesAreReordered(): void - { - $projectDir = "{$this->tempDir}/project"; - - mkdir($projectDir, 0o777, recursive: true); - - // Consumer already holds one 'dup' (at the end); the stub wants two. Exactly one insertion is allowed even - // though LCS reports both leading stub occurrences as provider-only. - file_put_contents($projectDir . '/output.txt', "alpha\nbeta\ndup\n"); - - $this->makeSourceFile("dup\ndup\nalpha\nbeta\n"); - - (new AppendMode())->apply( - $this->makeMapping(), - $projectDir, - new Hasher(), - null, - ); - - self::assertSame( - "dup\nalpha\nbeta\ndup\n", - file_get_contents($projectDir . '/output.txt'), - 'Exactly one missing occurrence must be inserted; the existing copy must not be duplicated.', - ); - } - - public function testInsertsSeparatorWhenDestinationDoesNotEndWithNewline(): void - { - $projectDir = "{$this->tempDir}/project"; - - mkdir($projectDir, 0o777, recursive: true); - file_put_contents($projectDir . '/output.txt', 'existing'); - - $this->makeSourceFile('appended'); - - (new AppendMode())->apply( - $this->makeMapping(), - $projectDir, - new Hasher(), - null, - ); - - self::assertSame( - "existing\nappended\n", - file_get_contents($projectDir . '/output.txt'), - 'AppendMode must insert a newline separator when the destination does not end with one.', - ); - } - - public function testIsIdempotentAfterContextualInsertion(): void - { - $projectDir = "{$this->tempDir}/project"; - - mkdir($projectDir, 0o777, recursive: true); - file_put_contents($projectDir . '/output.txt', "head\ncustom\ntail\n"); - - $this->makeSourceFile("head\nmiddle\ntail\n"); - - (new AppendMode())->apply( - $this->makeMapping(), - $projectDir, - new Hasher(), - null, - ); - - $result = (new AppendMode())->apply( - $this->makeMapping(), - $projectDir, - new Hasher(), - null, - ); - - self::assertSame( - ApplyOutcome::Skipped, - $result->outcome, - "Second apply must return 'ApplyOutcome::Skipped'.", - ); - self::assertSame( - "head\ncustom\nmiddle\ntail\n", - file_get_contents($projectDir . '/output.txt'), - 'Content must stay stable across repeated applies.', - ); - } - - public function testIsIdempotentWhenConsumerHasNoTrailingNewlineAndStubDoes(): void + public function mergesMissingLinesIntoExistingDestination(): void { - $projectDir = "{$this->tempDir}/project"; - - mkdir($projectDir, 0o777, recursive: true); + (new InspectionProject($this->tempDir)) + ->stub('p/a', 'output.txt', "alpha\nbeta\ngamma\n") + ->file('output.txt', "alpha\nbeta\n"); - // Destination has no trailing newline; stub ends with one. The trailing-EOL stripping must treat both as - // equivalent so no phantom empty line gets appended. - file_put_contents($projectDir . '/output.txt', 'alpha'); + $result = (new AppendMode()) + ->apply($this->mapping('output.txt'), $this->tempDir, 'sha256:some-recorded-hash'); - $this->makeSourceFile("alpha\n"); - - $result = (new AppendMode())->apply( - $this->makeMapping(), - $projectDir, - new Hasher(), - null, - ); + $path = "{$this->tempDir}/output.txt"; - self::assertSame( - ApplyOutcome::Skipped, - $result->outcome, - "AppendMode must treat 'alpha' and 'alpha\\n' as equivalent for diffing purposes.", - ); - self::assertSame( - 'alpha', - file_get_contents($projectDir . '/output.txt'), - 'AppendMode must not modify a destination that differs from the stub only by the final EOL.', + Assert::same( + [$result->outcome, file_get_contents($path), $result->newHash, $result->warning], + [ApplyOutcome::Written, "alpha\nbeta\n\ngamma\n", Hasher::hash($path), null], + "Merged destination must be 'Written' with the missing line after a blank separator.", ); } - public function testIsIdempotentWhenStubEndsWithBlankLine(): void + public function skipsDestinationHoldingEveryProviderLine(): void { - $projectDir = "{$this->tempDir}/project"; + (new InspectionProject($this->tempDir)) + ->stub('p/a', 'output.txt', "alpha\nbeta\n") + ->file('output.txt', "beta\nalpha\n"); - mkdir($projectDir, 0o777, recursive: true); + $result = (new AppendMode()) + ->apply($this->mapping('output.txt'), $this->tempDir, null); - // Stub ends with an intentional trailing blank line. - $this->makeSourceFile("alpha\n\n"); + $path = "{$this->tempDir}/output.txt"; - // Two passes: the first must write the trailing blank; the second must detect it as already present. - (new AppendMode())->apply( - $this->makeMapping(), - $projectDir, - new Hasher(), - null, - ); - - $afterFirst = file_get_contents($projectDir . '/output.txt'); - - $result = (new AppendMode())->apply( - $this->makeMapping(), - $projectDir, - new Hasher(), - null, - ); - - self::assertSame( - ApplyOutcome::Skipped, - $result->outcome, - 'AppendMode must remain idempotent when the stub ends with a blank line.', - ); - self::assertSame( - $afterFirst, - file_get_contents($projectDir . '/output.txt'), - 'AppendMode must not re-append the trailing blank line on subsequent runs.', + Assert::same( + [$result->outcome, file_get_contents($path), $result->newHash, $result->warning], + [ApplyOutcome::Skipped, "beta\nalpha\n", Hasher::hash($path), null], + "Complete destination must be 'Skipped', byte-identical, with its current hash.", ); } - public function testNormalizesLineEndingsBeforeDiffing(): void + public function usesManifestMergeStrategyOverBasenameDefault(): void { - $projectDir = "{$this->tempDir}/project"; - - mkdir($projectDir, 0o777, recursive: true); - - // Destination uses CRLF (typical for files checked out on Windows or repos with mixed EOL). - file_put_contents($projectDir . '/output.txt', "alpha\r\nbeta\r\n"); - - // Provider ships LF. - $this->makeSourceFile("alpha\nbeta\n"); + (new InspectionProject($this->tempDir)) + ->stub('p/a', '.gitignore', "# b\nx\n") + ->file('.gitignore', "# a\nx\n"); $result = (new AppendMode())->apply( - $this->makeMapping(), - $projectDir, - new Hasher(), + $this->mapping('.gitignore', MergeStrategyKind::Text), + $this->tempDir, null, ); - self::assertSame( - ApplyOutcome::Skipped, - $result->outcome, - 'AppendMode must normalise line endings so CRLF destinations match LF stubs.', - ); - self::assertSame( - "alpha\r\nbeta\r\n", - file_get_contents($projectDir . '/output.txt'), - 'AppendMode must leave the destination untouched when EOL-normalised content matches.', + Assert::same( + [$result->outcome, file_get_contents("{$this->tempDir}/.gitignore")], + [ApplyOutcome::Written, "# a\nx\n\n# b\n"], + "Strategy 'text' must replace the 'list' default and treat the comment as content.", ); } - public function testPreservesConsumerAdditionsOnRepeatedApplies(): void - { - $projectDir = "{$this->tempDir}/project"; - - mkdir($projectDir, 0o777, recursive: true); - file_put_contents($projectDir . '/output.txt', "alpha\nproject-specific-line\n"); - - $this->makeSourceFile("alpha\nbeta\n"); - - (new AppendMode())->apply( - $this->makeMapping(), - $projectDir, - new Hasher(), - null, - ); - - // Apply again must remain idempotent. - (new AppendMode())->apply( - $this->makeMapping(), - $projectDir, - new Hasher(), - null, - ); - - self::assertSame( - "alpha\nproject-specific-line\nbeta\n", - file_get_contents($projectDir . '/output.txt'), - 'AppendMode must remain idempotent and never duplicate provider lines or remove consumer additions.', - ); - } - - public function testPreservesCrlfEolForContextualInsertion(): void - { - $projectDir = "{$this->tempDir}/project"; - - mkdir($projectDir, 0o777, recursive: true); - - // Windows-style CRLF destination; the mid-file insertion must be emitted in the same EOL style. - file_put_contents($projectDir . '/output.txt', "alpha\r\nbeta\r\n"); - - $this->makeSourceFile("alpha\ngamma\nbeta\n"); - - (new AppendMode())->apply( - $this->makeMapping(), - $projectDir, - new Hasher(), - null, - ); - - self::assertSame( - "alpha\r\ngamma\r\nbeta\r\n", - file_get_contents($projectDir . '/output.txt'), - 'Mid-file insertion must use the destination CRLF EOL style.', - ); - } - - public function testPreservesMissingTrailingNewlineWhenInsertionIsNotAtEnd(): void - { - $projectDir = "{$this->tempDir}/project"; - - mkdir($projectDir, 0o777, recursive: true); - - // Destination intentionally lacks a trailing newline and the insertion lands mid-file, so the consumer's - // trailing-newline choice must survive the rewrite. - file_put_contents($projectDir . '/output.txt', "alpha\nomega"); - - $this->makeSourceFile("gamma\nalpha\n"); - - (new AppendMode())->apply( - $this->makeMapping(), - $projectDir, - new Hasher(), - null, - ); - - self::assertSame( - "gamma\nalpha\nomega", - file_get_contents($projectDir . '/output.txt'), - 'Consumer trailing-newline choice must survive a mid-file insertion.', - ); - } - - public function testPreservesPerLineEolsForMixedEolDestination(): void - { - $projectDir = "{$this->tempDir}/project"; - - mkdir($projectDir, 0o777, recursive: true); - - // Mixed endings: 'alpha' is LF-terminated, 'beta' is CRLF-terminated. Existing terminators must survive the - // rewrite byte-for-byte; only the inserted line adopts the dominant (CRLF) style. - file_put_contents($projectDir . '/output.txt', "alpha\nbeta\r\n"); - - $this->makeSourceFile("alpha\ngamma\nbeta\n"); - - (new AppendMode())->apply( - $this->makeMapping(), - $projectDir, - new Hasher(), - null, - ); - - self::assertSame( - "alpha\ngamma\r\nbeta\r\n", - file_get_contents($projectDir . '/output.txt'), - 'Existing LF and CRLF terminators must survive; the inserted line must use the dominant EOL.', - ); - - $result = (new AppendMode())->apply( - $this->makeMapping(), - $projectDir, - new Hasher(), - null, - ); - - self::assertSame( - ApplyOutcome::Skipped, - $result->outcome, - 'Merged mixed-EOL file must be stable on the next apply.', - ); - } - - public function testResultHashMatchesActualFileHash(): void - { - $this->makeSourceFile('content'); - - $hasher = new Hasher(); - $result = (new AppendMode())->apply( - $this->makeMapping(), - "{$this->tempDir}/project", - $hasher, - null, - ); - - self::assertSame( - $hasher->hash("{$this->tempDir}/project/output.txt"), - $result->newHash, - 'AppendMode must return a new hash that matches the actual content of the written file.', - ); - } - - public function testReturnsSkippedWhenAllProviderLinesAlreadyPresent(): void - { - $projectDir = "{$this->tempDir}/project"; - - mkdir($projectDir, 0o777, recursive: true); - file_put_contents($projectDir . '/output.txt', "alpha\nbeta\ngamma\n"); - - $this->makeSourceFile("alpha\nbeta\n"); - - $result = (new AppendMode())->apply( - $this->makeMapping(), - $projectDir, - new Hasher(), - null, - ); - - self::assertSame( - ApplyOutcome::Skipped, - $result->outcome, - "AppendMode must return 'ApplyOutcome::Skipped' when every provider line is already present.", - ); - self::assertSame( - "alpha\nbeta\ngamma\n", - file_get_contents($projectDir . '/output.txt'), - 'AppendMode must leave the destination untouched when every provider line is already present.', - ); - } - - public function testReturnsSkippedWhenProviderLinesArePresentInDifferentOrder(): void - { - $projectDir = "{$this->tempDir}/project"; - - mkdir($projectDir, 0o777, recursive: true); - - // Consumer reordered the stub lines; every line is present, so nothing is missing and nothing is duplicated. - file_put_contents($projectDir . '/output.txt', "beta\nalpha\n"); - - $this->makeSourceFile("alpha\nbeta\n"); - - $result = (new AppendMode())->apply( - $this->makeMapping(), - $projectDir, - new Hasher(), - null, - ); - - self::assertSame( - ApplyOutcome::Skipped, - $result->outcome, - 'Reordered-but-complete destination must be skipped.', - ); - self::assertSame( - "beta\nalpha\n", - file_get_contents($projectDir . '/output.txt'), - 'Reordered destination must stay byte-identical.', - ); - } - - public function testReturnsWrittenWhenAtLeastOneLineIsAppended(): void - { - $projectDir = "{$this->tempDir}/project"; - - mkdir($projectDir, 0o777, recursive: true); - file_put_contents($projectDir . '/output.txt', "alpha\n"); - - $this->makeSourceFile("alpha\nbeta\n"); - - $result = (new AppendMode())->apply( - $this->makeMapping(), - $projectDir, - new Hasher(), - 'sha256:some-recorded-hash', - ); - - self::assertSame( - ApplyOutcome::Written, - $result->outcome, - "AppendMode must return 'ApplyOutcome::Written' when at least one missing line is appended.", - ); - } - - public function testRewritesDestinationWithMergedContentWhenLinesAreMissing(): void - { - $projectDir = "{$this->tempDir}/project"; - - mkdir($projectDir, 0o777, recursive: true); - file_put_contents($projectDir . '/output.txt', "alpha\n"); - - $this->makeSourceFile("alpha\nbeta\n"); - - $capturedFlag = null; - - MockerState::addCondition( - 'PHPForge\\Scaffold\\Scaffold\\Modes', - 'file_put_contents', - [ - $projectDir . DIRECTORY_SEPARATOR . 'output.txt', - "alpha\nbeta\n", - 0, - null, - ], - static function (string $file, string $data, int $flag) use (&$capturedFlag): int { - $capturedFlag = $flag; - - return (int) \file_put_contents($file, $data, $flag); - }, - ); - - (new AppendMode())->apply( - $this->makeMapping(), - $projectDir, - new Hasher(), - null, - ); - - self::assertSame( - 0, - $capturedFlag, - "Full merged content must be written with no flags, never 'FILE_APPEND'.", - ); - } - - public function testThrowsWhenAppendWriteFails(): void - { - $projectDir = "{$this->tempDir}/project"; - - mkdir($projectDir, 0o777, recursive: true); - file_put_contents($projectDir . '/output.txt', "existing\n"); - - // Source has a line not present in the destination, so the merge-write path is reached. - $this->makeSourceFile("missing\n"); - - MockerState::addCondition( - 'PHPForge\\Scaffold\\Scaffold\\Modes', - 'file_put_contents', - [], - false, - default: true, - ); - - $this->expectException(RuntimeException::class); - $this->expectExceptionMessage('Could not write to'); - - (new AppendMode())->apply( - $this->makeMapping(), - $projectDir, - new Hasher(), - null, - ); - } - - public function testThrowsWhenDestinationReadFails(): void - { - $projectDir = "{$this->tempDir}/project"; - - mkdir($projectDir, 0o777, recursive: true); - file_put_contents($projectDir . '/output.txt', 'existing'); - - $this->makeSourceFile('extra'); - - // Mock the destination read by exact path to fail; the source read (different path) is unaffected. - MockerState::addCondition( - 'PHPForge\\Scaffold\\Scaffold\\Modes', - 'file_get_contents', - [$projectDir . DIRECTORY_SEPARATOR . 'output.txt', false, null, 0, null], - false, - ); - - $this->expectException(RuntimeException::class); - $this->expectExceptionMessage('Could not read destination file'); - - (new AppendMode())->apply( - $this->makeMapping(), - $projectDir, - new Hasher(), - null, - ); - } - - public function testThrowsWhenSourceReadFails(): void - { - $this->makeSourceFile('x'); - - // 'default: true' fails every 'file_get_contents' in the Modes namespace, independent of how paths are assembled. - MockerState::addCondition( - 'PHPForge\\Scaffold\\Scaffold\\Modes', - 'file_get_contents', - [], - false, - default: true, - ); - - $this->expectException(RuntimeException::class); - $this->expectExceptionMessage('Could not read source file'); - - (new AppendMode())->apply( - $this->makeMapping(), - "{$this->tempDir}/project", - new Hasher(), - null, - ); - } - - public function testThrowsWhenWriteFails(): void - { - $this->makeSourceFile('data'); - - MockerState::addCondition( - 'PHPForge\\Scaffold\\Scaffold\\Modes', - 'file_put_contents', - [], - false, - default: true, - ); - - $this->expectException(RuntimeException::class); - $this->expectExceptionMessage('Could not write to'); - - (new AppendMode())->apply( - $this->makeMapping(), - "{$this->tempDir}/project", - new Hasher(), - null, - ); - } - - public function testUsesZeroFlagWhenDestinationDoesNotExist(): void - { - $projectDir = "{$this->tempDir}/project"; - - $this->makeSourceFile('hello'); - - $capturedFlag = null; - - MockerState::addCondition( - 'PHPForge\\Scaffold\\Scaffold\\Modes', - 'file_put_contents', - [ - $projectDir . DIRECTORY_SEPARATOR . 'output.txt', - 'hello', - 0, - null, - ], - static function (string $file, string $data, int $flag) use (&$capturedFlag): int { - $capturedFlag = $flag; - - return (int) \file_put_contents($file, $data, $flag); - }, - ); - - (new AppendMode())->apply( - $this->makeMapping(), - $projectDir, - new Hasher(), - null, - ); - - self::assertSame( - 0, - $capturedFlag, - "AppendMode must pass exactly '0' (no flags) when the destination does not exist yet.", - ); - } - - public function testWritesFileWhenDestinationDoesNotExist(): void - { - $this->makeSourceFile('hello'); - - $result = (new AppendMode())->apply( - $this->makeMapping(), - "{$this->tempDir}/project", - new Hasher(), - null, - ); - - self::assertSame( - ApplyOutcome::Written, - $result->outcome, - "AppendMode must write the file when the destination does not exist, resulting in 'ApplyOutcome::Written'.", - ); - self::assertSame( - 'hello', - file_get_contents("{$this->tempDir}/project/output.txt"), - 'AppendMode must write the correct content to the new file when it does not exist.', - ); - self::assertNull( - $result->warning, - 'AppendMode must not produce any warnings when writing a new file.', - ); - } - - public function testWritesFullStubWhenDestinationIsEmptyFile(): void - { - $projectDir = "{$this->tempDir}/project"; - - mkdir($projectDir, 0o777, recursive: true); - - // Destination exists but is empty (zero bytes): every provider line is missing and lands at the top. - file_put_contents($projectDir . '/output.txt', ''); - - $this->makeSourceFile("alpha\nbeta\n"); - - $result = (new AppendMode())->apply( - $this->makeMapping(), - $projectDir, - new Hasher(), - null, - ); - - self::assertSame( - ApplyOutcome::Written, - $result->outcome, - "Empty destination must yield 'ApplyOutcome::Written'.", - ); - self::assertSame( - "alpha\nbeta\n", - file_get_contents($projectDir . '/output.txt'), - 'Content must equal the full stub with no leading separator.', - ); - } - - protected function setUp(): void - { - $this->setUpTempDirectory(); - } - - protected function tearDown(): void - { - $this->tearDownTempDirectory(); - } - /** - * Helper method to create a FileMapping with default values for testing. + * Returns the append mapping of `$destination` to the stub of the same name in the `p/a` provider. * - * @param string $destination Destination path for the file mapping, defaulting to 'output.txt'. - * @param string $source Source path for the file mapping, defaulting to 'stubs/source.txt'. + * @param string $destination Destination path relative to the project root. + * @param MergeStrategyKind|null $mergeStrategy Manifest merge strategy, or `null` for the basename default. * - * @return FileMapping A FileMapping instance with the specified or default values. + * @return FileMapping Mapping of the destination. */ - private function makeMapping(string $destination = 'output.txt', string $source = 'stubs/source.txt'): FileMapping + private function mapping(string $destination, MergeStrategyKind|null $mergeStrategy = null): FileMapping { return new FileMapping( - destination: $destination, - source: $source, - mode: FileMode::Append, - providerName: 'test/provider', - providerPath: "{$this->tempDir}/provider", + $destination, + "stubs/{$destination}", + FileMode::Append, + 'p/a', + "{$this->tempDir}/vendor/p/a", + $mergeStrategy, ); } - - /** - * Creates a source file with the specified content and relative path within the provider directory. - * - * @param string $content Content to write to the source file. - * @param string $relative Relative path to the source file within the provider directory, defaulting to - * 'stubs/source.txt'. - */ - private function makeSourceFile(string $content = 'appended content', string $relative = 'stubs/source.txt'): void - { - $path = $this->tempDir . '/provider/' . $relative; - - $this->ensureTestDirectory(dirname($path)); - - file_put_contents($path, $content); - } } diff --git a/tests/Scaffold/Modes/ModeContractTest.php b/tests/Scaffold/Modes/ModeContractTest.php new file mode 100644 index 0000000..4c07717 --- /dev/null +++ b/tests/Scaffold/Modes/ModeContractTest.php @@ -0,0 +1,189 @@ +tempDir)) + ->stub('p/a', 'output.txt', '#!/bin/sh'); + + chmod("{$this->tempDir}/vendor/p/a/stubs/output.txt", 0o755); + + $umask = umask(0o022); + + try { + $result = $mode->apply($this->mapping($fileMode), $this->tempDir, null); + } finally { + umask($umask); + } + + Assert::same( + [fileperms("{$this->tempDir}/output.txt") & 0o777, $result->warning], + [0o755, null], + "Destination must carry the source mode '0755' without a warning.", + ); + } + + #[DataProvider(ModeProvider::class . '::unreadableDestinations')] + public function throwRuntimeExceptionWhenDestinationIsADirectory( + ModeInterface $mode, + FileMode $fileMode, + string $message, + ): void { + (new InspectionProject($this->tempDir)) + ->stub('p/a', 'output.txt', 'stub'); + + mkdir("{$this->tempDir}/output.txt"); + + Expect::exception(RuntimeException::class) + ->withMessageMatchingRegex( + '/^' . preg_quote($this->paths($message), '/') . '/', + ); + + $mode->apply($this->mapping($fileMode), $this->tempDir, null); + } + + #[DataProvider(ModeProvider::class . '::unwritableDestinations')] + public function throwRuntimeExceptionWhenDestinationIsNotWritable( + ModeInterface $mode, + FileMode $fileMode, + string $message, + ): void { + (new InspectionProject($this->tempDir)) + ->stub('p/a', 'output.txt', 'stub'); + + $this->createDanglingLink("{$this->tempDir}/output.txt"); + + Expect::exception(RuntimeException::class) + ->withMessage( + $this->paths($message), + ); + + $mode->apply($this->mapping($fileMode), $this->tempDir, null); + } + + #[DataProvider(ModeProvider::class . '::missingSources')] + public function throwRuntimeExceptionWhenSourceIsMissing( + ModeInterface $mode, + FileMode $fileMode, + string $message, + ): void { + Expect::exception(RuntimeException::class) + ->withMessage( + $this->paths($message), + ); + + $mode->apply($this->mapping($fileMode), $this->tempDir, null); + } + + #[DataProvider(ModeProvider::class . '::missingDestinations')] + public function writesMissingDestinationWithParentDirectories( + ModeInterface $mode, + FileMode $fileMode, + string|null $lockHash, + ): void { + (new InspectionProject($this->tempDir)) + ->stub('p/a', 'a/b/c/deep.txt', 'hello'); + + $result = $mode->apply($this->mapping($fileMode, 'a/b/c/deep.txt'), $this->tempDir, $lockHash); + + $path = "{$this->tempDir}/a/b/c/deep.txt"; + + Assert::same( + [$result->outcome, file_get_contents($path), $result->newHash, $result->warning], + [ApplyOutcome::Written, 'hello', Hasher::hash($path), null], + "Missing destination must be 'Written' with the stub content, its hash and no warning.", + ); + } + + /** + * Returns the mapping of `$destination` to the stub of the same name in the `p/a` provider. + * + * @param FileMode $fileMode Mode recorded in the mapping. + * @param string $destination Destination path relative to the project root. + * + * @return FileMapping Mapping of the destination. + */ + private function mapping(FileMode $fileMode, string $destination = 'output.txt'): FileMapping + { + return new FileMapping( + $destination, + "stubs/{$destination}", + $fileMode, + 'p/a', + "{$this->tempDir}/vendor/p/a", + ); + } + + /** + * Replaces the `{source}` and `{destination}` placeholders with the absolute paths of the default mapping. + * + * @param string $message Message with placeholders. + * + * @return string Message with absolute paths. + */ + private function paths(string $message): string + { + return str_replace( + ['{source}', '{destination}'], + [ + PathResolver::source("{$this->tempDir}/vendor/p/a", 'stubs/output.txt'), + PathResolver::destination($this->tempDir, 'output.txt'), + ], + $message, + ); + } +} diff --git a/tests/Scaffold/Modes/PrependModeTest.php b/tests/Scaffold/Modes/PrependModeTest.php index 8bc8c7f..0b243d4 100644 --- a/tests/Scaffold/Modes/PrependModeTest.php +++ b/tests/Scaffold/Modes/PrependModeTest.php @@ -7,283 +7,90 @@ use PHPForge\Scaffold\Manifest\{FileMapping, FileMode}; use PHPForge\Scaffold\Scaffold\Lock\Hasher; use PHPForge\Scaffold\Scaffold\Modes\{ApplyOutcome, PrependMode}; -use PHPForge\Scaffold\Tests\Support\TempDirectoryTrait; -use PHPUnit\Framework\TestCase; -use RuntimeException; -use Xepozz\InternalMocker\MockerState; +use PHPForge\Scaffold\Tests\Provider\ModeProvider; +use PHPForge\Scaffold\Tests\Support\{InspectionProject, TempDirectoryTrait}; +use Testo\Assert; +use Testo\Codecov\Covers; +use Testo\Data\DataProvider; +use Testo\Test; + +use function file_get_contents; /** - * Unit tests for {@see PrependMode} scaffold file application strategy. + * Unit tests for {@see PrependMode} placing the stub block before the destination content once. + * + * The shared mode behavior lives in {@see ModeContractTest}. + * + * {@see ModeProvider} for test case data providers. */ -final class PrependModeTest extends TestCase +#[Test] +#[Covers(PrependMode::class)] +final class PrependModeTest { use TempDirectoryTrait; - public function testCreatesIntermediateDirectories(): void - { - $this->makeSourceFile(relative: 'stubs/nested/deep.txt'); - - $result = (new PrependMode())->apply( - $this->makeMapping('a/b/c/deep.txt', 'stubs/nested/deep.txt'), - "{$this->tempDir}/project", - new Hasher(), - null, - ); - - self::assertSame( - ApplyOutcome::Written, - $result->outcome, - 'PrependMode must create intermediate directories when they do not exist.', - ); - self::assertFileExists( - "{$this->tempDir}/project/a/b/c/deep.txt", - 'PrependMode must create the file in the expected location.', - ); - } - - public function testOutcomeIsAlwaysWritten(): void - { - $this->makeSourceFile(); - - $result = (new PrependMode())->apply( - $this->makeMapping(), - "{$this->tempDir}/project", - new Hasher(), - 'sha256:ignored-hash', - ); - - self::assertSame( - ApplyOutcome::Written, - $result->outcome, - "PrependMode must always return 'ApplyOutcome::Written' regardless of the previous file state.", - ); - } - - public function testPrependContentComesBeforeExistingContent(): void - { - $projectDir = "{$this->tempDir}/project"; - - mkdir($projectDir, 0o777, recursive: true); - file_put_contents($projectDir . '/output.txt', 'EXISTING'); - - $this->makeSourceFile('PREPENDED'); - - (new PrependMode())->apply( - $this->makeMapping(), - $projectDir, - new Hasher(), - null, - ); - - $content = file_get_contents($projectDir . '/output.txt'); - - self::assertNotFalse( - $content, - 'Failed to read the content of the destination file after applying PrependMode.', - ); - self::assertStringStartsWith( - 'PREPENDED', - $content, - 'PrependMode must prepend the content correctly.', - ); - self::assertStringEndsWith( - 'EXISTING', - $content, - 'PrependMode must preserve the existing content.', - ); - } - - public function testPrependsToExistingFile(): void - { - $projectDir = "{$this->tempDir}/project"; - - mkdir($projectDir, 0o777, recursive: true); - file_put_contents($projectDir . '/output.txt', 'existing'); - - $this->makeSourceFile('prepended '); - - (new PrependMode())->apply( - $this->makeMapping(), - $projectDir, - new Hasher(), - null, - ); - - self::assertSame( - 'prepended existing', - file_get_contents($projectDir . '/output.txt'), - 'PrependMode must prepend the content correctly.', - ); - } - - public function testResultHashMatchesActualFileHash(): void - { - $this->makeSourceFile('stub'); - - $hasher = new Hasher(); - $result = (new PrependMode())->apply( - $this->makeMapping(), - "{$this->tempDir}/project", - $hasher, - null, - ); - - self::assertSame( - $hasher->hash("{$this->tempDir}/project/output.txt"), - $result->newHash, - 'PrependMode must return the correct hash for the new file content.', + #[DataProvider(ModeProvider::class . '::prependBlocks')] + public function prependReturnsContentOrNullWhenBlockIsPresent( + string $source, + string|null $existing, + string|null $expected, + ): void { + Assert::same( + PrependMode::prepend($source, $existing), + $expected, + 'Prepended content must match.', ); } - public function testThrowsWhenDestinationReadFails(): void + public function prependsStubToExistingDestination(): void { - $projectDir = "{$this->tempDir}/project"; - - mkdir($projectDir, 0o777, recursive: true); - file_put_contents("{$projectDir}/output.txt", 'existing'); - - $sourcePath = "{$this->tempDir}/provider/stubs/source.txt"; - - $this->ensureTestDirectory(dirname($sourcePath)); + (new InspectionProject($this->tempDir)) + ->stub('p/a', 'output.txt', "# header\n") + ->file('output.txt', 'EXISTING'); - file_put_contents($sourcePath, 'source'); + $result = (new PrependMode()) + ->apply($this->mapping(), $this->tempDir, null); - // 'PrependMode' reads source AND destination; strict arg-matching is required so only the destination branch fails. - $destBasename = 'output.txt'; + $path = "{$this->tempDir}/output.txt"; - MockerState::addCondition( - 'PHPForge\\Scaffold\\Scaffold\\Modes', - 'file_get_contents', - [ - /** - * match the destination argument by absolute path. `PrependMode` uses `PathResolver::destination`, - * which concatenates `rtrim($projectRoot, '/\\') . DIRECTORY_SEPARATOR . $mapping->destination` we - * reproduce that exactly here. - */ - rtrim($projectDir, '/\\') . DIRECTORY_SEPARATOR . $destBasename, - false, - null, - 0, - null, - ], - false, + Assert::same( + [$result->outcome, file_get_contents($path), $result->newHash, $result->warning], + [ApplyOutcome::Written, "# header\nEXISTING", Hasher::hash($path), null], + "Destination must be 'Written' with the block before the existing content.", ); - - $this->expectException(RuntimeException::class); - $this->expectExceptionMessage('Could not read destination file'); - - (new PrependMode())->apply($this->makeMapping(), $projectDir, new Hasher(), null); } - public function testThrowsWhenSourceReadFails(): void + public function skipsDestinationHoldingTheBlock(): void { - $this->makeSourceFile('x'); - - MockerState::addCondition( - 'PHPForge\\Scaffold\\Scaffold\\Modes', - 'file_get_contents', - [], - false, - default: true, - ); - - $this->expectException(RuntimeException::class); - $this->expectExceptionMessage('Could not read source file'); + (new InspectionProject($this->tempDir)) + ->stub('p/a', 'output.txt', "# header\n") + ->file('output.txt', "intro\n# header\nbody\n"); - (new PrependMode())->apply( - $this->makeMapping(), - "{$this->tempDir}/project", - new Hasher(), - null, - ); - } + $result = (new PrependMode()) + ->apply($this->mapping(), $this->tempDir, null); - public function testThrowsWhenWriteFails(): void - { - $this->makeSourceFile('source'); + $path = "{$this->tempDir}/output.txt"; - MockerState::addCondition( - 'PHPForge\\Scaffold\\Scaffold\\Modes', - 'file_put_contents', - [], - false, - default: true, + Assert::same( + [$result->outcome, file_get_contents($path), $result->newHash, $result->warning], + [ApplyOutcome::Skipped, "intro\n# header\nbody\n", Hasher::hash($path), null], + "Destination holding the block must be 'Skipped', untouched, with its current hash.", ); - - $this->expectException(RuntimeException::class); - $this->expectExceptionMessage('Could not write to'); - - (new PrependMode())->apply($this->makeMapping(), "{$this->tempDir}/project", new Hasher(), null); - } - - public function testWritesFileWhenDestinationDoesNotExist(): void - { - $this->makeSourceFile('hello'); - - $result = (new PrependMode())->apply( - $this->makeMapping(), - "{$this->tempDir}/project", - new Hasher(), - null, - ); - - self::assertSame( - ApplyOutcome::Written, - $result->outcome, - 'PrependMode must return the correct outcome when writing a new file.', - ); - self::assertSame( - 'hello', - file_get_contents("{$this->tempDir}/project/output.txt"), - 'PrependMode must write the correct content when the destination file does not exist.', - ); - self::assertNull( - $result->warning, - 'PrependMode must not return a warning when writing a new file.', - ); - } - - protected function setUp(): void - { - $this->setUpTempDirectory(); - } - - protected function tearDown(): void - { - $this->tearDownTempDirectory(); } /** - * Helper to create a file mapping for testing. + * Returns the prepend mapping of `output.txt` to the stub of the same name in the `p/a` provider. * - * @param string $destination Destination path relative to the project root. - * @param string $source Source path relative to the provider path. - * - * @return FileMapping Created file mapping instance. + * @return FileMapping Mapping of the destination. */ - private function makeMapping(string $destination = 'output.txt', string $source = 'stubs/source.txt'): FileMapping + private function mapping(): FileMapping { return new FileMapping( - destination: $destination, - source: $source, - mode: FileMode::Prepend, - providerName: 'test/provider', - providerPath: "{$this->tempDir}/provider", + 'output.txt', + 'stubs/output.txt', + FileMode::Prepend, + 'p/a', + "{$this->tempDir}/vendor/p/a", ); } - - /** - * Helper to create a source file with specified content for testing. - * - * @param string $content Content to write to the source file. - * @param string $relative Relative path from the provider path where the source file should be created. - */ - private function makeSourceFile(string $content = 'prepended content', string $relative = 'stubs/source.txt'): void - { - $path = "{$this->tempDir}/provider/{$relative}"; - - $this->ensureTestDirectory(dirname($path)); - - file_put_contents($path, $content); - } } diff --git a/tests/Scaffold/Modes/PreserveModeTest.php b/tests/Scaffold/Modes/PreserveModeTest.php index d180862..2259a46 100644 --- a/tests/Scaffold/Modes/PreserveModeTest.php +++ b/tests/Scaffold/Modes/PreserveModeTest.php @@ -7,251 +7,51 @@ use PHPForge\Scaffold\Manifest\{FileMapping, FileMode}; use PHPForge\Scaffold\Scaffold\Lock\Hasher; use PHPForge\Scaffold\Scaffold\Modes\{ApplyOutcome, PreserveMode}; -use PHPForge\Scaffold\Tests\Support\TempDirectoryTrait; -use PHPUnit\Framework\TestCase; -use RuntimeException; -use Xepozz\InternalMocker\MockerState; +use PHPForge\Scaffold\Tests\Support\{InspectionProject, TempDirectoryTrait}; +use Testo\Assert; +use Testo\Codecov\Covers; +use Testo\Data\DataSet; +use Testo\Test; + +use function file_get_contents; /** - * Unit tests for {@see PreserveMode} scaffold file application strategy. + * Unit tests for {@see PreserveMode} never overwriting an existing destination. + * + * The shared mode behavior lives in {@see ModeContractTest}. */ -final class PreserveModeTest extends TestCase +#[Test] +#[Covers(PreserveMode::class)] +final class PreserveModeTest { use TempDirectoryTrait; - public function testCreatesIntermediateDirectories(): void - { - $this->makeSourceFile(relative: 'stubs/nested/deep.txt'); - - $result = (new PreserveMode())->apply( - $this->makeMapping('a/b/c/deep.txt', 'stubs/nested/deep.txt'), - "{$this->tempDir}/project", - new Hasher(), - null, - ); - - self::assertSame( - ApplyOutcome::Written, - $result->outcome, - 'Expected file to be written when intermediate directories are created.', - ); - self::assertFileExists( - "{$this->tempDir}/project/a/b/c/deep.txt", - 'Expected file to exist after creating intermediate directories.', - ); - } - - public function testLockHashIsIgnored(): void - { - // 'PreserveMode' never overwrites the lock hash is irrelevant. - $projectDir = "{$this->tempDir}/project"; - - mkdir($projectDir, 0o777, recursive: true); - file_put_contents($projectDir . '/output.txt', 'user content'); - - $this->makeSourceFile('different stub'); - - $result = (new PreserveMode())->apply( - $this->makeMapping(), - $projectDir, - new Hasher(), - 'sha256:some-recorded-hash', - ); - - self::assertSame( - ApplyOutcome::Skipped, - $result->outcome, - 'PreserveMode must skip the file when it already exists.', - ); - self::assertSame( - 'user content', - file_get_contents($projectDir . '/output.txt'), - 'Existing file content must not be modified.', - ); - } - - public function testSkippedResultHashIsHashOfExistingFile(): void - { - $projectDir = "{$this->tempDir}/project"; - - mkdir($projectDir, 0o777, recursive: true); - file_put_contents($projectDir . '/output.txt', 'user content'); - - $this->makeSourceFile(); - - $hasher = new Hasher(); - - $expected = $hasher->hash($projectDir . '/output.txt'); - - $result = (new PreserveMode())->apply( - $this->makeMapping(), - $projectDir, - $hasher, - null, - ); - - self::assertSame( - $expected, - $result->newHash, - 'PreserveMode must return the correct hash for the existing file.', - ); - } - - public function testSkipsFileWhenDestinationAlreadyExists(): void - { - $projectDir = "{$this->tempDir}/project"; - - mkdir($projectDir, 0o777, recursive: true); - file_put_contents($projectDir . '/output.txt', 'user content'); - - $this->makeSourceFile('stub content'); - - $result = (new PreserveMode())->apply( - $this->makeMapping(), - $projectDir, - new Hasher(), - null, - ); - - self::assertSame( - ApplyOutcome::Skipped, - $result->outcome, - 'PreserveMode must skip the file when it already exists.', - ); - // Existing file must not be modified. - self::assertSame( - 'user content', - file_get_contents($projectDir . '/output.txt'), - 'Existing file content must not be modified.', - ); - self::assertNull( - $result->warning, - 'PreserveMode must not produce a warning when skipping a file.', - ); - } - - public function testSyncsSourceExecutableBitOntoDestinationAfterCopy(): void - { - if (DIRECTORY_SEPARATOR === '\\') { - self::markTestSkipped('POSIX umask-based permissions do not apply to NTFS (Windows always reports 0777).'); - } - - $source = "{$this->tempDir}/provider/stubs/source.txt"; - - $this->makeSourceFile('#!/bin/sh'); - - chmod($source, 0o755); - - $oldUmask = umask(0o022); - - try { - (new PreserveMode())->apply( - $this->makeMapping(), - "{$this->tempDir}/project", - new Hasher(), - null, - ); - - self::assertSame( - 0o755, - fileperms("{$this->tempDir}/project/output.txt") & 0o777, - "After 'PreserveMode::apply' copies the stub, 'syncPermissions' must propagate the source exec bit (0755).", - ); - } finally { - umask($oldUmask); - } - } - - public function testThrowsWhenCopyFails(): void + #[DataSet([null], 'without lock hash')] + #[DataSet(['sha256:some-recorded-hash'], 'with lock hash')] + public function skipsExistingDestination(string|null $lockHash): void { - $this->makeSourceFile('content'); - - MockerState::addCondition( - 'PHPForge\\Scaffold\\Scaffold\\Modes', - 'copy', - [], - false, - default: true, - ); - - $this->expectException(RuntimeException::class); - $this->expectExceptionMessage('Could not copy'); - - (new PreserveMode())->apply($this->makeMapping(), "{$this->tempDir}/project", new Hasher(), null); - } - - public function testWritesFileWhenDestinationDoesNotExist(): void - { - $this->makeSourceFile(); + (new InspectionProject($this->tempDir)) + ->stub('p/a', 'output.txt', 'stub content') + ->file('output.txt', 'user content'); $result = (new PreserveMode())->apply( - $this->makeMapping(), - "{$this->tempDir}/project", - new Hasher(), - null, - ); - - self::assertSame( - ApplyOutcome::Written, - $result->outcome, - 'PreserveMode must write the file when it does not already exist.', - ); - self::assertStringStartsWith( - 'sha256:', - $result->newHash, - "PreserveMode must return a hash starting with 'sha256'.", + new FileMapping( + 'output.txt', + 'stubs/output.txt', + FileMode::Preserve, + 'p/a', + "{$this->tempDir}/vendor/p/a", + ), + $this->tempDir, + $lockHash, ); - self::assertNull( - $result->warning, - 'PreserveMode must not produce a warning when writing a file.', - ); - self::assertFileExists( - "{$this->tempDir}/project/output.txt", - 'PreserveMode must create the output file.', - ); - } - protected function setUp(): void - { - $this->setUpTempDirectory(); - } + $path = "{$this->tempDir}/output.txt"; - protected function tearDown(): void - { - $this->tearDownTempDirectory(); - } - - /** - * Helper method to create a FileMapping for testing. - * - * @param string $destination Destination path relative to the project directory. - * @param string $source Source path relative to the provider directory. - * - * @return FileMapping Created file mapping instance. - */ - private function makeMapping(string $destination = 'output.txt', string $source = 'stubs/source.txt'): FileMapping - { - return new FileMapping( - destination: $destination, - source: $source, - mode: FileMode::Preserve, - providerName: 'test/provider', - providerPath: "{$this->tempDir}/provider", + Assert::same( + [$result->outcome, file_get_contents($path), $result->newHash, $result->warning], + [ApplyOutcome::Skipped, 'user content', Hasher::hash($path), null], + "Existing destination must be 'Skipped', untouched, with its current hash and no warning.", ); } - - /** - * Helper method to create a source file with specified content and relative path. - * - * @param string $content Content to write to the source file. - * @param string $relative Relative path within the provider directory for the source file. - */ - private function makeSourceFile(string $content = 'stub content', string $relative = 'stubs/source.txt'): void - { - $path = "{$this->tempDir}/provider/{$relative}"; - - $this->ensureTestDirectory(dirname($path)); - - file_put_contents($path, $content); - } } diff --git a/tests/Scaffold/Modes/ReplaceModeTest.php b/tests/Scaffold/Modes/ReplaceModeTest.php index 543901e..773f1d0 100644 --- a/tests/Scaffold/Modes/ReplaceModeTest.php +++ b/tests/Scaffold/Modes/ReplaceModeTest.php @@ -5,294 +5,59 @@ namespace PHPForge\Scaffold\Tests\Scaffold\Modes; use PHPForge\Scaffold\Manifest\{FileMapping, FileMode}; -use PHPForge\Scaffold\Scaffold\Lock\Hasher; use PHPForge\Scaffold\Scaffold\Modes\{ApplyOutcome, ReplaceMode}; -use PHPForge\Scaffold\Tests\Support\TempDirectoryTrait; -use PHPUnit\Framework\TestCase; -use RuntimeException; -use Xepozz\InternalMocker\MockerState; +use PHPForge\Scaffold\Tests\Provider\ModeProvider; +use PHPForge\Scaffold\Tests\Support\{InspectionProject, TempDirectoryTrait}; +use Testo\Assert; +use Testo\Codecov\Covers; +use Testo\Data\DataProvider; +use Testo\Test; + +use function file_get_contents; /** - * Unit tests for {@see ReplaceMode} scaffold file application strategy. + * Unit tests for {@see ReplaceMode} overwriting an existing destination unless the user modified it. + * + * The shared mode behavior lives in {@see ModeContractTest}. + * + * {@see ModeProvider} for test case data providers. */ -final class ReplaceModeTest extends TestCase +#[Test] +#[Covers(ReplaceMode::class)] +final class ReplaceModeTest { use TempDirectoryTrait; - public function testCreatesIntermediateDirectories(): void - { - $this->makeSourceFile(relative: 'stubs/nested/deep.txt'); - - $result = (new ReplaceMode())->apply( - $this->makeMapping('a/b/c/deep.txt', 'stubs/nested/deep.txt'), - "{$this->tempDir}/project", - new Hasher(), - null, - ); - - self::assertSame( - ApplyOutcome::Written, - $result->outcome, - 'Expected file to be written successfully, even if intermediate directories do not exist.', - ); - self::assertFileExists( - "{$this->tempDir}/project/a/b/c/deep.txt", - 'Expected file to exist after creating intermediate directories.', - ); - } - - public function testOverwritesFileWhenHashMatchesLockHash(): void - { - $projectDir = "{$this->tempDir}/project"; - - mkdir($projectDir, 0o777, recursive: true); - file_put_contents($projectDir . '/output.txt', 'original scaffold content'); - - $this->makeSourceFile('updated stub content'); - - $hasher = new Hasher(); - - $lockHash = $hasher->hash($projectDir . '/output.txt'); - - $result = (new ReplaceMode())->apply( - $this->makeMapping(), - $projectDir, - $hasher, - $lockHash, - ); - - self::assertSame( - ApplyOutcome::Written, - $result->outcome, - 'Expected file to be overwritten when hash matches lock hash.', - ); - self::assertSame( - 'updated stub content', - file_get_contents($projectDir . '/output.txt'), - 'Expected file content to be updated when hash matches lock hash.', - ); - } - - public function testResultHashMatchesActualFileHash(): void - { - $this->makeSourceFile('known content'); + #[DataProvider(ModeProvider::class . '::replaceDecisions')] + public function appliesExistingDestinationAgainstLockHash( + string|null $lockHash, + string $existing, + string $stub, + ApplyOutcome $outcome, + string $content, + string $newHash, + string|null $warning, + ): void { + (new InspectionProject($this->tempDir)) + ->stub('p/a', 'output.txt', $stub) + ->file('output.txt', $existing); - $hasher = new Hasher(); $result = (new ReplaceMode())->apply( - $this->makeMapping(), - "{$this->tempDir}/project", - $hasher, - null, - ); - - $actualHash = $hasher->hash("{$this->tempDir}/project/output.txt"); - - self::assertSame( - $actualHash, - $result->newHash, - 'Expected result hash to match the actual file hash.', - ); - } - - public function testSkipsFileWhenUserHasModifiedIt(): void - { - $projectDir = "{$this->tempDir}/project"; - - mkdir($projectDir, 0o777, recursive: true); - file_put_contents($projectDir . '/output.txt', 'original scaffold content'); - - $this->makeSourceFile('updated stub content'); - - $hasher = new Hasher(); - - // Lock hash recorded for original; user then modified the file to different content. - $lockHash = 'sha256:' . hash('sha256', 'the-original-hash-that-no-longer-matches'); - - $result = (new ReplaceMode())->apply( - $this->makeMapping(), - $projectDir, - $hasher, + new FileMapping( + 'output.txt', + 'stubs/output.txt', + FileMode::Replace, + 'p/a', + "{$this->tempDir}/vendor/p/a", + ), + $this->tempDir, $lockHash, ); - self::assertSame( - ApplyOutcome::Skipped, - $result->outcome, - 'Expected file to be skipped when user has modified it.', - ); - self::assertSame( - '', - $result->newHash, - 'Expected new hash to be empty when file is skipped.', - ); - self::assertNotNull( - $result->warning, - 'Expected warning to be set when file is skipped.', - ); - self::assertStringContainsString( - 'output.txt', - $result->warning, - 'Expected warning to mention the file name when file is skipped.', + Assert::same( + [$result->outcome, file_get_contents("{$this->tempDir}/output.txt"), $result->newHash, $result->warning], + [$outcome, $content, $newHash, $warning], + 'Outcome, content, new hash and warning must match the decision.', ); - // File must NOT be overwritten. - self::assertSame( - 'original scaffold content', - file_get_contents($projectDir . '/output.txt'), - 'Expected file content to remain unchanged when file is skipped.', - ); - } - - public function testSyncsSourceExecutableBitOntoDestinationAfterCopy(): void - { - if (DIRECTORY_SEPARATOR === '\\') { - self::markTestSkipped('POSIX umask-based permissions do not apply to NTFS (Windows always reports 0777).'); - } - - $source = "{$this->tempDir}/provider/stubs/source.txt"; - - $this->makeSourceFile('#!/bin/sh'); - - chmod($source, 0o755); - - $oldUmask = umask(0o022); - - try { - (new ReplaceMode())->apply( - $this->makeMapping(), - "{$this->tempDir}/project", - new Hasher(), - null, - ); - - self::assertSame( - 0o755, - fileperms("{$this->tempDir}/project/output.txt") & 0o777, - "After 'ReplaceMode::apply' copies the stub, 'syncPermissions' must propagate the source exec bit (0755).", - ); - } finally { - umask($oldUmask); - } - } - - public function testThrowsWhenCopyFails(): void - { - $this->makeSourceFile('content'); - - MockerState::addCondition( - 'PHPForge\\Scaffold\\Scaffold\\Modes', - 'copy', - [], - false, - default: true, - ); - - $this->expectException(RuntimeException::class); - $this->expectExceptionMessage('Could not copy'); - - (new ReplaceMode())->apply($this->makeMapping(), "{$this->tempDir}/project", new Hasher(), null); - } - - public function testWritesFileWhenDestinationDoesNotExist(): void - { - $this->makeSourceFile(); - - $result = (new ReplaceMode())->apply( - $this->makeMapping(), - $this->tempDir . '/project', - new Hasher(), - null, - ); - - self::assertSame( - ApplyOutcome::Written, - $result->outcome, - 'Expected file to be written when destination does not exist.', - ); - self::assertStringStartsWith( - 'sha256:', - $result->newHash, - "Expected new hash to start with 'sha256:'", - ); - self::assertNull( - $result->warning, - 'Expected no warning when file is written.', - ); - self::assertFileExists( - "{$this->tempDir}/project/output.txt", - 'Expected file to exist after being written.', - ); - } - - public function testWritesFileWhenNoLockHashExists(): void - { - $projectDir = "{$this->tempDir}/project"; - - mkdir($projectDir, 0o777, recursive: true); - file_put_contents($projectDir . '/output.txt', 'any existing content'); - - $this->makeSourceFile('fresh stub'); - - $result = (new ReplaceMode())->apply( - $this->makeMapping(), - $projectDir, - new Hasher(), - null, // No lock hash treat as untracked, overwrite unconditionally. - ); - - self::assertSame( - ApplyOutcome::Written, - $result->outcome, - 'Expected file to be written when no lock hash exists.', - ); - self::assertSame( - 'fresh stub', - file_get_contents($projectDir . '/output.txt'), - 'Expected file content to match the source when no lock hash exists.', - ); - } - - protected function setUp(): void - { - $this->setUpTempDirectory(); - } - - protected function tearDown(): void - { - $this->tearDownTempDirectory(); - } - - /** - * Helper to create a FileMapping for testing. - * - * @param string $destination Relative destination path within the project, defaulting to 'output.txt'. - * @param string $source Relative source path within the provider, defaulting to 'stubs/source.txt'. - * - * @return FileMapping Created FileMapping instance. - */ - private function makeMapping(string $destination = 'output.txt', string $source = 'stubs/source.txt'): FileMapping - { - return new FileMapping( - destination: $destination, - source: $source, - mode: FileMode::Replace, - providerName: 'test/provider', - providerPath: "{$this->tempDir}/provider", - ); - } - - /** - * Helper to create a source file for testing. - * - * @param string $content Content to write to the source file, defaulting to 'stub content'. - * @param string $relative Relative path of the source file within the provider directory, defaulting to - * 'stubs/source.txt'. - */ - private function makeSourceFile(string $content = 'stub content', string $relative = 'stubs/source.txt'): void - { - $path = "{$this->tempDir}/provider/{$relative}"; - - $this->ensureTestDirectory(dirname($path)); - - file_put_contents($path, $content); } } diff --git a/tests/Scaffold/PathResolverTest.php b/tests/Scaffold/PathResolverTest.php index 4034e92..a3058df 100644 --- a/tests/Scaffold/PathResolverTest.php +++ b/tests/Scaffold/PathResolverTest.php @@ -4,483 +4,283 @@ namespace PHPForge\Scaffold\Tests\Scaffold; +use PHPForge\Scaffold\Console\Message as ConsoleMessage; +use PHPForge\Scaffold\Exception\Message; use PHPForge\Scaffold\Scaffold\PathResolver; -use PHPForge\Scaffold\Tests\Support\TempDirectoryTrait; -use PHPUnit\Framework\Attributes\Group; -use PHPUnit\Framework\TestCase; +use PHPForge\Scaffold\Tests\Provider\PathResolverProvider; +use PHPForge\Scaffold\Tests\Support\{FileAssert, TempDirectoryTrait}; +use ReflectionMethod; use RuntimeException; -use Xepozz\InternalMocker\MockerState; +use Testo\Assert; +use Testo\Codecov\Covers; +use Testo\Core\Exception\SkipTest; +use Testo\Data\DataProvider; +use Testo\Expect; +use Testo\Test; + +use function chmod; +use function error_clear_last; +use function error_get_last; +use function file_put_contents; +use function fileperms; +use function function_exists; +use function is_array; +use function is_file; +use function is_string; +use function mkdir; +use function posix_geteuid; +use function preg_quote; +use function realpath; +use function str_replace; +use function umask; +use function uniqid; /** - * Unit tests for {@see PathResolver} path joining, directory creation, and provider-root resolution. + * Unit tests for {@see PathResolver} path joining, directory creation, permission copying and provider-root + * resolution. + * + * {@see PathResolverProvider} for test case data providers. */ -#[Group('scaffold')] -final class PathResolverTest extends TestCase +#[Test] +#[Covers(PathResolver::class)] +final class PathResolverTest { use TempDirectoryTrait; - public function testDestinationStripsLeadingSeparatorFromDestination(): void - { - self::assertSame( - '/tmp/foo' . DIRECTORY_SEPARATOR . 'bar', - PathResolver::destination('/tmp/foo', '/bar'), - 'Leading separator in destination must not produce a double separator.', - ); - } - - public function testDestinationStripsTrailingSeparatorFromProjectRoot(): void - { - self::assertSame( - '/tmp/foo' . DIRECTORY_SEPARATOR . 'bar', - PathResolver::destination('/tmp/foo/', 'bar'), - 'Trailing separator in project root must not produce a double separator.', - ); - } - - public function testEnsureDirectoryCreatesUsing0777Mode(): void + public function ensureDirectoryCreatesParentWithUmaskAppliedMode(): void { if (DIRECTORY_SEPARATOR === '\\') { - self::markTestSkipped('POSIX umask-based permissions do not apply to NTFS (Windows always reports 0777).'); + throw new SkipTest('POSIX umask-based permissions do not apply to NTFS.'); } - $oldUmask = umask(0o022); + $umask = umask(0o022); try { - $dir = $this->tempDir . '/fresh'; - - PathResolver::ensureDirectory($dir . '/file.txt'); - - self::assertDirectoryExists( - $dir, - 'Directory must be created if it does not exist.', - ); - self::assertSame( - 0o755, - fileperms($dir) & 0o777, - "Directory must be created with '0777' mode so umask '0022' yields '0755' effective permissions.", - ); + PathResolver::ensureDirectory("{$this->tempDir}/fresh/file.txt"); } finally { - umask($oldUmask); + umask($umask); } - } - - public function testEnsureDirectoryIsNoopWhenDirectoryAlreadyExists(): void - { - $dir = "{$this->tempDir}/existing"; - mkdir($dir, 0o777, recursive: true); - - PathResolver::ensureDirectory($dir . '/file.txt'); - - self::assertDirectoryExists( - $dir, - 'Directory must exist if it already exists.', + Assert::same( + fileperms("{$this->tempDir}/fresh") & 0o777, + 0o755, + "Directory created under umask '0022' must have mode '0755'.", ); } - public function testEnsureDirectoryIsNoopWhenRaceCreatesDirectoryAfterMkdirFails(): void + public function ensureDirectoryKeepsExistingParent(): void { - $dir = "{$this->tempDir}/race"; + mkdir("{$this->tempDir}/existing"); - $isDirCalls = 0; + PathResolver::ensureDirectory("{$this->tempDir}/existing/file.txt"); - MockerState::addCondition( - 'PHPForge\\Scaffold\\Scaffold', - 'is_dir', - [$dir], - static function () use (&$isDirCalls): bool { - $isDirCalls++; - - // First call (guard): directory does not exist yet, so attempt mkdir. - // Second call (recheck after mkdir failure): another process created the directory in between. - return $isDirCalls >= 2; - }, - ); - MockerState::addCondition( - 'PHPForge\\Scaffold\\Scaffold', - 'mkdir', - [$dir, 0o777, true, null], - false, + FileAssert::directoryExists( + "{$this->tempDir}/existing", + 'Existing parent directory must be kept.', ); - PathResolver::ensureDirectory($dir . '/file.txt'); - - self::assertGreaterThanOrEqual( - 2, - $isDirCalls, - "'is_dir' must be rechecked after 'mkdir' returns 'false' so a concurrent creation is not treated as failure.", - ); - } - - public function testEnsureDirectoryThrowsWhenMkdirFailsAndDirectoryStillAbsent(): void - { - $dir = "{$this->tempDir}/unwritable"; - - MockerState::addCondition( - 'PHPForge\\Scaffold\\Scaffold', - 'is_dir', - [$dir], - false, - ); - MockerState::addCondition( - 'PHPForge\\Scaffold\\Scaffold', - 'mkdir', - [$dir, 0o777, true, null], - false, - ); - - $this->expectException(RuntimeException::class); - $this->expectExceptionMessage('Could not create directory'); - - PathResolver::ensureDirectory($dir . '/file.txt'); } - public function testRealpathOrFallbackReturnsCanonicalPathWhenExists(): void - { - self::assertSame( - realpath($this->tempDir), - PathResolver::realpathOrFallback($this->tempDir), - "realpathOrFallback must return the canonical path when 'realpath' succeeds.", + /** + * @param string $path Absolute path to check. + * @param string $directory Absolute path of the containing directory. + * @param bool $caseInsensitive Whether to compare ignoring case. + * @param bool $expected Whether `$path` is expected inside `$directory`. + */ + #[DataProvider(PathResolverProvider::class . '::within')] + public function isWithinHonorsSeparatorsAndCaseInsensitiveFlag( + string $path, + string $directory, + bool $caseInsensitive, + bool $expected, + ): void { + Assert::same( + (new ReflectionMethod(PathResolver::class, 'isWithin'))->invoke(null, $path, $directory, $caseInsensitive), + $expected, + 'Containment check must treat both separators alike and honor the case flag.', ); } - public function testRealpathOrFallbackTrimsWhenResolutionFails(): void + /** + * @param 'destination'|'source' $method Join method. + */ + #[DataProvider(PathResolverProvider::class . '::joins')] + public function joinsPathsWithOneSeparator(string $method, string $base, string $relative, string $expected): void { - $unique = '/nonexistent/path/' . uniqid(); - - self::assertSame( - $unique, - PathResolver::realpathOrFallback($unique . '/'), - "realpathOrFallback must 'trim' trailing separators when 'realpath' fails.", + Assert::same( + $method === 'destination' + ? PathResolver::destination($base, $relative) + : PathResolver::source($base, $relative), + $expected, + 'Joined path must hold one separator between its parts.', ); } - public function testResolveProviderRootAcceptsLockPathEqualToVendorDir(): void + public function realpathOrFallbackCanonicalizesExistingPathsAndTrimsMissingOnes(): void { - $vendor = $this->tempDir; + $missing = '/nonexistent/path/' . uniqid(); - // Some edge deployments (e.g. a single-package vendor) can register the vendor dir itself as a provider. - $result = PathResolver::resolveProviderRoot($vendor, 'pkg/name', ['path' => $vendor]); - - self::assertNull( - $result['warning'], - "A lock path equal to the vendor 'dir' must be accepted without emitting a warning.", + Assert::same( + [PathResolver::realpathOrFallback($this->tempDir), PathResolver::realpathOrFallback("{$missing}/\\")], + [realpath($this->tempDir), $missing], + 'Existing path must be canonical; missing path must lose its trailing separators.', ); } - public function testResolveProviderRootDetectsUncLikePathAsAbsoluteViaBackslashPrefix(): void - { - $vendor = PathResolver::realpathOrFallback($this->tempDir); - - $result = PathResolver::resolveProviderRoot( - $vendor, - 'pkg/name', - ['path' => '\\\\server\\share'], - $vendor, - ); - - self::assertNotNull( - $result['warning'], - "A UNC-like recordedPath starting with '\\' must stay absolute and land outside vendor, emitting a warning.", - ); - } - - public function testResolveProviderRootDoesNotClassifyRelativePathContainingDriveLetterInMiddleAsAbsolute(): void - { - $vendor = PathResolver::realpathOrFallback($this->tempDir); - - $result = PathResolver::resolveProviderRoot( - $vendor, - 'pkg/name', - ['path' => 'foo/C:/bar'], - $vendor, - ); - - self::assertNull( - $result['warning'], - "A relative recordedPath with a drive-letter substring must stay relative; '^' anchor keeps it under projectRoot.", - ); - } - - public function testResolveProviderRootFallsBackToDefaultWhenLockPathEscapesVendor(): void - { - $vendor = $this->tempDir; - - mkdir($vendor . '/pkg/name', 0o777, recursive: true); - - $result = PathResolver::resolveProviderRoot( - $vendor, - 'pkg/name', - ['path' => '/etc'], - ); - - self::assertSame( - realpath($vendor) . DIRECTORY_SEPARATOR . 'pkg/name', - $result['root'], - 'When the lock-recorded path escapes vendor, resolveProviderRoot must fall back to the vendor-derived path.', - ); - self::assertNotNull( - $result['warning'], - 'A warning must be emitted when a lock-recorded provider path escapes vendor.', - ); - } - - public function testResolveProviderRootHonorsAbsoluteLockPathVerbatimWhenProjectRootIsNonEmpty(): void - { - $vendor = $this->tempDir . '/vendor'; - - mkdir($vendor . '/pkg/name', 0o777, recursive: true); - - $absoluteLockPath = realpath($vendor . '/pkg/name'); - - self::assertIsString($absoluteLockPath, 'Test setup failed to resolve the seeded provider root.'); - - $result = PathResolver::resolveProviderRoot( - $vendor, - 'pkg/name', - ['path' => $absoluteLockPath], - $this->tempDir . '/unrelated-project-root', - ); - - self::assertSame($absoluteLockPath, $result['root'], 'Absolute lock path inside vendor must be verbatim.'); - self::assertNull($result['warning'], 'Absolute path inside vendor must not emit a warning.'); - } - - public function testResolveProviderRootRejectsLockPathSharingSiblingPrefixWithVendorDir(): void - { - $vendor = "{$this->tempDir}/vendor"; - $sibling = "{$this->tempDir}/vendorsibling"; - - mkdir($vendor, 0o777, recursive: true); - mkdir($sibling, 0o777, recursive: true); + /** + * @param list $directories Directories to create, relative to the temporary directory. + */ + #[DataProvider(PathResolverProvider::class . '::providerRoots')] + public function resolveProviderRootHonorsOnlyLockPathsInsideVendor( + array $directories, + string $vendorDir, + mixed $lock, + string $projectRoot, + string $root, + string|null $warning, + ): void { + foreach ($directories as $directory) { + $this->ensureTestDirectory("{$this->tempDir}/{$directory}"); + } - $result = PathResolver::resolveProviderRoot($vendor, 'pkg/name', ['path' => $sibling]); + if (is_array($lock) && is_string($lock['path'] ?? null)) { + $lock['path'] = $this->expand($lock['path']); + } - self::assertNotNull( - $result['warning'], - 'A lock path outside vendor that only shares a string prefix must warn and fall back to the default root.', + Assert::same( + PathResolver::resolveProviderRoot( + $this->expand($vendorDir), + 'pkg/name', + $lock, + $this->expand($projectRoot), + ), + ['root' => $this->expand($root), 'warning' => $warning], + 'Resolved root and warning must match.', ); } - public function testResolveProviderRootResolvesRelativeLockPathAgainstProjectRoot(): void - { - $projectRoot = $this->tempDir; - $vendor = "{$projectRoot}/vendor"; - - mkdir($vendor . '/pkg/name', 0o777, recursive: true); - - $result = PathResolver::resolveProviderRoot( - $vendor, - 'pkg/name', - ['path' => 'vendor/pkg/name'], - $projectRoot, - ); + #[DataProvider(PathResolverProvider::class . '::permissions')] + public function syncPermissionsCopiesSourceBitsMaskedByUmask( + int $sourceMode, + int $destinationMode, + int $umask, + int $expected, + ): void { + if (DIRECTORY_SEPARATOR === '\\') { + throw new SkipTest('POSIX umask-based permissions do not apply to NTFS.'); + } - self::assertSame( - realpath($vendor . '/pkg/name'), - $result['root'], - 'A relative lock path must be expanded against the project root before the vendor-containment check.', + file_put_contents( + "{$this->tempDir}/source.sh", + "#!/bin/sh\n", ); - self::assertNull( - $result['warning'], - 'No warning must be emitted when the relative path resolves inside the vendor directory.', + file_put_contents( + "{$this->tempDir}/copy.sh", + "#!/bin/sh\n", ); - } - - public function testResolveProviderRootReturnsLockPathWhenInsideVendor(): void - { - $vendor = $this->tempDir; - - mkdir($vendor . '/pkg/name', 0o777, recursive: true); + chmod("{$this->tempDir}/source.sh", $sourceMode); + chmod("{$this->tempDir}/copy.sh", $destinationMode); - $insidePath = "{$vendor}/pkg/name"; + $previous = umask($umask); - $result = PathResolver::resolveProviderRoot($vendor, 'pkg/name', ['path' => $insidePath]); + try { + $warning = PathResolver::syncPermissions("{$this->tempDir}/source.sh", "{$this->tempDir}/copy.sh"); + } finally { + umask($previous); + } - self::assertSame( - realpath($insidePath), - $result['root'], - 'When the lock-recorded path is inside vendor, it must be honored.', - ); - self::assertNull( - $result['warning'], - 'No warning must be emitted when the lock-recorded provider path is valid and inside vendor.', + Assert::same( + [fileperms("{$this->tempDir}/copy.sh") & 0o777, $warning], + [$expected, null], + 'Destination bits must be the source bits masked by the umask, without a warning.', ); } - public function testResolveProviderRootTrimsTrailingSeparatorFromProjectRootBeforeJoiningRelativeLockPath(): void + public function syncPermissionsReturnsChmodWarningInsteadOfRaisingIt(): void { - $tempDir = PathResolver::realpathOrFallback($this->tempDir); - $projectRoot = PathResolver::destination($tempDir, 'proj'); - $vendor = PathResolver::destination($projectRoot, 'vendor'); - - mkdir($vendor, 0o777, recursive: true); - - // Relative path normalized through the same helper the production join uses, minus the leading separator. - $relativeInVendor = ltrim(PathResolver::source('', 'vendor/pkg/name-missing'), '/\\'); + if (!function_exists('posix_geteuid') || posix_geteuid() === 0 || !is_file('/proc/version')) { + throw new SkipTest( + 'Needs a non-root POSIX process and a file it does not own.', + ); + } - $result = PathResolver::resolveProviderRoot( - $vendor, - 'pkg/name', - ['path' => $relativeInVendor], - PathResolver::destination($projectRoot, ''), + file_put_contents( + "{$this->tempDir}/source.txt", + 'x', ); - - self::assertNull($result['warning'], 'Trailing separator in projectRoot must be rtrimmed before joining.'); - } - - public function testResolveProviderRootUsesDefaultWhenLockEntryIsMissingPath(): void - { - $result = PathResolver::resolveProviderRoot($this->tempDir, 'pkg/name', null); - - self::assertSame( - PathResolver::realpathOrFallback($this->tempDir) . DIRECTORY_SEPARATOR . 'pkg/name', - $result['root'], - 'When the lock record lacks a path, resolveProviderRoot must fall back to the canonicalized default root.', + error_clear_last(); + + Assert::same( + PathResolver::syncPermissions("{$this->tempDir}/source.txt", '/proc/version'), + Message::FILESYSTEM_FAILED->getMessage( + ConsoleMessage::SCAFFOLD_PERMISSIONS_COPY_FAILED->getMessage("{$this->tempDir}/source.txt", '/proc/version'), + 'chmod(): Operation not permitted', + ), + 'PHP warning text must be returned, not raised.', ); - self::assertNull( - $result['warning'], - 'No warning must be emitted when the lock record is missing or does not contain a path.', + Assert::null( + error_get_last(), + 'The warning must not reach the PHP error handler.', ); } - public function testSourceStripsLeadingSeparatorFromSource(): void + public function syncPermissionsReturnsWarningWhenSourceIsMissing(): void { - // Single segment avoids `str_replace('/', DIRECTORY_SEPARATOR, ...)` normalization differences on Windows. - self::assertSame( - '/tmp/provider' . DIRECTORY_SEPARATOR . 'file.txt', - PathResolver::source('/tmp/provider', '/file.txt'), - 'Leading separator in source must not produce a double separator.', + file_put_contents("{$this->tempDir}/copy.sh", "#!/bin/sh\n"); + + $before = fileperms("{$this->tempDir}/copy.sh"); + + Assert::same( + [ + PathResolver::syncPermissions("{$this->tempDir}/missing.sh", "{$this->tempDir}/copy.sh"), + fileperms("{$this->tempDir}/copy.sh"), + ], + [ + Message::FILESYSTEM_FAILED->getMessage( + ConsoleMessage::SCAFFOLD_PERMISSIONS_COPY_FAILED->getMessage( + "{$this->tempDir}/missing.sh", + "{$this->tempDir}/copy.sh", + ), + "fileperms(): stat failed for {$this->tempDir}/missing.sh", + ), + $before, + ], + 'Missing source must be reported and the destination bits must stay unchanged.', ); } - public function testSourceStripsTrailingSeparatorFromProviderPath(): void + public function throwRuntimeExceptionWhenParentIsARegularFile(): void { - self::assertSame( - '/tmp/provider' . DIRECTORY_SEPARATOR . 'file.txt', - PathResolver::source('/tmp/provider/', 'file.txt'), - 'Trailing separator in provider path must not produce a double separator.', + file_put_contents( + "{$this->tempDir}/blocker", + 'x', ); - } - - public function testSyncPermissionsCopiesSourcePermissionBitsOntoDestinationUnderPermissiveUmask(): void - { - if (DIRECTORY_SEPARATOR === '\\') { - self::markTestSkipped('POSIX umask-based permissions do not apply to NTFS (Windows always reports 0777).'); - } - - $source = "{$this->tempDir}/exec.sh"; - $destination = "{$this->tempDir}/exec-copy.sh"; - - file_put_contents($source, "#!/bin/sh\necho hello\n"); - file_put_contents($destination, "#!/bin/sh\necho hello\n"); - - chmod($source, 0o755); - chmod($destination, 0o644); - - $oldUmask = umask(0o022); - - try { - PathResolver::syncPermissions($source, $destination); - - self::assertSame( - 0o755, - fileperms($destination) & 0o777, - "Under a permissive '0022' umask, 'syncPermissions()' must preserve the source executable bit.", - ); - } finally { - umask($oldUmask); - } - } - - public function testSyncPermissionsHonorsRestrictiveUmaskToAvoidSilentlyWideningPermissions(): void - { - if (DIRECTORY_SEPARATOR === '\\') { - self::markTestSkipped('POSIX umask-based permissions do not apply to NTFS (Windows always reports 0777).'); - } - - $source = "{$this->tempDir}/world-readable.sh"; - $destination = "{$this->tempDir}/world-readable-copy.sh"; - - file_put_contents($source, "#!/bin/sh\n"); - file_put_contents($destination, "#!/bin/sh\n"); - - chmod($source, 0o755); - chmod($destination, 0o600); - $oldUmask = umask(0o077); + $directory = "{$this->tempDir}/blocker/sub"; - try { - PathResolver::syncPermissions($source, $destination); - - self::assertSame( - 0o700, - fileperms($destination) & 0o777, - "Under a restrictive '0077' umask, 'syncPermissions()' must mask source perms and drop group/other bits.", + Expect::exception(RuntimeException::class) + ->withMessageMatchingRegex( + '/\A' + . preg_quote(Message::PATH_DIRECTORY_CREATE_FAILED->getMessage($directory) . ' Reason: mkdir(): ', '/') + . '.+\.\z/', ); - } finally { - umask($oldUmask); - } - } - - public function testSyncPermissionsMasksSourceBitsWithPermsAnd0777RatherThanPermsOr0777(): void - { - if (DIRECTORY_SEPARATOR === '\\') { - self::markTestSkipped('POSIX umask-based permissions do not apply to NTFS (Windows always reports 0777).'); - } - - $source = "{$this->tempDir}/mode-0640.sh"; - $destination = "{$this->tempDir}/mode-0640-copy.sh"; - - file_put_contents($source, "#!/bin/sh\n"); - file_put_contents($destination, "#!/bin/sh\n"); - - chmod($source, 0o640); - chmod($destination, 0o600); - - // '0000' umask isolates the `& 0777` mask from the umask step so `& → |` mutations are directly observable. - $oldUmask = umask(0o000); - try { - PathResolver::syncPermissions($source, $destination); - - self::assertSame( - 0o640, - fileperms($destination) & 0o777, - "Under a permissive '0000' umask, the destination must land on exactly the source permissions (0640).", - ); - } finally { - umask($oldUmask); - } + PathResolver::ensureDirectory("{$directory}/file.txt"); } - public function testSyncPermissionsReturnsEarlyWhenSourceFilepermsIsFalse(): void + /** + * Replaces the `{tmp}` and `{real}` placeholders with the temporary directory and its canonical path, and `{/}` + * with the platform separator that the resolver joins with. + * + * @param string $path Path with placeholders. + * + * @return string Path with the placeholders replaced. + */ + private function expand(string $path): string { - if (DIRECTORY_SEPARATOR === '\\') { - self::markTestSkipped('POSIX umask-based permissions do not apply to NTFS (Windows always reports 0777).'); - } - - $destination = "{$this->tempDir}/unchanged.sh"; - - file_put_contents($destination, "#!/bin/sh\n"); - - chmod($destination, 0o644); - - PathResolver::syncPermissions("{$this->tempDir}/does-not-exist", $destination); - - self::assertSame( - 0o644, - fileperms($destination) & 0o777, - "When 'fileperms()' returns 'false', 'syncPermissions()' must return early and leave the destination untouched.", + return str_replace( + ['{tmp}', '{real}', '{/}'], + [$this->tempDir, (string) realpath($this->tempDir), DIRECTORY_SEPARATOR], + $path, ); } - - protected function setUp(): void - { - $this->setUpTempDirectory(); - } - - protected function tearDown(): void - { - $this->tearDownTempDirectory(); - } } diff --git a/tests/Scaffold/ScaffoldRunnerTest.php b/tests/Scaffold/ScaffoldRunnerTest.php new file mode 100644 index 0000000..931e4a3 --- /dev/null +++ b/tests/Scaffold/ScaffoldRunnerTest.php @@ -0,0 +1,574 @@ +tempDir)) + ->provider('p/a', ['a.txt' => "provider\n"]) + ->file('a.txt', "mine\n") + ->track('a.txt', 'p/a', 'replace', ['stub-hash' => null]); + + $lock = new LockFile($this->tempDir); + + $data = $lock->read(); + + $data['files']['a.txt']['adopted'] = true; + + $lock->write($data); + + $summary = $this->runner(['p/a'], new BufferedOutputWriter()) + ->run( + new ProjectConfig(['p/a']), + ['p/a' => new ProviderPackage('p/a', '1.0.0', "{$this->tempDir}/vendor/p/a")], + $this->tempDir, + ); + + FileAssert::contentSame( + "{$this->tempDir}/a.txt", + "mine\n", + 'Adopted file must stay.', + ); + Assert::same( + self::counters($summary), + ['written' => 0, 'unchanged' => 0, 'warnings' => 1, 'errors' => 0, 'conflict' => 0, 'outdated' => 0], + "Skip must count one warning and no conflict without a recorded 'stub-hash'.", + ); + } + + public function appendDestinationHoldingTheBlockIsNotAdopted(): void + { + (new InspectionProject($this->tempDir)) + ->provider('p/a', ['a.txt' => "block\n"], ['a.txt' => 'append']) + ->file('a.txt', "mine\nblock\n"); + + $summary = $this->runner(['p/a'], new BufferedOutputWriter()) + ->run( + new ProjectConfig(['p/a']), + ['p/a' => new ProviderPackage('p/a', '1.0.0', "{$this->tempDir}/vendor/p/a")], + $this->tempDir, + ); + + Assert::same( + [ + array_key_exists( + 'adopted', + (new LockFile($this->tempDir))->read()['files']['a.txt'] ?? [] + ), + $summary->unchanged, + ], + [false, 1], + "Entry must be recorded without 'adopted' and count as 'unchanged'.", + ); + } + + public function appliesProvidersReadFromComposerJsonAndFromExtra(): void + { + $project = (new InspectionProject($this->tempDir)) + ->provider('p/a', ['a.txt' => "a\n"]) + ->provider('p/b', ['b.txt' => "b\n"]); + + $out = new BufferedOutputWriter(); + + $summary = $this->runner(['p/a', 'p/b'], $out) + ->run( + new ProjectConfig(['p/a', 'p/b']), + [ + 'p/a' => new ProviderPackage( + 'p/a', + '1.0.0', + "{$this->tempDir}/vendor/p/a", + ), + 'p/b' => new ProviderPackage( + 'p/b', + '2.0.0', + "{$this->tempDir}/vendor/p/b", + ['scaffold' => ['copy' => [['from' => 'stubs/b.txt', 'to' => 'b.txt']]]], + ), + ], + $this->tempDir, + ); + + FileAssert::contentSame( + "{$this->tempDir}/a.txt", + "a\n", + "Provider read from 'composer.json' must apply.", + ); + FileAssert::contentSame( + "{$this->tempDir}/b.txt", + "b\n", + "Provider read from 'extra' must apply.", + ); + Assert::same( + $summary->written, + 2, + "Both files must count as 'written'.", + ); + Assert::same( + $project->lock()->read()['providers'], + [ + 'p/a' => ['version' => '1.0.0', 'path' => 'vendor/p/a'], + 'p/b' => ['version' => '2.0.0', 'path' => 'vendor/p/b'], + ], + 'Providers must be recorded with relative paths.', + ); + Assert::same( + $out->stderrBuffer, + '', + 'No warning expected.', + ); + } + + public function ejectedFileIsCountedAndTheNextFileStillApplies(): void + { + (new InspectionProject($this->tempDir)) + ->provider('p/a', ['a.txt' => "provider\n", 'b.txt' => "b\n"]) + ->file('a.txt', "mine\n") + ->track('a.txt', 'p/a', 'replace', ['ejected' => true]); + + $summary = $this->runner(['p/a'], new BufferedOutputWriter()) + ->run( + new ProjectConfig(['p/a']), + ['p/a' => new ProviderPackage('p/a', '1.0.0', "{$this->tempDir}/vendor/p/a")], + $this->tempDir, + ); + + FileAssert::contentSame( + "{$this->tempDir}/a.txt", + "mine\n", + 'Ejected file must stay.', + ); + FileAssert::contentSame( + "{$this->tempDir}/b.txt", + "b\n", + 'Next file must apply.', + ); + Assert::same( + self::counters($summary), + ['written' => 1, 'unchanged' => 1, 'warnings' => 0, 'errors' => 0, 'conflict' => 0, 'outdated' => 0], + "Ejected file must count as 'unchanged' and the next one as 'written'.", + ); + } + + public function forceOverwritesUserModifiedReplaceFile(): void + { + $project = (new InspectionProject($this->tempDir)) + ->provider('p/a', ['a.txt' => "provider\n"]) + ->file('a.txt', "provider\n") + ->track('a.txt', 'p/a'); + + file_put_contents( + "{$this->tempDir}/a.txt", + "mine\n", + ); + + $providers = [ + 'p/a' => new ProviderPackage('p/a', '1.0.0', "{$this->tempDir}/vendor/p/a"), + ]; + + $out = new BufferedOutputWriter(); + + $this->runner(['p/a'], $out) + ->run( + new ProjectConfig(['p/a']), + $providers, + $this->tempDir, + ); + + FileAssert::contentSame( + "{$this->tempDir}/a.txt", + "mine\n", + 'Without force the edit must stay.', + ); + Assert::true( + str_contains($out->stderrBuffer, Message::SCAFFOLD_USER_MODIFIED_SKIPPED->getMessage('a.txt')), + 'Skipped user-modified file must be warned.', + ); + + $forced = new BufferedOutputWriter(); + + $summary = $this->runner(['p/a'], $forced) + ->run( + new ProjectConfig(['p/a']), + $providers, + $this->tempDir, + true, + ); + + FileAssert::contentSame( + "{$this->tempDir}/a.txt", + "provider\n", + 'Force must overwrite the edit.', + ); + Assert::same( + [$forced->stderrBuffer, $summary->written, $project->lock()->read()['files']['a.txt']['hash'] ?? null], + ['', 1, Hasher::hash("{$this->tempDir}/a.txt")], + "Forced overwrite must be silent, count as 'written' and record the new hash.", + ); + } + + public function forceRewritesAdoptedReplaceFileAndClearsTheFlag(): void + { + $project = (new InspectionProject($this->tempDir)) + ->provider('p/a', ['a.txt' => "provider\n"]) + ->file('a.txt', "mine\n") + ->track('a.txt', 'p/a', 'replace', ['adopted' => 'yes']); + + $data = $project->lock()->read(); + + $data['files']['a.txt']['adopted'] = true; + + $project->lock()->write($data); + + $this->runner(['p/a'], new BufferedOutputWriter()) + ->run( + new ProjectConfig(['p/a']), + ['p/a' => new ProviderPackage('p/a', '1.0.0', "{$this->tempDir}/vendor/p/a")], + $this->tempDir, + true, + ); + + FileAssert::contentSame( + "{$this->tempDir}/a.txt", + "provider\n", + 'Adopted file must be replaced.', + ); + Assert::false( + array_key_exists( + 'adopted', + (new LockFile($this->tempDir))->read()['files']['a.txt'] ?? [], + ), + "Flag 'adopted' must be cleared.", + ); + } + + public function metapackageAloneLeavesNoLockFile(): void + { + $this->runner(['p/meta'], new BufferedOutputWriter()) + ->run( + new ProjectConfig(['p/meta']), + ['p/meta' => new ProviderPackage('p/meta', '1.0.0', null, [])], + $this->tempDir, + ); + + FileAssert::fileDoesNotExist( + "{$this->tempDir}/scaffold-lock.json", + 'Nothing must be recorded.', + ); + } + + public function metapackageWithoutInstallPathIsSkippedWithWarning(): void + { + (new InspectionProject($this->tempDir)) + ->provider('p/a', ['a.txt' => "a\n"]); + + $out = new BufferedOutputWriter(); + + $summary = $this->runner(['p/meta', 'p/a'], $out) + ->run( + new ProjectConfig(['p/meta', 'p/a']), + [ + 'p/meta' => new ProviderPackage('p/meta', '1.0.0', null, []), + 'p/a' => new ProviderPackage('p/a', '1.0.0', "{$this->tempDir}/vendor/p/a"), + ], + $this->tempDir, + ); + + FileAssert::contentSame( + "{$this->tempDir}/a.txt", + "a\n", + 'Next provider must still apply.', + ); + Assert::same( + [$out->stderrBuffer, $summary->warnings, $summary->written], + [Message::SCAFFOLD_PROVIDER_INSTALL_PATH_MISSING->getMessage('p/meta') . PHP_EOL, 1, 1], + "Metapackage must be reported as one warning and the next file counted as 'written'.", + ); + } + + public function orphanCountAccumulatesAcrossRunsSharingTheSummary(): void + { + (new InspectionProject($this->tempDir)) + ->file('old.txt', "old\n")->track('old.txt', 'p/gone'); + + $runner = $this->runner( + ['p/gone'], + new BufferedOutputWriter(), + ); + + $runner->run(new ProjectConfig(['p/gone']), [], $this->tempDir); + + $summary = $runner->run(new ProjectConfig(['p/gone']), [], $this->tempDir); + + Assert::same( + $summary->orphan, + 2, + 'Counters of a shared summary must add up.', + ); + } + + public function orphansAreListedWithLimitAndRemainder(): void + { + $project = (new InspectionProject($this->tempDir))->provider('p/a', ['a.txt' => "a\n"]); + + foreach ( + [ + 'old1', + 'old10', + 'old11', + 'old12', + 'old2', + 'old3', + 'old4', + 'old5', + 'old6', + 'old7', + 'old8', + 'old9', + ] as $name) { + $project->file("{$name}.txt", "old\n")->track("{$name}.txt", 'p/a'); + } + + $out = new BufferedOutputWriter(); + + $summary = $this->runner(['p/a'], $out) + ->run( + new ProjectConfig(['p/a']), + ['p/a' => new ProviderPackage('p/a', '1.0.0', "{$this->tempDir}/vendor/p/a")], + $this->tempDir, + ); + + Assert::same( + $out->stderrBuffer, + implode( + PHP_EOL, + [ + Message::SCAFFOLD_ORPHAN_HEADER->getMessage(12, Message::FRAGMENT_FILES->getMessage()), + Message::SCAFFOLD_ORPHAN_ENTRY->getMessage('old1.txt', 'p/a'), + Message::SCAFFOLD_ORPHAN_ENTRY->getMessage('old10.txt', 'p/a'), + Message::SCAFFOLD_ORPHAN_ENTRY->getMessage('old11.txt', 'p/a'), + Message::SCAFFOLD_ORPHAN_ENTRY->getMessage('old12.txt', 'p/a'), + Message::SCAFFOLD_ORPHAN_ENTRY->getMessage('old2.txt', 'p/a'), + Message::SCAFFOLD_ORPHAN_ENTRY->getMessage('old3.txt', 'p/a'), + Message::SCAFFOLD_ORPHAN_ENTRY->getMessage('old4.txt', 'p/a'), + Message::SCAFFOLD_ORPHAN_ENTRY->getMessage('old5.txt', 'p/a'), + Message::SCAFFOLD_ORPHAN_ENTRY->getMessage('old6.txt', 'p/a'), + Message::SCAFFOLD_ORPHAN_ENTRY->getMessage('old7.txt', 'p/a'), + Message::SCAFFOLD_ORPHAN_MORE->getMessage(2), + '', + ], + ), + 'Header, the first ten orphans and the remainder line expected.', + ); + Assert::same( + $summary->orphan, + 12, + 'Summary must count every orphan.', + ); + FileAssert::fileExists( + "{$this->tempDir}/old12.txt", + 'Orphans must never be deleted.', + ); + Assert::true( + array_key_exists('old12.txt', $project->lock()->read()['files']), + 'Orphan lock entries must stay.', + ); + } + + public function orphansAreReportedWhenNoProviderShipsAnything(): void + { + (new InspectionProject($this->tempDir)) + ->file('old.txt', "old\n")->track('old.txt', 'p/gone'); + + $out = new BufferedOutputWriter(); + + $summary = $this->runner(['p/gone'], $out) + ->run( + new ProjectConfig(['p/gone']), + [], + $this->tempDir, + ); + + Assert::same( + [$out->stderrBuffer, $summary->orphan], + [ + Message::SCAFFOLD_PROVIDER_NOT_INSTALLED->getMessage('p/gone') . PHP_EOL + . Message::SCAFFOLD_ORPHAN_HEADER->getMessage(1, Message::FRAGMENT_FILE->getMessage()) . PHP_EOL + . Message::SCAFFOLD_ORPHAN_ENTRY->getMessage('old.txt', 'p/gone') . PHP_EOL, + 1, + ], + 'Orphan must be reported and counted without mappings.', + ); + } + + public function providerWithoutMappingsIsWarnedAndTheNextProviderStillApplies(): void + { + (new InspectionProject($this->tempDir)) + ->provider('p/a', ['a.txt' => "a\n"]); + + $out = new BufferedOutputWriter(); + + $summary = $this->runner(['p/empty', 'p/a'], $out) + ->run( + new ProjectConfig(['p/empty', 'p/a']), + [ + 'p/empty' => new ProviderPackage('p/empty', '1.0.0', "{$this->tempDir}/vendor/p/empty", []), + 'p/a' => new ProviderPackage('p/a', '1.0.0', "{$this->tempDir}/vendor/p/a"), + ], + $this->tempDir, + ); + + FileAssert::contentSame( + "{$this->tempDir}/a.txt", + "a\n", + 'Next provider must apply.', + ); + Assert::same( + [$out->stderrBuffer, self::counters($summary)], + [ + Message::SCAFFOLD_PROVIDER_MAPPINGS_EMPTY->getMessage('p/empty') . PHP_EOL, + ['written' => 1, 'unchanged' => 0, 'warnings' => 1, 'errors' => 0, 'conflict' => 0, 'outdated' => 0], + ], + "Empty provider must be warned once and the next file must count as 'written'.", + ); + } + + #[DataProvider(ScaffoldRunnerProvider::class . '::providerPaths')] + public function recordsProviderPathRelativeToProjectRoot( + string $installPath, + string $projectRoot, + string $expected, + ): void { + $installPath = $this->expand($installPath); + + (new InspectionProject($installPath)) + ->file('stubs/a.txt', "a\n"); + + $out = new BufferedOutputWriter(); + + // The applier allows no provider, so no file is written outside the temporary directory. + (new ScaffoldRunner( + new ManifestLoader(new ManifestSchema(), new ManifestExpander()), + new FileApplier(new ProjectConfig([]), new PathValidator(), $out), + new LockFile($this->tempDir), + $out, + new ScaffoldSummary(), + ))->run( + new ProjectConfig(['p/a']), + [ + 'p/a' => new ProviderPackage( + 'p/a', + '1.0.0', + $installPath, + ['scaffold' => ['copy' => [['from' => 'stubs/a.txt', 'to' => 'a.txt']]]], + ), + ], + $this->expand($projectRoot), + ); + + Assert::same( + (new LockFile($this->tempDir))->read()['providers'], + ['p/a' => ['version' => '1.0.0', 'path' => $this->expand($expected)]], + 'Recorded provider path must match.', + ); + } + + /** + * Returns the counters of `$summary` that a run updates, except the orphan count. + * + * @return array{written: int, unchanged: int, warnings: int, errors: int, conflict: int, outdated: int} + */ + private static function counters(ScaffoldSummary $summary): array + { + return [ + 'written' => $summary->written, + 'unchanged' => $summary->unchanged, + 'warnings' => $summary->warnings, + 'errors' => $summary->errors, + 'conflict' => $summary->conflict, + 'outdated' => $summary->outdated, + ]; + } + + /** + * Replaces the `{tmp}` placeholder with the temporary directory, `{real}` with its canonical path in forward + * slashes as the lock records it, `{root}` with the filesystem root that holds it (a drive root on Windows) and + * `{rel}` with `{real}` relative to `{root}`. + * + * @param string $path Path with placeholders. + * + * @return string Path with the placeholders replaced. + */ + private function expand(string $path): string + { + $real = (string) realpath($this->tempDir); + $root = $real; + + while (dirname($root) !== $root) { + $root = dirname($root); + } + + $normalized = str_replace('\\', '/', $real); + + return str_replace( + ['{tmp}', '{real}', '{root}', '{rel}'], + [$this->tempDir, $normalized, $root, ltrim(substr($normalized, strlen($root)), '/')], + $path, + ); + } + + /** + * Builds a runner for the project in the temporary directory. + * + * @param list $allowed Providers allowed to write files. + * @param BufferedOutputWriter $out Output sink of the messages. + * + * @return ScaffoldRunner Runner configured for the test. + */ + private function runner(array $allowed, BufferedOutputWriter $out): ScaffoldRunner + { + return new ScaffoldRunner( + new ManifestLoader(new ManifestSchema(), new ManifestExpander()), + new FileApplier(new ProjectConfig($allowed), new PathValidator(), $out), + new LockFile($this->tempDir), + $out, + new ScaffoldSummary(), + ); + } +} diff --git a/tests/Scaffold/ScaffoldSummaryTest.php b/tests/Scaffold/ScaffoldSummaryTest.php new file mode 100644 index 0000000..042cd5f --- /dev/null +++ b/tests/Scaffold/ScaffoldSummaryTest.php @@ -0,0 +1,58 @@ +format(), $summary->format('sync')], + [ExpectedSummary::line(0, 0), ExpectedSummary::withCommand('sync', 0, 0)], + 'Format must always render, with the command name when one is given.', + ); + } + + #[DataProvider(ScaffoldSummaryProvider::class . '::reapplyLines')] + public function reapplyLineListsSkipReasons(ReapplySummary $summary, bool $dryRun, string $expected): void + { + Assert::same( + $summary->line($dryRun), + $expected, + 'Reapply summary line must match.', + ); + } + + #[DataProvider(ScaffoldSummaryProvider::class . '::scaffoldLines')] + public function scaffoldLineListsAttentionCountsOnlyWhenNotZero( + ScaffoldSummary $summary, + string|null $expected, + ): void { + Assert::same( + $summary->line(), + $expected, + 'Scaffold summary line must match.', + ); + } +} diff --git a/tests/Scaffold/ScaffolderToProjectRelativeTest.php b/tests/Scaffold/ScaffolderToProjectRelativeTest.php deleted file mode 100644 index d96385e..0000000 --- a/tests/Scaffold/ScaffolderToProjectRelativeTest.php +++ /dev/null @@ -1,124 +0,0 @@ -call('/tmp/project/pkg', '/tmp/Project'); - - if (DIRECTORY_SEPARATOR === '\\') { - self::assertSame( - 'pkg', - $actual, - 'On Windows, mixed-case prefixes must match via case-insensitive comparison.', - ); - - return; - } - - self::assertSame( - '/tmp/project/pkg', - $actual, - 'On POSIX, mixed-case prefixes must not match (byte-exact comparison required).', - ); - } - - public function testNormalizesBackslashSeparatorsInAbsolutePathBeforePrefixMatch(): void - { - self::assertSame( - 'pkg', - $this->call('/tmp/project/subdir\\pkg', '/tmp/project/subdir'), - 'absolutePath containing a backslash must be normalized to forward-slashes before the prefix check.', - ); - } - public function testNormalizesBackslashSeparatorsInProjectRootBeforePrefixMatch(): void - { - self::assertSame( - 'pkg', - $this->call('/tmp/project/subdir/pkg', '/tmp/project\\subdir'), - 'projectRoot containing a backslash must be normalized to forward-slashes before the prefix check.', - ); - } - public function testReturnsBasenameRelativeWhenPackagePathSitsInsideProjectRoot(): void - { - self::assertSame( - 'vendor/pkg', - $this->call('/tmp/project/vendor/pkg', '/tmp/project'), - 'Package path inside the project root must be returned as a project-relative path with forward slashes.', - ); - } - - public function testReturnsEmptyStringWhenPackagePathEqualsProjectRootExactly(): void - { - self::assertSame( - '', - $this->call('/tmp/project', '/tmp/project'), - "When the package path equals the project root exactly, 'toProjectRelative' must return an empty string.", - ); - } - - public function testReturnsFullAbsolutePathWithForwardSlashesWhenOutsideProjectRoot(): void - { - self::assertSame( - '/outside/project/pkg', - $this->call('/outside/project/pkg', '/tmp/project'), - 'Package paths outside the project root must fall back to the normalized absolute path.', - ); - } - - public function testStripsTrailingSeparatorFromAbsoluteFallbackWhenOutsideProjectRoot(): void - { - self::assertSame( - '/other/location', - $this->call('/other/location/', '/tmp/project'), - "When the package path is outside the project root, the fallback must 'rtrim' trailing separators.", - ); - } - - public function testStripsTrailingSeparatorFromProjectRootBeforePrefixCheck(): void - { - self::assertSame( - 'vendor/pkg', - $this->call('/tmp/project/vendor/pkg', '/tmp/project/'), - "A trailing separator on the project root must be stripped before the prefix check via 'rtrim'.", - ); - } - - public function testStripsTrailingSeparatorFromRelativeReturnValue(): void - { - self::assertSame( - 'vendor/pkg', - $this->call('/tmp/project/vendor/pkg/', '/tmp/project'), - "A trailing separator on the relative segment (after 'substr') must be stripped via outer 'rtrim'.", - ); - } - - /** - * Invokes the private static {@see Scaffolder::toProjectRelative()} via reflection. - */ - private function call(string $absolutePath, string $projectRoot): string - { - $method = new ReflectionMethod(Scaffolder::class, 'toProjectRelative'); - - /** @var string $result */ - $result = $method->invoke(null, $absolutePath, $projectRoot); - - return $result; - } -} diff --git a/tests/Security/PackageAllowlistTest.php b/tests/Security/PackageAllowlistTest.php deleted file mode 100644 index ba6b6e7..0000000 --- a/tests/Security/PackageAllowlistTest.php +++ /dev/null @@ -1,117 +0,0 @@ -expectNotToPerformAssertions(); - - $list = new PackageAllowlist(['php-forge/nginx-scaffold']); - - $list->assertAllowed('php-forge/nginx-scaffold'); - } - - public function testAssertAllowedThrowsForEmptyAllowlist(): void - { - $list = new PackageAllowlist([]); - - $this->expectException(RuntimeException::class); - $this->expectExceptionMessage('allowed-packages'); - - $list->assertAllowed('any/package'); - } - - public function testAssertAllowedThrowsForUnauthorizedPackage(): void - { - $list = new PackageAllowlist(['php-forge/app-base-scaffold']); - - $this->expectException(RuntimeException::class); - $this->expectExceptionMessage('php-forge/nginx-scaffold'); - - $list->assertAllowed('php-forge/nginx-scaffold'); - } - - public function testEmptyAllowlistRejectsEveryPackage(): void - { - $list = new PackageAllowlist([]); - - self::assertFalse( - $list->isAllowed('php-forge/anything'), - 'Empty allowlist should reject all packages.', - ); - } - - public function testIsAllowedUsesStrictStringComparison(): void - { - $list = new PackageAllowlist(['php-forge/nginx-scaffold']); - - self::assertFalse( - $list->isAllowed('php-forge/apache-scaffold'), - 'Package not in allowlist should not be allowed.', - ); - self::assertTrue( - $list->isAllowed('php-forge/nginx-scaffold'), - 'Package in allowlist should be allowed.', - ); - } - - public function testMultiplePackagesInAllowlist(): void - { - $list = new PackageAllowlist([ - 'php-forge/app-base-scaffold', - 'php-forge/nginx-scaffold', - 'php-forge/inertia-vue-scaffold', - ]); - - self::assertTrue( - $list->isAllowed('php-forge/app-base-scaffold'), - 'First package in allowlist should be allowed.', - ); - self::assertTrue( - $list->isAllowed('php-forge/nginx-scaffold'), - 'Second package in allowlist should be allowed.', - ); - self::assertTrue( - $list->isAllowed('php-forge/inertia-vue-scaffold'), - 'Third package in allowlist should be allowed.', - ); - self::assertFalse( - $list->isAllowed('php-forge/apache-scaffold'), - 'Package not in allowlist should not be allowed.', - ); - } - - public function testPackageInAllowlistIsAllowed(): void - { - $list = new PackageAllowlist(['php-forge/app-base-scaffold', 'php-forge/nginx-scaffold']); - - self::assertTrue( - $list->isAllowed('php-forge/app-base-scaffold'), - 'Package in allowlist should be allowed.', - ); - } - - public function testPackageNotInAllowlistIsNotAllowed(): void - { - $list = new PackageAllowlist(['php-forge/app-base-scaffold']); - - self::assertFalse( - $list->isAllowed('php-forge/nginx-scaffold'), - 'Package not in allowlist should not be allowed.', - ); - } -} diff --git a/tests/Security/PathValidatorTest.php b/tests/Security/PathValidatorTest.php index cbae95e..d60a541 100644 --- a/tests/Security/PathValidatorTest.php +++ b/tests/Security/PathValidatorTest.php @@ -4,322 +4,136 @@ namespace PHPForge\Scaffold\Tests\Security; +use PHPForge\Scaffold\Exception\Message; use PHPForge\Scaffold\Security\PathValidator; +use PHPForge\Scaffold\Tests\Provider\PathValidatorProvider; use PHPForge\Scaffold\Tests\Support\TempDirectoryTrait; -use PHPUnit\Framework\Attributes\{Group, RequiresOperatingSystemFamily}; -use PHPUnit\Framework\TestCase; -use ReflectionMethod; use RuntimeException; +use Testo\Assert; +use Testo\Codecov\Covers; +use Testo\Core\Exception\SkipTest; +use Testo\Data\{DataProvider, DataSet}; +use Testo\Expect; +use Testo\Test; + +use function realpath; +use function str_replace; +use function symlink; /** - * Unit tests for {@see PathValidator} path traversal and absolute path detection. + * Unit tests for {@see PathValidator} path traversal, absolute path, symlink escape and reserved destination detection. + * + * {@see PathValidatorProvider} for test case data providers. */ -#[Group('scaffold')] -#[Group('security')] -final class PathValidatorTest extends TestCase +#[Test] +#[Covers(PathValidator::class)] +final class PathValidatorTest { use TempDirectoryTrait; - public function testDestinationAcceptsDeepNonExistentPathInsideRoot(): void - { - $this->expectNotToPerformAssertions(); - - (new PathValidator())->validateDestination('a/b/c/d/does-not-exist.txt', $this->tempDir); - } - - public function testDestinationAcceptsEmptyRelativePath(): void - { - $this->expectNotToPerformAssertions(); - - (new PathValidator())->validateDestination('', $this->tempDir); - } - - public function testDestinationAcceptsNonExistentFileInsideExistingSubdirectory(): void - { - // Walking to an existing in-root ancestor must NOT trigger an escape detection. - $root = "{$this->tempDir}/root"; - - mkdir($root . '/sub', 0o777, recursive: true); - - $this->expectNotToPerformAssertions(); - - (new PathValidator())->validateDestination('sub/missing-file.txt', $root); - } - - public function testDestinationAcceptsPathWithColonInSegment(): void - { - $this->expectNotToPerformAssertions(); - - // Colon in a non-leading segment must not be mistaken for a Windows drive letter prefix. - (new PathValidator())->validateDestination('nested/C:file.txt', $this->tempDir); - } - - public function testDestinationAcceptsSymlinkThatLoopsBackToRoot(): void - { - if (DIRECTORY_SEPARATOR === '\\') { - // Windows canonicalizes symlink targets with short-path/long-path variance that shifts the prefix used by - // `realpath`, so the POSIX "loop-to-root" equivalence this test models is not reproducible reliably there. - self::markTestSkipped('Symlink canonicalization on Windows is not equivalent to POSIX.'); - } - - // A symlink whose resolved target is `realRoot` itself must pass when used as an ancestor of a missing leaf. - $root = "{$this->tempDir}/root"; - - mkdir($root, 0o777, recursive: true); - - $this->createSymlinkOrSkip($root, $root . '/loop'); - $this->expectNotToPerformAssertions(); - - (new PathValidator())->validateDestination('loop/missing-file.txt', $root); - } - - public function testDestinationAcceptsTrailingSeparator(): void - { - $this->expectNotToPerformAssertions(); - - (new PathValidator())->validateDestination('config/', $this->tempDir); - } - - public function testDestinationRejectsNonExistentLeafBeneathSiblingPrefixSymlink(): void - { - // `rootsibling` shares a string prefix with `root` but resolves outside root. Because the leaf does not exist, - // the validator walks ancestors and must detect the escape at the resolved symlink inside the loop (L125). - $root = "{$this->tempDir}/root"; - $sibling = "{$this->tempDir}/rootsibling"; - - mkdir($root, 0o777, recursive: true); - mkdir($sibling, 0o777, recursive: true); - - $this->createSymlinkOrSkip($sibling, $root . '/link'); - - $this->expectException(RuntimeException::class); - $this->expectExceptionMessage('Destination path escapes the root via symlink'); - - (new PathValidator())->validateDestination('link/missing-leaf.txt', $root); - } - - #[RequiresOperatingSystemFamily('Linux')] - public function testDestinationRejectsNonExistentPathBeneathSymlinkEscapingAncestor(): void - { - $root = "{$this->tempDir}/root"; - $outside = "{$this->tempDir}/outside"; - - mkdir($root, 0o777, recursive: true); - mkdir($outside, 0o777, recursive: true); - - $this->createSymlinkOrSkip($outside, $root . '/escape'); - $this->expectException(RuntimeException::class); - $this->expectExceptionMessage('Destination path escapes the root via symlink'); - - // The terminal file does not exist, forcing the validator to walk ancestors. - (new PathValidator())->validateDestination('escape/missing/file.txt', $root); - } - - #[RequiresOperatingSystemFamily('Linux')] - public function testDestinationRejectsSymlinkEscapingOutsideRoot(): void - { - $root = "{$this->tempDir}/root"; - $outside = "{$this->tempDir}/outside"; - - mkdir($root, 0o777, recursive: true); - mkdir($outside, 0o777, recursive: true); - - $this->createSymlinkOrSkip($outside, "{$root}/escape"); - $this->expectException(RuntimeException::class); - $this->expectExceptionMessage('Destination path escapes the root via symlink'); - - (new PathValidator())->validateDestination('escape', $root); - } - - public function testDestinationRejectsSymlinkToSiblingPrefix(): void - { - // `rootsibling` is a directory whose path shares a prefix with `root` but is not inside it. - $root = "{$this->tempDir}/root"; - $sibling = "{$this->tempDir}/rootsibling"; - - mkdir($root, 0o777, recursive: true); - mkdir($sibling, 0o777, recursive: true); - - $this->createSymlinkOrSkip($sibling, "{$root}/link"); - $this->expectException(RuntimeException::class); - $this->expectExceptionMessage('Destination path escapes the root via symlink'); - - (new PathValidator())->validateDestination('link', $root); - } - - public function testDestinationWithAbsoluteUnixPathThrows(): void - { - $this->expectException(RuntimeException::class); - $this->expectExceptionMessage('destination'); - - (new PathValidator())->validateDestination('/etc/passwd', sys_get_temp_dir()); - } - - public function testDestinationWithAbsoluteWindowsPathThrows(): void - { - $this->expectException(RuntimeException::class); - $this->expectExceptionMessage('destination'); - - (new PathValidator())->validateDestination('C:\\Windows\\System32\\file', sys_get_temp_dir()); - } - - public function testDestinationWithBackslashTraversalThrows(): void - { - $this->expectException(RuntimeException::class); - $this->expectExceptionMessage('destination'); - - (new PathValidator())->validateDestination('config\\..\\..\\etc\\passwd', sys_get_temp_dir()); - } - - public function testDestinationWithDotFileIsAllowed(): void - { - $this->expectNotToPerformAssertions(); - - (new PathValidator())->validateDestination('.gitignore', sys_get_temp_dir()); - } - - public function testDestinationWithDoubleDotInFilenameIsAllowed(): void - { - $this->expectNotToPerformAssertions(); - - // "foo..bar" has ".." inside a filename segment not a traversal component. - (new PathValidator())->validateDestination('foo..bar', sys_get_temp_dir()); - } - - public function testDestinationWithTraversalAtStartThrows(): void - { - $this->expectException(RuntimeException::class); - $this->expectExceptionMessage('destination'); - - (new PathValidator())->validateDestination('../../../etc/passwd', sys_get_temp_dir()); - } - - public function testDestinationWithTraversalInMiddleThrows(): void - { - $this->expectException(RuntimeException::class); - $this->expectExceptionMessage('destination'); - - (new PathValidator())->validateDestination('config/../../../etc/passwd', sys_get_temp_dir()); - } - - public function testNonExistentProjectRootThrows(): void - { - $this->expectException(RuntimeException::class); - - (new PathValidator())->validateDestination('config/params.php', '/nonexistent/path/' . uniqid()); - } - - public function testNonExistentProviderRootThrows(): void - { - $this->expectException(RuntimeException::class); - - (new PathValidator())->validateSource('stubs/params.php', '/nonexistent/provider/' . uniqid()); - } - - public function testNormalizePathStripsTrailingSeparatorFromCombinedResult(): void + /** + * @param 'destination'|'source' $kind Validated path kind. + * @param list $directories Directories to create besides the root, relative to the temporary directory. + * @param array $links Symbolic link targets keyed by link path. + */ + #[DataProvider(PathValidatorProvider::class . '::acceptedPaths')] + public function acceptsPathInsideRoot(string $kind, string $path, array $directories, array $links): void { - // Private 'normalizePath' exercised via reflection: must 'rtrim' trailing separators from the combined result. - $method = new ReflectionMethod(PathValidator::class, 'normalizePath'); + $this->seed($directories, $links); - /** @var string $result */ - $result = $method->invoke(new PathValidator(), '/root', 'subdir/'); - - self::assertSame( - '/root' . DIRECTORY_SEPARATOR . 'subdir', - $result, - 'Trailing separator on the relative segment must be stripped from the combined path.', + Assert::same( + $this->validate($kind, $path), + realpath("{$this->tempDir}/root"), + 'Accepted path must yield the canonical root.', ); } - public function testSourceAcceptsEmptyRelativePath(): void - { - $this->expectNotToPerformAssertions(); - - (new PathValidator())->validateSource('', $this->tempDir); - } - - #[RequiresOperatingSystemFamily('Linux')] - public function testSourceRejectsSymlinkEscapingOutsideRoot(): void - { - $root = "{$this->tempDir}/provider"; - $outside = "{$this->tempDir}/outside"; - - mkdir($root, 0o777, recursive: true); - mkdir($outside, 0o777, recursive: true); - - $this->createSymlinkOrSkip($outside, "{$root}/escape"); - $this->expectException(RuntimeException::class); - $this->expectExceptionMessage('symlink'); - - (new PathValidator())->validateSource('escape', $root); - } - - public function testSourceWithAbsolutePathThrows(): void - { - $this->expectException(RuntimeException::class); - $this->expectExceptionMessage('source'); - - (new PathValidator())->validateSource('/etc/shadow', sys_get_temp_dir()); - } - - public function testSourceWithTraversalAtStartThrows(): void + #[DataProvider(PathValidatorProvider::class . '::paths')] + public function classifiesAbsoluteAndTraversalPaths(string $path, bool $absolute, bool $traversal): void { - $this->expectException(RuntimeException::class); - $this->expectExceptionMessage('source'); - - (new PathValidator())->validateSource('../stubs/params.php', sys_get_temp_dir()); + Assert::same( + [PathValidator::isAbsolute($path), PathValidator::hasTraversal($path)], + [$absolute, $traversal], + "Absolute and traversal classification of '{$path}' must match.", + ); } - public function testSourceWithTraversalInMiddleThrows(): void - { - $this->expectException(RuntimeException::class); - $this->expectExceptionMessage('source'); - - (new PathValidator())->validateSource('stubs/../../../etc/shadow', sys_get_temp_dir()); - } + /** + * @param 'destination'|'source' $kind Validated path kind. + * @param list $directories Directories to create besides the root, relative to the temporary directory. + * @param array $links Symbolic link targets keyed by link path. + */ + #[DataProvider(PathValidatorProvider::class . '::rejectedPaths')] + public function throwRuntimeExceptionForRejectedPath( + string $kind, + string $path, + array $directories, + array $links, + string $message, + ): void { + $this->seed($directories, $links); - public function testValidNestedRelativeDestinationPasses(): void - { - $this->expectNotToPerformAssertions(); + Expect::exception(RuntimeException::class) + ->withMessage( + $message, + ); - (new PathValidator())->validateDestination('resources/js/Pages/Home.vue', sys_get_temp_dir()); + $this->validate($kind, $path); } - public function testValidRelativeDestinationPasses(): void + /** + * @param 'destination'|'source' $kind Validated path kind. + */ + #[DataSet(['destination', Message::PATH_PROJECT_ROOT_INACCESSIBLE], 'project root')] + #[DataSet(['source', Message::PATH_PROVIDER_ROOT_INACCESSIBLE], 'provider root')] + public function throwRuntimeExceptionWhenRootIsMissing(string $kind, Message $message): void { - $this->expectNotToPerformAssertions(); + Expect::exception(RuntimeException::class) + ->withMessage( + $message->getMessage("{$this->tempDir}/root"), + ); - (new PathValidator())->validateDestination('config/params.php', sys_get_temp_dir()); + $this->validate($kind, 'config/params.php'); } - public function testValidRelativeSourcePasses(): void + /** + * Creates the root, the extra directories and the symbolic links, skipping on Windows when links are needed. + * + * @param list $directories Directories to create besides the root, relative to the temporary directory. + * @param array $links Symbolic link targets keyed by link path, both relative to the temporary + * directory unless the target starts with `{tmp}`. + */ + private function seed(array $directories, array $links): void { - $this->expectNotToPerformAssertions(); - - (new PathValidator())->validateSource('stubs/params.php', sys_get_temp_dir()); - } + if ($links !== [] && DIRECTORY_SEPARATOR === '\\') { + throw new SkipTest( + 'Symbolic link resolution is only verified on POSIX.', + ); + } - protected function setUp(): void - { - $this->setUpTempDirectory(); - } + foreach (['root', ...$directories] as $directory) { + $this->ensureTestDirectory("{$this->tempDir}/{$directory}"); + } - protected function tearDown(): void - { - $this->tearDownTempDirectory(); + foreach ($links as $link => $target) { + symlink(str_replace('{tmp}', $this->tempDir, $target), "{$this->tempDir}/{$link}"); + } } /** - * Creates a filesystem symlink or skips the current test when the environment does not support symlink creation - * (for example, Windows without developer mode, restricted container mounts, or chroots without `CAP_SYS_ADMIN`). + * Validates `$path` as a destination or a source against the `root` directory. + * + * @param 'destination'|'source' $kind Validated path kind. + * @param string $path Path relative to the root. * - * @param string $target The target path the symlink should point to. - * @param string $link The path where the symlink should be created. + * @return string Canonical root returned by the validator. */ - private function createSymlinkOrSkip(string $target, string $link): void + private function validate(string $kind, string $path): string { - if (@symlink($target, $link) === false) { - self::markTestSkipped('Symlink creation is not supported in this environment.'); - } + $validator = new PathValidator(); + + return $kind === 'destination' + ? $validator->validateDestination($path, "{$this->tempDir}/root") + : $validator->validateSource($path, "{$this->tempDir}/root"); } } diff --git a/tests/Services/ApplyPreviewerTest.php b/tests/Services/ApplyPreviewerTest.php new file mode 100644 index 0000000..7e0340d --- /dev/null +++ b/tests/Services/ApplyPreviewerTest.php @@ -0,0 +1,173 @@ +mapping('a.txt', FileMode::Replace), $exists, $current, $proposed); + + Assert::same( + [$preview->changes(), $preview->differsOnlyInLineEndings()], + [$changes, $lineEndingsOnly], + "Flags 'changes' and 'differsOnlyInLineEndings' must match.", + ); + } + + /** + * @param string|null $current Destination content, or `null` when the destination is missing. + * @param array $expected Expected preview values keyed by property. + */ + #[DataProvider(ApplyPreviewerProvider::class . '::modes')] + public function proposesTheContentOfTheMode( + string $destination, + FileMode $mode, + MergeStrategyKind|null $strategy, + string $stub, + string|null $current, + array $expected, + ): void { + $project = (new InspectionProject($this->tempDir))->stub('p/a', $destination, $stub); + + if ($current !== null) { + $project->file($destination, $current); + } + + $preview = (new ApplyPreviewer())->preview($this->mapping($destination, $mode, $strategy), $this->tempDir); + + Assert::same( + [ + 'exists' => $preview->exists, + 'current' => $preview->current, + 'proposed' => $preview->proposed, + 'changes' => $preview->changes(), + 'informational' => $preview->informational, + ], + $expected, + 'Preview of the mode must match.', + ); + } + + /** + * @param LockEntry|null $entry Lock entry of the destination, or `null` when untracked. + */ + #[DataProvider(ApplyPreviewerProvider::class . '::userModified')] + public function reportsUserModifiedReplaceDestinations(array|null $entry, bool $expected): void + { + (new InspectionProject($this->tempDir))->stub('p/a', 'a.txt', "stub\n")->file('a.txt', "mine\n"); + + Assert::same( + (new ApplyPreviewer()) + ->preview($this->mapping('a.txt', FileMode::Replace), $this->tempDir, $entry) + ->userModified, + $expected, + "Flag 'userModified' must match the lock entry.", + ); + } + + public function throwRuntimeExceptionWhenDestinationCannotBeRead(): void + { + (new InspectionProject($this->tempDir))->stub('p/a', 'a.txt', "stub\n"); + + // A directory where the destination file is expected cannot be read as a file. + mkdir("{$this->tempDir}/a.txt"); + + Expect::exception(RuntimeException::class) + ->withMessageContaining( + Message::SERVICE_CURRENT_FILE_UNREADABLE->getMessage(PathResolver::destination($this->tempDir, 'a.txt')) + . ' Reason: file_get_contents(', + ); + + (new ApplyPreviewer()) + ->preview($this->mapping('a.txt', FileMode::Replace), $this->tempDir); + } + + public function throwRuntimeExceptionWhenStubCannotBeRead(): void + { + (new InspectionProject($this->tempDir))->stub('p/a', 'a.txt', "stub\n"); + + $stub = PathResolver::source("{$this->tempDir}/vendor/p/a", 'stubs/a.txt'); + + $this->restrictFileAccess($stub, 0o000); + + Expect::exception(RuntimeException::class) + ->withMessage( + Message::FILESYSTEM_FAILED->getMessage( + Message::SERVICE_STUB_UNREADABLE->getMessage($stub), + "file_get_contents({$stub}): Failed to open stream: Permission denied", + ), + ); + + (new ApplyPreviewer()) + ->preview($this->mapping('a.txt', FileMode::Replace), $this->tempDir); + } + + public function throwRuntimeExceptionWhenStubIsMissing(): void + { + Expect::exception(RuntimeException::class) + ->withMessage( + Message::SERVICE_STUB_NOT_FOUND->getMessage( + PathResolver::source("{$this->tempDir}/vendor/p/a", 'stubs/a.txt'), + ), + ); + + (new ApplyPreviewer()) + ->preview($this->mapping('a.txt', FileMode::Replace), $this->tempDir); + } + + /** + * Returns a mapping of `$destination` from the `p/a` provider stub. + */ + private function mapping( + string $destination, + FileMode $mode, + MergeStrategyKind|null $strategy = null, + ): FileMapping { + return new FileMapping( + $destination, + "stubs/{$destination}", + $mode, + 'p/a', + "{$this->tempDir}/vendor/p/a", + $strategy, + ); + } +} diff --git a/tests/Services/DiffServiceTest.php b/tests/Services/DiffServiceTest.php index 34b1e27..17a2ea4 100644 --- a/tests/Services/DiffServiceTest.php +++ b/tests/Services/DiffServiceTest.php @@ -4,754 +4,578 @@ namespace PHPForge\Scaffold\Tests\Services; -use PHPForge\Scaffold\Scaffold\Lock\{Hasher, LockFile}; +use PHPForge\Scaffold\Console\Message as ConsoleMessage; +use PHPForge\Scaffold\Exception\Message; +use PHPForge\Scaffold\Scaffold\PathResolver; use PHPForge\Scaffold\Services\DiffService; -use PHPForge\Scaffold\Tests\Support\{BufferedOutputWriter, TempDirectoryTrait}; -use PHPUnit\Framework\Attributes\Group; -use PHPUnit\Framework\TestCase; -use Xepozz\InternalMocker\MockerState; +use PHPForge\Scaffold\Tests\Support\{BufferedOutputWriter, InspectionProject, TempDirectoryTrait}; +use Testo\Assert; +use Testo\Codecov\Covers; +use Testo\Core\Exception\SkipTest; +use Testo\Test; + +use function dirname; +use function file_get_contents; +use function mkdir; +use function preg_quote; +use function realpath; +use function symlink; +use function unlink; /** - * Unit tests for {@see DiffService} covering diff computation and error handling for unsafe / missing inputs. + * Unit tests for {@see DiffService} rendering what applying the provider would change, per mode. */ -#[Group('scaffold')] -#[Group('services')] -final class DiffServiceTest extends TestCase +#[Test] +#[Covers(DiffService::class)] +final class DiffServiceTest { use TempDirectoryTrait; - public function testBuildDiffDoesNotStartOrEndWithNewline(): void + public function allDiffsTrackedFilesInLockOrderAndReportsOrphans(): void { - $diff = (new DiffService())->buildDiff("a\n", "a\nb\n", 'config/params.php'); + $project = $this->project() + ->provider('p/a', ['b.txt' => "b2\n", 'a.txt' => "a\n", 'gone.txt' => "g\n", 'e.txt' => "e\n"]) + ->file('a.txt', "a\n") + ->file('b.txt', "b\n") + ->file('gone.txt', "g\n") + ->file('e.txt', "mine\n") + ->track('b.txt', 'p/a') + ->track('a.txt', 'p/a') + ->track('gone.txt', 'p/a') + ->track('e.txt', 'p/a', extra: ['ejected' => true]) + ->provider('p/a', ['b.txt' => "b2\n", 'a.txt' => "a\n", 'e.txt' => "e\n"]); - self::assertStringStartsNotWith( - "\n", - $diff, - 'Diff must start with the first header line, not a newline.', - ); - self::assertStringEndsNotWith( - "\n", - $diff, - "The builder's trailing newline must be stripped; 'writeStdout' appends the final one.", - ); - } - - public function testBuildDiffEmitsGitStyleFileHeaders(): void - { - $diff = (new DiffService())->buildDiff("a\n", "a\nb\n", 'config/params.php'); + $out = new BufferedOutputWriter(); - self::assertStringStartsWith( - "--- a/config/params.php\n+++ b/config/params.php\n", - $diff, - "Headers must label the stub as 'a/' and the current file as 'b/'.", + Assert::same( + (new DiffService())->run($project->context(), $out), + 0, + "Exit code must be '0': orphans and changes are not errors.", ); - } - - public function testBuildDiffEmitsHunkHeaderWithLineRanges(): void - { - $diff = (new DiffService())->buildDiff( - "one\ntwo\nthree\nfour\nfive\n", - "one\ntwo\nchanged\nfour\nfive\n", - 'config/params.php', + Assert::same( + $out->stdoutBuffer, + ConsoleMessage::DIFF_NO_CHANGES->getMessage('a.txt') . PHP_EOL + . ConsoleMessage::DIFF_PREVIEW_HEADER->getMessage('b.txt', 'replace', 'p/a', '') . PHP_EOL + . "--- a/b.txt\n+++ b/b.txt\n@@ -1 +1 @@\n-b\n+b2" . PHP_EOL + . ConsoleMessage::DIFF_ORPHAN->getMessage('gone.txt') . PHP_EOL, + 'Files must follow lock order; ejected files are skipped.', ); - - self::assertStringContainsString( - '@@ -1,5 +1,5 @@', - $diff, - 'Hunk header must carry the from/to line ranges.', + Assert::same( + $out->stderrBuffer, + '', + 'Nothing may be written to stderr.', ); } - public function testBuildDiffLimitsContextToThreeLines(): void + public function allKeepsCountingErrorsAcrossOrphansAndDiffsLaterFiles(): void { - $diff = (new DiffService())->buildDiff( - "one\ntwo\nthree\nfour\nfive\nsix\nseven\neight\nnine\nten\n", - "one\ntwo\nthree\nfour\nfive\nchanged\nseven\neight\nnine\nten\n", - 'config/params.php', - ); + $project = $this->project() + ->provider('p/a', ['c.txt' => "c2\n"]) + ->provider('p/denied', ['a-denied.txt' => "d\n"]) + ->file('a-denied.txt', "d\n") + ->file('b-gone.txt', "g\n") + ->file('c.txt', "c\n") + ->track('a-denied.txt', 'p/denied') + ->track('b-gone.txt', 'p/a') + ->track('c.txt', 'p/a'); + + $out = new BufferedOutputWriter(); - self::assertStringContainsString( - ' three', - $diff, - 'The third line before the change belongs to the context window.', + Assert::same( + (new DiffService())->run($project->context(), $out), + 1, + "Exit code must stay '1' after an orphan.", ); - self::assertStringNotContainsString( - ' two', - $diff, - 'Lines beyond three of context must be omitted.', + Assert::same( + $out->stdoutBuffer, + ConsoleMessage::DIFF_ORPHAN->getMessage('b-gone.txt') . PHP_EOL + . ConsoleMessage::DIFF_PREVIEW_HEADER->getMessage('c.txt', 'replace', 'p/a', '') . PHP_EOL + . "--- a/c.txt\n+++ b/c.txt\n@@ -1 +1 @@\n-c\n+c2" . PHP_EOL, + 'Files after an orphan must still be diffed.', ); - self::assertStringNotContainsString( - ' ten', - $diff, - 'Trailing lines beyond three of context must be omitted.', + Assert::same( + $out->stderrBuffer, + ConsoleMessage::COMMAND_PROVIDER_NOT_ALLOWED->getMessage('a-denied.txt', 'p/denied') . PHP_EOL, + 'Not-allowed entry must be reported.', ); } - public function testBuildDiffMarksMissingTrailingNewlineWithBackslashMarker(): void + public function allKeepsDiffingAfterAFileThatCannotBeRead(): void { - $diff = (new DiffService())->buildDiff("a\n", "a\nb", 'config/params.php'); + $project = $this->project() + ->provider('p/a', ['a.txt' => "a\n", 'b.txt' => "b2\n"]) + ->file('b.txt', "b\n") + ->track('a.txt', 'p/a') + ->track('b.txt', 'p/a'); - self::assertStringContainsString( - '\\ No newline at end of file', - $diff, - 'A file without a final newline must carry the backslash marker.', - ); - } - - public function testBuildDiffNormalizesCrlfAndLfAsIdentical(): void - { - self::assertSame( - '', - (new DiffService())->buildDiff("line\r\nline2\r\n", "line\nline2\n", 'config/params.php'), - 'Mixed CRLF / LF line endings with identical text content must collapse to an empty diff.', - ); - } + // A directory where the destination file is expected cannot be read as a file. + mkdir("{$this->tempDir}/a.txt"); - public function testBuildDiffPrefixesContextLinesWithSingleSpace(): void - { - $diff = (new DiffService())->buildDiff("shared\nold\n", "shared\nnew\n", 'config/params.php'); + $out = new BufferedOutputWriter(); - self::assertStringContainsString( - "\n shared\n", - $diff, - 'Context lines must be prefixed with a single space.', + Assert::same( + (new DiffService())->run($project->context(), $out), + 1, + "Exit code must be '1' when a file cannot be read.", ); - } - - public function testBuildDiffReturnsEmptyStringForIdenticalContent(): void - { - self::assertSame( - '', - (new DiffService())->buildDiff("line\n", "line\n", 'config/params.php'), - 'Identical contents must produce an empty diff.', + Assert::same( + $out->stdoutBuffer, + ConsoleMessage::DIFF_PREVIEW_HEADER->getMessage('b.txt', 'replace', 'p/a', '') . PHP_EOL + . "--- a/b.txt\n+++ b/b.txt\n@@ -1 +1 @@\n-b\n+b2" . PHP_EOL, + 'Next file must still be diffed.', + ); + Assert::string($out->stderrBuffer)->matchesRegex( + $this->readFailurePattern('a.txt'), + 'Read failure must be the only stderr line.', ); } - public function testBuildDiffShowsAddedLinesWithPlusPrefix(): void + public function appendEditorconfigEvidenceShowsOnlyTheMissingSectionAtTheEnd(): void { - $diff = (new DiffService())->buildDiff("a\n", "a\nadded\n", 'config/params.php'); + $project = $this->seedEvidence('.editorconfig', 'ini/provider.txt', 'ini/consumer-scaffold.txt'); - self::assertStringContainsString( - "\n+added", - $diff, - "Added lines must be prefixed with a single '+'.", - ); - } + $out = new BufferedOutputWriter(); - public function testBuildDiffShowsRemovedLinesWithMinusPrefix(): void - { - $diff = (new DiffService())->buildDiff("a\nremoved\n", "a\n", 'config/params.php'); + (new DiffService()) + ->run($project->context(), $out, '.editorconfig'); - self::assertStringContainsString( - "\n-removed", - $diff, - "Removed lines must be prefixed with a single '-'.", + Assert::same( + $out->stdoutBuffer, + ConsoleMessage::DIFF_PREVIEW_HEADER->getMessage('.editorconfig', 'append', 'php-forge/baseline', '') + . PHP_EOL + . "--- a/.editorconfig\n+++ b/.editorconfig\n@@ -45,3 +45,6 @@ indent_size = 2\n" + . " [LICENSE*]\n indent_style = unset\n indent_size = unset\n+\n+[*.js]\n+indent_size = 2" . PHP_EOL, + "Only the missing '[*.js]' section may be added.", ); } - public function testBuildDiffSplitsDistantChangesIntoSeparateHunks(): void + public function appendGitignoreEvidenceShowsOnlyTheMissingBlock(): void { - $stub = "one\ntwo\nthree\nfour\nfive\nsix\nseven\neight\nnine\nten\neleven\ntwelve\nthirteen\nfourteen\nfifteen\n"; - $current = "one\nchanged\nthree\nfour\nfive\nsix\nseven\neight\nnine\nten\neleven\ntwelve\nthirteen\naltered\nfifteen\n"; + $project = $this->seedEvidence('.gitignore', 'list/provider-v1.txt', 'list/consumer-scaffold.txt'); - $diff = (new DiffService())->buildDiff($stub, $current, 'config/params.php'); + $out = new BufferedOutputWriter(); + + (new DiffService()) + ->run($project->context(), $out, '.gitignore'); - self::assertSame( - 2, - substr_count($diff, '@@ -'), - 'Changes separated by more than the common-line threshold must produce two hunks.', + Assert::same( + $out->stdoutBuffer, + ConsoleMessage::DIFF_PREVIEW_HEADER->getMessage('.gitignore', 'append', 'php-forge/baseline', '') . PHP_EOL + . "--- a/.gitignore\n+++ b/.gitignore\n@@ -56,3 +56,6 @@ Thumbs.db\n .buildpath\n .project\n .settings\n" + . "+\n+# Local AI agent, editor, and GitHub CLI config (if present)\n+.config/gh" . PHP_EOL, + "Only the '.config/gh' block may be added.", ); } - public function testRunAnnouncesNoDifferencesWhenFilesAreIdentical(): void + public function appendSatisfiedReportsNoChanges(): void { - $this->seedProviderAndFile( - destination: 'config/params.php', - sourceContent: "return [];\n", - currentContent: "return [];\n", - ); + $project = $this->project() + ->provider('p/a', ['.gitignore' => "/vendor\n"], ['.gitignore' => 'append']) + ->file('.gitignore', "/my-build\n/vendor\n") + ->track('.gitignore', 'p/a', 'append'); $out = new BufferedOutputWriter(); - $exitCode = (new DiffService())->run( - $this->tempDir, - "{$this->tempDir}/vendor", - 'config/params.php', - $out, - ); - self::assertSame( + Assert::same( + (new DiffService())->run($project->context(), $out, '.gitignore', exitCode: true), 0, - $exitCode, - "When files are identical, the exit code must be '0'.", + "Exit code must be '0' when nothing would change.", ); - self::assertStringContainsString( - 'No differences found', + Assert::same( $out->stdoutBuffer, - 'When files are identical, the output must indicate no differences.', + ConsoleMessage::DIFF_NO_CHANGES->getMessage('.gitignore') . PHP_EOL, + 'No-change line must be the only output.', ); } - public function testRunColorizesDiffWhenDecorated(): void + public function crlfOnlyDifferenceIsReported(): void { - $this->seedProviderAndFile( - destination: 'config/params.php', - sourceContent: "return ['x' => 1];\n", - currentContent: "return ['x' => 2];\n", - ); + $project = $this->project() + ->provider('p/a', ['a.txt' => "a\nb\n"]) + ->file('a.txt', "a\r\nb\r\n") + ->track('a.txt', 'p/a'); $out = new BufferedOutputWriter(); - (new DiffService())->run( - $this->tempDir, - "{$this->tempDir}/vendor", - 'config/params.php', - $out, - decorated: true, - ); - self::assertStringContainsString( - "\e[31m", - $out->stdoutBuffer, - 'Removed lines must carry the red ANSI escape code.', + Assert::same( + (new DiffService())->run($project->context(), $out, 'a.txt', exitCode: true), + 1, + "Exit code must be '1' when line endings would change.", ); - self::assertStringContainsString( - "\e[32m", + Assert::same( $out->stdoutBuffer, - 'Added lines must carry the green ANSI escape code.', + ConsoleMessage::DIFF_LINE_ENDINGS_ONLY->getMessage('a.txt') . PHP_EOL, + 'Line-ending notice must be the only output.', ); } - public function testRunEmitsWarningWhenLockProviderPathEscapesVendor(): void + public function decoratedOutputColorsTheDiffButNotTheHeader(): void { - $this->seedProviderAndFile( - destination: 'config/params.php', - sourceContent: "return [];\n", - currentContent: "return [];\n", - ); - - $lock = new LockFile($this->tempDir); - - $data = $lock->read(); - - $data['providers'] = [ - 'pkg/name' => [ - 'version' => '0.1.x-dev', - 'path' => '../outside-vendor', - ], - ]; - - $lock->write($data); + $project = $this->project() + ->provider('p/a', ['a.txt' => "new\n"]) + ->file('a.txt', "old\n") + ->track('a.txt', 'p/a'); $out = new BufferedOutputWriter(); - $exitCode = (new DiffService())->run( - $this->tempDir, - "{$this->tempDir}/vendor", - 'config/params.php', - $out, - ); - self::assertSame( - 0, - $exitCode, - 'A provider-path warning must be non-fatal: the command falls back to the default root and still succeeds.', - ); - self::assertStringContainsString( - 'resolves outside vendor dir', - $out->stderrBuffer, - 'A lock-recorded provider path outside the vendor directory must emit a warning.', + (new DiffService()) + ->run($project->context(), $out, 'a.txt', true); + + Assert::same( + $out->stdoutBuffer, + ConsoleMessage::DIFF_PREVIEW_HEADER->getMessage('a.txt', 'replace', 'p/a', '') . PHP_EOL + . "\e[1m--- a/a.txt\e[0m\n\e[1m+++ b/a.txt\e[0m\n\e[36m@@ -1 +1 @@\e[0m\n\e[31m-old\e[0m\n\e[32m+new\e[0m" + . PHP_EOL, + 'Only the diff lines must be colored.', ); } - public function testRunEndsCurrentFileReadErrorWithSinglePhpEolSuffixOnStderr(): void + public function ejectedFileIsReportedWithoutDiff(): void { - $this->seedProviderAndFile( - destination: 'config/params.php', - sourceContent: "return [];\n", - currentContent: "return [];\n", - ); + $project = $this->project() + ->provider('p/a', ['a.txt' => "a\n"]) + ->file('a.txt', "mine\n") + ->track('a.txt', 'p/a', extra: ['ejected' => true]); - MockerState::addCondition( - 'PHPForge\\Scaffold\\Services', - 'file_get_contents', - [], - false, - default: true, - ); $out = new BufferedOutputWriter(); - (new DiffService())->run($this->tempDir, "{$this->tempDir}/vendor", 'config/params.php', $out); - self::assertStringEndsWith( - PHP_EOL, - $out->stderrBuffer, - "The 'Could not read current file' error must terminate with PHP_EOL.", + Assert::same( + (new DiffService())->run($project->context(), $out, 'a.txt'), + 0, + "Exit code must be '0' for an ejected file.", ); - self::assertStringStartsNotWith( - PHP_EOL, - $out->stderrBuffer, - "The 'Could not read current file' error must not begin with PHP_EOL.", + Assert::same( + $out->stdoutBuffer, + ConsoleMessage::DIFF_EJECTED->getMessage('a.txt') . PHP_EOL, + 'Ejected line must be the only output.', ); } - public function testRunEndsNoDifferencesMessageWithSinglePhpEolSuffixOnStdout(): void + public function missingDestinationDiffsFromEmpty(): void { - $this->seedProviderAndFile( - destination: 'config/params.php', - sourceContent: "return [];\n", - currentContent: "return [];\n", - ); + $project = $this->project() + ->provider('p/a', ['a.txt' => "a\n"]) + ->file('a.txt', "a\n") + ->track('a.txt', 'p/a') + ->delete('a.txt'); $out = new BufferedOutputWriter(); - (new DiffService())->run($this->tempDir, "{$this->tempDir}/vendor", 'config/params.php', $out); - self::assertStringEndsWith( - PHP_EOL, - $out->stdoutBuffer, - "The 'No differences found' message must end with PHP_EOL so terminals render it on its own line.", - ); - self::assertStringStartsNotWith( - PHP_EOL, + (new DiffService()) + ->run($project->context(), $out, 'a.txt'); + + Assert::same( $out->stdoutBuffer, - "The 'No differences found' message must not be prefixed with PHP_EOL; the newline belongs after it.", + ConsoleMessage::DIFF_PREVIEW_HEADER->getMessage('a.txt', 'replace', 'p/a', '') . PHP_EOL + . "--- a/a.txt\n+++ b/a.txt\n@@ -0,0 +1 @@\n+a" . PHP_EOL, + 'Missing file must diff from empty.', ); } - public function testRunEndsNotTrackedErrorWithSinglePhpEolSuffixOnStderr(): void + public function missingStubAndUnsafeEntriesAreErrors(): void { - (new LockFile($this->tempDir))->write(['providers' => [], 'files' => []]); + $project = $this->project() + ->provider('p/a', ['a.txt' => "a\n"]) + ->file('a.txt', "a\n") + ->track('a.txt', 'p/a') + ->track('../evil', 'p/a') + ->delete('vendor/p/a/stubs/a.txt'); $out = new BufferedOutputWriter(); - (new DiffService())->run($this->tempDir, "{$this->tempDir}/vendor", 'missing.php', $out); - self::assertStringEndsWith( - PHP_EOL, - $out->stderrBuffer, - "The 'not tracked' error must terminate with PHP_EOL so subsequent stderr writes start on a fresh line.", + Assert::same( + (new DiffService())->run($project->context(), $out), + 1, + "Exit code must be '1' when entries fail.", ); - self::assertStringStartsNotWith( - PHP_EOL, + Assert::same( $out->stderrBuffer, - "The 'not tracked' error must not begin with PHP_EOL.", + Message::SCAFFOLD_MANIFEST_LOAD_FAILED->getMessage( + 'p/a', + Message::MANIFEST_COPY_ENTRY_NOT_FOUND->getMessage( + 'stubs/a.txt', + (string) realpath("{$this->tempDir}/vendor/p/a"), + ), + ) . PHP_EOL + . ConsoleMessage::COMMAND_UNSAFE_ENTRY->getMessage( + '../evil', + Message::PATH_TRAVERSAL->getMessage('destination', '../evil'), + ) . PHP_EOL + . ConsoleMessage::DIFF_MANIFEST_NOT_LOADED->getMessage('a.txt', 'p/a') . PHP_EOL, + 'Manifest warning, unsafe entry and skipped entry must be reported in order.', + ); + Assert::same( + $out->stdoutBuffer, + '', + 'Nothing may be diffed.', ); } - public function testRunEndsProviderEscapesVendorWarningWithSinglePhpEolSuffixOnStderr(): void + public function notAllowedProviderIsRejected(): void { - $this->seedProviderAndFile( - destination: 'config/params.php', - sourceContent: "return [];\n", - currentContent: "return [];\n", - ); - - $lock = new LockFile($this->tempDir); - - $data = $lock->read(); - - $data['providers'] = [ - 'pkg/name' => [ - 'version' => '0.1.x-dev', - 'path' => '../outside-vendor', - ], - ]; - - $lock->write($data); + $project = $this->project() + ->provider('p/denied', ['d.txt' => "d\n"]) + ->file('d.txt', "x\n") + ->track('d.txt', 'p/denied'); $out = new BufferedOutputWriter(); - (new DiffService())->run($this->tempDir, "{$this->tempDir}/vendor", 'config/params.php', $out); - self::assertStringEndsWith( - PHP_EOL, - $out->stderrBuffer, - 'The provider-escapes-vendor warning must terminate with PHP_EOL.', + Assert::same( + (new DiffService())->run($project->context(), $out, 'd.txt'), + 1, + "Exit code must be '1' for a rejected entry.", ); - self::assertStringStartsNotWith( - PHP_EOL, + Assert::same( $out->stderrBuffer, - 'The provider-escapes-vendor warning must not begin with PHP_EOL.', + ConsoleMessage::COMMAND_PROVIDER_NOT_ALLOWED->getMessage('d.txt', 'p/denied') . PHP_EOL, + 'Allowlist message must be the only stderr line.', + ); + Assert::same( + $out->stdoutBuffer, + '', + 'Nothing may be diffed.', ); } - public function testRunEndsStubNotFoundErrorWithSinglePhpEolSuffixOnStderr(): void + public function notTrackedFileIsAnError(): void { - $this->seedProviderAndFile( - destination: 'config/params.php', - sourceContent: "return [];\n", - currentContent: "return [];\n", - ); - - unlink($this->tempDir . '/vendor/pkg/name/stubs/config/params.php'); - $out = new BufferedOutputWriter(); - (new DiffService())->run($this->tempDir, "{$this->tempDir}/vendor", 'config/params.php', $out); - self::assertStringEndsWith( - PHP_EOL, - $out->stderrBuffer, - "The 'Stub not found' error must terminate with PHP_EOL.", + Assert::same( + (new DiffService())->run($this->project()->context(), $out, 'nope.txt'), + 1, + "Exit code must be '1' for an untracked file.", ); - self::assertStringStartsNotWith( - PHP_EOL, + Assert::same( $out->stderrBuffer, - "The 'Stub not found' error must not begin with PHP_EOL.", + ConsoleMessage::COMMAND_FILE_NOT_TRACKED->getMessage('nope.txt') . PHP_EOL, + 'Error must be the only stderr line.', + ); + Assert::same( + $out->stdoutBuffer, + '', + 'Nothing may be diffed.', ); } - public function testRunEndsUnsafeLockEntryErrorWithSinglePhpEolSuffixOnStderr(): void + public function prependShowsTheBlockAddedOnTop(): void { - (new LockFile($this->tempDir))->write( - [ - 'providers' => [], - 'files' => [ - '../escape.php' => [ - 'hash' => 'sha256:abc', - 'provider' => 'pkg/name', - 'source' => 'stubs/escape.php', - 'mode' => 'replace', - ], - ], - ], - ); + $project = $this->project() + ->provider('p/a', ['h.php' => " 'prepend']) + ->file('h.php', "echo 1;\n") + ->track('h.php', 'p/a', 'prepend'); $out = new BufferedOutputWriter(); - (new DiffService())->run($this->tempDir, "{$this->tempDir}/vendor", '../escape.php', $out); - self::assertStringEndsWith( - PHP_EOL, - $out->stderrBuffer, - "The 'Unsafe lock entry' error must terminate with PHP_EOL.", - ); - self::assertStringStartsNotWith( - PHP_EOL, - $out->stderrBuffer, - "The 'Unsafe lock entry' error must not begin with PHP_EOL.", + (new DiffService()) + ->run($project->context(), $out, 'h.php'); + + Assert::same( + $out->stdoutBuffer, + ConsoleMessage::DIFF_PREVIEW_HEADER->getMessage('h.php', 'prepend', 'p/a', '') . PHP_EOL + . "--- a/h.php\n+++ b/h.php\n@@ -1 +1,2 @@\n+seedProviderAndFile( - destination: 'config/params.php', - sourceContent: "return [];\n", - currentContent: "return [];\n", - ); + $project = $this->project() + ->provider('p/a', ['ecs.php' => "stub\n"], ['ecs.php' => 'preserve']) + ->file('ecs.php', "mine\n") + ->track('ecs.php', 'p/a', 'preserve'); - MockerState::addCondition( - 'PHPForge\\Scaffold\\Services', - 'file_get_contents', - [], - false, - default: true, - ); $out = new BufferedOutputWriter(); - $exitCode = (new DiffService())->run( - $this->tempDir, - "{$this->tempDir}/vendor", - 'config/params.php', - $out, - ); - self::assertSame( - 1, - $exitCode, - "When the current file cannot be read, the exit code must be '1'.", - ); - self::assertStringContainsString( - 'Could not read current file', - $out->stderrBuffer, - 'When the current file cannot be read, the output must indicate an error.', + (new DiffService()) + ->run($project->context(), $out, 'ecs.php'); + + Assert::same( + $out->stdoutBuffer, + ConsoleMessage::DIFF_PREVIEW_HEADER->getMessage( + 'ecs.php', + 'preserve', + 'p/a', + ConsoleMessage::FRAGMENT_PRESERVE_PREVIEW->getMessage(), + ) . PHP_EOL . "--- a/ecs.php\n+++ b/ecs.php\n@@ -1 +1 @@\n-mine\n+stub" . PHP_EOL, + 'Preserve diff must be labelled.', ); } - public function testRunReturnsErrorWhenFileNotTracked(): void + public function replaceUserModifiedFileGetsSuffix(): void { - (new LockFile($this->tempDir))->write(['providers' => [], 'files' => []]); + $project = $this->project() + ->provider('p/a', ['a.txt' => "stub\n"]) + ->file('a.txt', "stub\n") + ->track('a.txt', 'p/a') + ->file('a.txt', "mine\n"); $out = new BufferedOutputWriter(); - $exitCode = (new DiffService())->run($this->tempDir, "{$this->tempDir}/vendor", 'missing.php', $out); - self::assertSame( + Assert::same( + (new DiffService())->run($project->context(), $out, 'a.txt', exitCode: true), 1, - $exitCode, - "When the file is not tracked, the exit code must be '1'.", + "Exit code must be '1' when a change exists.", ); - self::assertStringContainsString( - 'not tracked', - $out->stderrBuffer, - 'When the file is not tracked, the output must indicate an error.', + Assert::same( + $out->stdoutBuffer, + ConsoleMessage::DIFF_PREVIEW_HEADER->getMessage( + 'a.txt', + 'replace', + 'p/a', + ConsoleMessage::FRAGMENT_USER_MODIFIED_PREVIEW->getMessage(), + ) . PHP_EOL . "--- a/a.txt\n+++ b/a.txt\n@@ -1 +1 @@\n-mine\n+stub" . PHP_EOL, + 'User-modified suffix must be shown.', ); } - public function testRunReturnsErrorWhenLockEntryHasUnsafeDestination(): void + public function unloadableManifestIsWarnedAndIsAnError(): void { - (new LockFile($this->tempDir))->write( - [ - 'providers' => [], - 'files' => [ - '../escape.php' => [ - 'hash' => 'sha256:abc', - 'provider' => 'pkg/name', - 'source' => 'stubs/escape.php', - 'mode' => 'replace', - ], - ], - ], - ); + $project = $this->project() + ->provider('p/a', ['a.txt' => "a\n"]) + ->file('a.txt', "a\n") + ->track('a.txt', 'p/a') + ->file('vendor/p/a/composer.json', '{"extra": {"scaffold": {"copy": []}}}'); $out = new BufferedOutputWriter(); - $exitCode = (new DiffService())->run( - $this->tempDir, - "{$this->tempDir}/vendor", - '../escape.php', - $out, - ); - self::assertSame( + Assert::same( + (new DiffService())->run($project->context(), $out, 'a.txt'), 1, - $exitCode, - "When the lock entry is unsafe, the exit code must be '1'.", + "Exit code must be '1' when the manifest cannot be loaded.", ); - self::assertStringContainsString( - 'Unsafe lock entry', + Assert::same( $out->stderrBuffer, - 'When the lock entry is unsafe, the output must indicate an error.', + Message::SCAFFOLD_MANIFEST_LOAD_FAILED->getMessage('p/a', Message::MANIFEST_COPY_EMPTY->getMessage()) + . PHP_EOL + . ConsoleMessage::DIFF_MANIFEST_NOT_LOADED->getMessage('a.txt', 'p/a') . PHP_EOL, + 'Manifest warning must precede the entry error.', ); } - public function testRunReturnsErrorWhenStubMissing(): void + public function unreadableDestinationIsAnErrorAndOtherFilesAreIgnored(): void { - $this->seedProviderAndFile( - destination: 'config/params.php', - sourceContent: "return [];\n", - currentContent: "return [];\n", - ); + $project = $this->project() + ->provider('p/a', ['a.txt' => "a\n", 'b.txt' => "b\n"]) + ->file('a.txt', "a\n") + ->track('a.txt', 'p/a') + ->track('b.txt', 'p/a'); - unlink($this->tempDir . '/vendor/pkg/name/stubs/config/params.php'); + // A directory where the destination file is expected cannot be read as a file. + mkdir("{$this->tempDir}/b.txt"); $out = new BufferedOutputWriter(); - $exitCode = (new DiffService())->run( - $this->tempDir, - "{$this->tempDir}/vendor", - 'config/params.php', - $out, - ); - self::assertSame( + Assert::same( + (new DiffService())->run($project->context(), $out, 'b.txt'), 1, - $exitCode, - "When the stub is missing, the exit code must be '1'.", + "Exit code must be '1' when the file cannot be read.", ); - self::assertStringContainsString( - 'Stub not found', - $out->stderrBuffer, - 'When the stub is missing, the output must indicate an error.', + Assert::same( + $out->stdoutBuffer, + '', + 'Other files must not be diffed.', + ); + Assert::string($out->stderrBuffer)->matchesRegex( + $this->readFailurePattern('b.txt'), + 'Read failure must be reported with its reason.', ); } - public function testRunReturnsUnsafeDestinationErrorEvenWhenProviderRootAndSourceAreSafe(): void + public function unsafeStubSymlinkIsAnError(): void { - // Valid provider tree so 'validateSource' passes unconditionally; isolates the 'validateDestination' guard. - $providerRoot = "{$this->tempDir}/vendor/pkg/name"; - - $this->ensureTestDirectory("{$providerRoot}/stubs"); - - file_put_contents("{$providerRoot}/stubs/safe.php", "return [];\n"); - - (new LockFile($this->tempDir))->write( - [ - 'providers' => [ - 'pkg/name' => [ - 'version' => '0.1.x-dev', - 'path' => 'vendor/pkg/name', - ], - ], - 'files' => [ - '../escape.php' => [ - 'hash' => 'sha256:abc', - 'provider' => 'pkg/name', - 'source' => 'stubs/safe.php', - 'mode' => 'replace', - ], - ], - ], - ); + $project = $this->project() + ->provider('p/a', ['a.txt' => "a\n"]) + ->file('a.txt', "a\n") + ->track('a.txt', 'p/a') + ->file('outside.txt', "outside\n"); - $out = new BufferedOutputWriter(); - $exitCode = (new DiffService())->run( - $this->tempDir, - "{$this->tempDir}/vendor", - '../escape.php', - $out, - ); - - self::assertSame( - 1, - $exitCode, - "When 'validateDestination' flags an unsafe destination, the exit code must be '1'.", - ); - self::assertStringContainsString( - 'Unsafe lock entry', - $out->stderrBuffer, - "'validateDestination' must catch the traversal destination and emit the 'Unsafe lock entry' diagnostic.", - ); - } + unlink("{$this->tempDir}/vendor/p/a/stubs/a.txt"); - public function testRunReturnsUnsafeSourceErrorEvenWhenDestinationIsSafe(): void - { - // Safe destination + unsafe source so 'validateDestination' passes; isolates the 'validateSource' guard. - $providerRoot = "{$this->tempDir}/vendor/pkg/name"; - - $this->ensureTestDirectory($providerRoot); - $this->ensureTestDirectory("{$this->tempDir}/config"); - - file_put_contents("{$this->tempDir}/config/params.php", "return [];\n"); - - (new LockFile($this->tempDir))->write( - [ - 'providers' => [ - 'pkg/name' => [ - 'version' => '0.1.x-dev', - 'path' => 'vendor/pkg/name', - ], - ], - 'files' => [ - 'config/params.php' => [ - 'hash' => 'sha256:abc', - 'provider' => 'pkg/name', - 'source' => '../escape.php', - 'mode' => 'replace', - ], - ], - ], - ); + if (@symlink("{$this->tempDir}/outside.txt", "{$this->tempDir}/vendor/p/a/stubs/a.txt") === false) { + throw new SkipTest('Symbolic links are not available.'); + } $out = new BufferedOutputWriter(); - $exitCode = (new DiffService())->run( - $this->tempDir, - "{$this->tempDir}/vendor", - 'config/params.php', - $out, - ); - self::assertSame( + Assert::same( + (new DiffService())->run($project->context(), $out, 'a.txt'), 1, - $exitCode, - "When 'validateSource' flags an unsafe source, the exit code must be '1'.", + "Exit code must be '1' for an escaping stub.", ); - self::assertStringContainsString( - 'Unsafe lock entry', + Assert::same( + $out->stdoutBuffer, + '', + 'Nothing may be diffed.', + ); + Assert::same( $out->stderrBuffer, - "'validateSource' must catch the traversal source and emit the 'Unsafe lock entry' diagnostic.", + ConsoleMessage::COMMAND_UNSAFE_ENTRY->getMessage( + 'a.txt', + Message::PATH_SYMLINK_ESCAPE->getMessage('Source', 'stubs/a.txt'), + ) . PHP_EOL, + 'Unsafe source must be the only stderr line.', ); } - - public function testRunShowsFullStubAsRemovedWhenDestinationIsAbsent(): void + public function wouldBeCreatedEmptyIsReported(): void { - $this->seedProviderAndFile( - destination: 'config/params.php', - sourceContent: "return ['x' => 1];\n", - currentContent: "return ['x' => 1];\n", - ); - - unlink($this->tempDir . '/config/params.php'); + $project = $this->project() + ->provider('p/a', ['empty.txt' => '']) + ->track('empty.txt', 'p/a'); $out = new BufferedOutputWriter(); - $exitCode = (new DiffService())->run( - $this->tempDir, - "{$this->tempDir}/vendor", - 'config/params.php', - $out, - ); - self::assertSame( - 0, - $exitCode, - "When the destination is absent, the exit code must be '0'.", - ); - self::assertStringContainsString( - "-return ['x' => 1];", - $out->stdoutBuffer, - 'When the destination is absent, the output must indicate the full stub as removed.', + Assert::same( + (new DiffService())->run($project->context(), $out, 'empty.txt', exitCode: true), + 1, + "Exit code must be '1': creating an empty file is a change.", ); - self::assertStringContainsString( - '@@ -1 +1,0 @@', + Assert::same( $out->stdoutBuffer, - 'An absent destination must render as an empty-target hunk.', + ConsoleMessage::DIFF_PREVIEW_HEADER->getMessage('empty.txt', 'replace', 'p/a', '') . PHP_EOL + . ConsoleMessage::DIFF_CREATED_EMPTY->getMessage('empty.txt') . PHP_EOL, + 'Empty file creation must be reported.', ); } - public function testRunWritesPlainDiffWhenNotDecorated(): void + /** + * Returns the builder of the temporary project, with `p/a` and `php-forge/baseline` allowed. + */ + private function project(): InspectionProject { - $this->seedProviderAndFile( - destination: 'config/params.php', - sourceContent: "return ['x' => 1];\n", - currentContent: "return ['x' => 2];\n", - ); - - $out = new BufferedOutputWriter(); - (new DiffService())->run( - $this->tempDir, - "{$this->tempDir}/vendor", - 'config/params.php', - $out, - ); - - self::assertStringNotContainsString( - "\e[", - $out->stdoutBuffer, - 'Undecorated output must contain no ANSI escape codes.', - ); + return (new InspectionProject($this->tempDir))->composer(['p/a', 'php-forge/baseline']); } - protected function setUp(): void + /** + * Returns the pattern of the only stderr line reporting that `$destination`, a directory, cannot be read. + * + * The PHP notice depends on the filesystem and the platform, so only its function name is matched. + */ + private function readFailurePattern(string $destination): string { - $this->setUpTempDirectory(); - } + $prefix = ConsoleMessage::COMMAND_FILE_ERROR->getMessage( + $destination, + Message::SERVICE_CURRENT_FILE_UNREADABLE->getMessage(PathResolver::destination($this->tempDir, $destination)) + . ' Reason: file_get_contents(', + ); - protected function tearDown(): void - { - $this->tearDownTempDirectory(); + return '/\A' . preg_quote($prefix, '/') . '.+\R\z/'; } /** - * Helper method to seed a provider and file for testing. - * - * @param string $destination Relative destination path within the project. - * @param string $sourceContent Content to write to the source file. - * @param string $currentContent Content to write to the current file. + * Tracks an `append` file built from the owner's merge evidence fixtures. */ - private function seedProviderAndFile(string $destination, string $sourceContent, string $currentContent): void + private function seedEvidence(string $destination, string $provider, string $consumer): InspectionProject { - $providerRoot = "{$this->tempDir}/vendor/pkg/name"; - - $stubRelative = "stubs/{$destination}"; - $stubPath = "{$providerRoot}/{$stubRelative}"; - - $this->ensureTestDirectory(dirname($stubPath)); - - file_put_contents($stubPath, $sourceContent); - - $destAbsolute = "{$this->tempDir}/{$destination}"; - - $this->ensureTestDirectory(dirname($destAbsolute)); - - file_put_contents($destAbsolute, $currentContent); - - $hash = (new Hasher())->hash($destAbsolute); - (new LockFile($this->tempDir))->write( - [ - 'providers' => [ - 'pkg/name' => [ - 'version' => '0.1.x-dev', - 'path' => 'vendor/pkg/name', - ], - ], - 'files' => [ - $destination => [ - 'hash' => $hash, - 'provider' => 'pkg/name', - 'source' => $stubRelative, - 'mode' => 'replace', - ], - ], - ], - ); + $fixtures = dirname(__DIR__) . '/Fixtures/merge'; + + return $this->project() + ->provider( + 'php-forge/baseline', + [$destination => (string) file_get_contents("{$fixtures}/{$provider}")], + [$destination => 'append'], + ) + ->file($destination, (string) file_get_contents("{$fixtures}/{$consumer}")) + ->track($destination, 'php-forge/baseline', 'append'); } } diff --git a/tests/Services/EjectServiceTest.php b/tests/Services/EjectServiceTest.php index 1bb33f8..db41b2b 100644 --- a/tests/Services/EjectServiceTest.php +++ b/tests/Services/EjectServiceTest.php @@ -4,181 +4,135 @@ namespace PHPForge\Scaffold\Tests\Services; -use PHPForge\Scaffold\Scaffold\Lock\LockFile; +use PHPForge\Scaffold\Console\Message; use PHPForge\Scaffold\Services\EjectService; -use PHPForge\Scaffold\Tests\Support\{BufferedOutputWriter, TempDirectoryTrait}; -use PHPUnit\Framework\Attributes\Group; -use PHPUnit\Framework\TestCase; +use PHPForge\Scaffold\Tests\Support\{BufferedOutputWriter, FileAssert, InspectionProject, TempDirectoryTrait}; +use Testo\Assert; +use Testo\Codecov\Covers; +use Testo\Data\DataSet; +use Testo\Test; + +use function file_get_contents; /** - * Unit tests for {@see EjectService} covering dry-run, confirmed removal, and untracked-file error paths. + * Unit tests for {@see EjectService} covering dry-run, confirmed ejection, and untracked-file error paths. */ -#[Group('scaffold')] -#[Group('services')] -final class EjectServiceTest extends TestCase +#[Test] +#[Covers(EjectService::class)] +final class EjectServiceTest { use TempDirectoryTrait; - public function testConfirmedEjectSuccessMessageEndsWithSinglePhpEolSuffix(): void + #[DataSet([false], 'preview')] + #[DataSet([true], 'confirmed')] + public function alreadyEjectedEntryReportsOnlyItsState(bool $confirmed): void { - $this->seedTracked('config/params.php'); - - file_put_contents("{$this->tempDir}/config/params.php", "return [];\n"); + (new InspectionProject($this->tempDir)) + ->track('config/params.php', 'pkg/name', extra: ['ejected' => true]); - $out = new BufferedOutputWriter(); - (new EjectService())->run($this->tempDir, 'config/params.php', confirmed: true, out: $out); - - self::assertStringEndsWith( - PHP_EOL, - $out->stdoutBuffer, - "The 'Removed' confirmation must end with PHP_EOL so shells render it on its own line.", + $before = file_get_contents( + "{$this->tempDir}/scaffold-lock.json", ); - self::assertStringStartsNotWith( - PHP_EOL, - $out->stdoutBuffer, - "The 'Removed' confirmation must not be prefixed with PHP_EOL.", - ); - } - - public function testDryRunLeavesLockUntouchedWithoutConfirmation(): void - { - $this->seedTracked('config/params.php'); $out = new BufferedOutputWriter(); - $exitCode = (new EjectService())->run($this->tempDir, 'config/params.php', confirmed: false, out: $out); - self::assertSame( + Assert::same( + (new EjectService())->run($this->tempDir, $out, 'config/params.php', $confirmed), 0, - $exitCode, - "Dry-run should exit with code '0' to indicate no error.", + "Exit code must be '0' for an entry that is already ejected.", ); - self::assertStringContainsString( - 'Would remove', + Assert::same( $out->stdoutBuffer, - 'Dry-run must indicate which files would be removed.', + Message::EJECT_ALREADY_EJECTED->getMessage('config/params.php') . PHP_EOL, + 'State line must be the only output.', ); - - $data = (new LockFile($this->tempDir))->read(); - - self::assertArrayHasKey( - 'config/params.php', - $data['files'], - 'File must remain tracked in the lock file during a dry-run.', + Assert::same( + file_get_contents("{$this->tempDir}/scaffold-lock.json"), + $before, + 'Lock must not be rewritten.', ); } - public function testDryRunMessageEndsWithSinglePhpEolSuffix(): void + public function confirmedEjectMarksTheEntryAndKeepsTheFile(): void { - $this->seedTracked('config/params.php'); + $project = (new InspectionProject($this->tempDir)) + ->file('config/params.php', "return [];\n") + ->track('config/params.php', 'pkg/name'); $out = new BufferedOutputWriter(); - (new EjectService())->run($this->tempDir, 'config/params.php', confirmed: false, out: $out); - self::assertStringEndsWith( - PHP_EOL, - $out->stdoutBuffer, - "The dry-run 'Would remove' message must end with PHP_EOL.", + Assert::same( + (new EjectService())->run($this->tempDir, $out, 'config/params.php', true), + 0, + "Exit code must be '0' when the eject is confirmed.", ); - self::assertStringStartsNotWith( - PHP_EOL, + Assert::same( $out->stdoutBuffer, - "The dry-run 'Would remove' message must not be prefixed with PHP_EOL.", + Message::EJECT_EJECTED->getMessage('config/params.php') . PHP_EOL, + 'Confirmation must be the only output.', + ); + Assert::same( + $project->lock()->read()['files']['config/params.php']['ejected'] ?? null, + true, + "Entry must be kept and marked 'ejected'.", + ); + FileAssert::contentSame( + "{$this->tempDir}/config/params.php", + "return [];\n", + 'Eject must never touch the file on disk.', ); } - public function testEjectRemovesEntryAndPreservesFileOnDiskWhenConfirmed(): void + public function previewPrintsTheHintAndLeavesTheLockUntouched(): void { - $this->seedTracked('config/params.php'); + (new InspectionProject($this->tempDir)) + ->track('config/params.php', 'pkg/name'); - file_put_contents("{$this->tempDir}/config/params.php", "return [];\n"); + $before = file_get_contents( + "{$this->tempDir}/scaffold-lock.json", + ); $out = new BufferedOutputWriter(); - $exitCode = (new EjectService())->run($this->tempDir, 'config/params.php', confirmed: true, out: $out); - self::assertSame( + Assert::same( + (new EjectService())->run($this->tempDir, $out, 'config/params.php'), 0, - $exitCode, - "When the eject is confirmed, the exit code must be '0'.", + "Exit code of a preview must be '0'.", ); - self::assertStringContainsString( - 'Removed', + Assert::same( $out->stdoutBuffer, - 'When the eject is confirmed, the output must indicate the removal.', + Message::EJECT_CONFIRMATION_REQUIRED->getMessage('config/params.php') . PHP_EOL, + 'Preview must be the only output.', ); - - $data = (new LockFile($this->tempDir))->read(); - - self::assertArrayNotHasKey( - 'config/params.php', - $data['files'], - 'File must no longer be tracked in the lock file after confirmed eject.', - ); - self::assertFileExists( - "{$this->tempDir}/config/params.php", - 'Eject must never delete the on-disk file.', + Assert::same( + file_get_contents("{$this->tempDir}/scaffold-lock.json"), + $before, + 'Preview must not rewrite the lock.', ); } - public function testReturnsErrorWhenFileIsNotTracked(): void + public function untrackedFileIsAnError(): void { - (new LockFile($this->tempDir))->write(['providers' => [], 'files' => []]); + (new InspectionProject($this->tempDir)) + ->lock() + ->write(['providers' => [], 'files' => []]); $out = new BufferedOutputWriter(); - $exitCode = (new EjectService())->run($this->tempDir, 'missing.php', confirmed: true, out: $out); - self::assertSame( + Assert::same( + (new EjectService())->run($this->tempDir, $out, 'missing.php', true), 1, - $exitCode, - "When the file is not tracked, the exit code must be '1'.", - ); - self::assertStringContainsString( - 'not tracked', - $out->stderrBuffer, - 'When the file is not tracked, the output must indicate the error.', + "Exit code must be '1' when the file is not tracked.", ); - self::assertStringEndsWith( - PHP_EOL, + Assert::same( $out->stderrBuffer, - "The 'not tracked' stderr message must end with PHP_EOL so subsequent stderr writes start on a fresh line.", + Message::COMMAND_FILE_NOT_TRACKED->getMessage('missing.php') . PHP_EOL, + 'Error must be the only stderr line.', ); - self::assertStringStartsNotWith( - PHP_EOL, - $out->stderrBuffer, - "The 'not tracked' stderr message must not begin with PHP_EOL.", - ); - } - - protected function setUp(): void - { - $this->setUpTempDirectory(); - } - - protected function tearDown(): void - { - $this->tearDownTempDirectory(); - } - - /** - * Seeds the lock file with a tracked file and ensures the test directory exists. - * - * @param string $destination Path of the file to track, relative to the project root. - */ - private function seedTracked(string $destination): void - { - (new LockFile($this->tempDir))->write( - [ - 'providers' => [], - 'files' => [ - $destination => [ - 'hash' => 'sha256:abc', - 'provider' => 'pkg/name', - 'source' => "stubs/{$destination}", - 'mode' => 'replace', - ], - ], - ], + Assert::same( + $out->stdoutBuffer, + '', + 'Nothing may be written to stdout.', ); - - $this->ensureTestDirectory(dirname("{$this->tempDir}/{$destination}")); } } diff --git a/tests/Services/FileStatusTest.php b/tests/Services/FileStatusTest.php new file mode 100644 index 0000000..17d63bf --- /dev/null +++ b/tests/Services/FileStatusTest.php @@ -0,0 +1,42 @@ + $providers Provider versions keyed by name. + * @param array $files Provider names keyed by tracked destination. + * @param array $expected Expected file counts keyed by provider. + */ + #[DataProvider(ProvidersServiceProvider::class . '::counts')] + public function countsTheFilesOfEveryProvider(array $providers, array $files, array $expected): void { - (new LockFile($this->tempDir))->write( - [ - 'providers' => [], - 'files' => [ - 'a.txt' => [ - 'hash' => 'sha256:a', - 'provider' => 'pkg/a', - 'source' => 'stubs/a.txt', - 'mode' => 'replace', - ], - 'b.txt' => [ - 'hash' => 'sha256:b', - 'provider' => 'pkg/a', - 'source' => 'stubs/b.txt', - 'mode' => 'replace', - ], - 'c.txt' => [ - 'hash' => 'sha256:c', - 'provider' => 'pkg/b', - 'source' => 'stubs/c.txt', - 'mode' => 'preserve', - ], - ], - ], - ); + $this->writeLock($providers, $files); - self::assertSame( - ['pkg/a' => 2, 'pkg/b' => 1], + Assert::same( (new ProvidersService())->getProviders($this->tempDir), - "File counts must aggregate per 'provider' key.", - ); - } - - public function testGetProvidersIncludesProvidersWithZeroFilesFromLockMetadata(): void - { - (new LockFile($this->tempDir))->write( - [ - 'providers' => [ - 'pkg/with-files' => [ - 'version' => '0.1.0', - 'path' => 'vendor/pkg/with-files', - ], - 'pkg/zero-files' => [ - 'version' => '0.1.0', - 'path' => 'vendor/pkg/zero-files', - ], - ], - 'files' => [ - 'a.txt' => [ - 'hash' => 'sha256:a', - 'provider' => 'pkg/with-files', - 'source' => 'stubs/a.txt', - 'mode' => 'replace', - ], - ], - ], - ); - - self::assertSame( - ['pkg/with-files' => 1, 'pkg/zero-files' => 0], - (new ProvidersService())->getProviders($this->tempDir), - "Providers recorded in the lock's top-level metadata must appear with count '0' when they have no files.", - ); - } - - public function testRunEmptyProvidersMessageEndsWithSinglePhpEolSuffix(): void - { - (new LockFile($this->tempDir))->write(['providers' => [], 'files' => []]); - - $out = new BufferedOutputWriter(); - (new ProvidersService())->run($this->tempDir, $out); - - self::assertStringEndsWith( - PHP_EOL, - $out->stdoutBuffer, - "The 'No providers tracked' message must end with PHP_EOL so shells render it on its own line.", - ); - self::assertStringEndsNotWith( - PHP_EOL . PHP_EOL, - $out->stdoutBuffer, - "The 'No providers tracked' message must end with exactly one PHP_EOL.", - ); - self::assertStringStartsNotWith( - PHP_EOL, - $out->stdoutBuffer, - "The 'No providers tracked' message must not be prefixed with PHP_EOL.", + $expected, + 'File counts must aggregate per provider.', ); } - public function testRunPrintsEmptyMessageWhenNoProvidersTracked(): void + /** + * @param array $providers Provider versions keyed by name. + * @param array $files Provider names keyed by tracked destination. + */ + #[DataProvider(ProvidersServiceProvider::class . '::tables')] + public function rendersTheProvidersTable(array $providers, array $files, string $expected): void { - (new LockFile($this->tempDir))->write(['providers' => [], 'files' => []]); + $this->writeLock($providers, $files); $out = new BufferedOutputWriter(); - $exitCode = (new ProvidersService())->run($this->tempDir, $out); - self::assertSame( + Assert::same( + (new ProvidersService())->run($this->tempDir, $out), 0, - $exitCode, - "Exit code must be '0' when no providers are tracked, indicating successful execution with empty state.", - ); - self::assertStringContainsString( - 'No providers tracked in scaffold-lock.json', - $out->stdoutBuffer, - 'When no providers are tracked, the output must indicate the empty state.', + "Exit code must be '0'.", ); - self::assertStringNotContainsString( - 'Files', + Assert::same( $out->stdoutBuffer, - "When the providers map is empty, the service must 'return' before rendering the 'Provider Files' header.", + $expected, + 'Table must be the only output.', ); - self::assertStringNotContainsString( - str_repeat('-', 52), - $out->stdoutBuffer, - 'When the providers map is empty, the service must return before rendering the 52-dash separator.', - ); - } - - public function testRunRendersHeaderAndRowsWhenProvidersExist(): void - { - (new LockFile($this->tempDir))->write( - [ - 'providers' => [], - 'files' => [ - 'a.txt' => [ - 'hash' => 'sha256:a', - 'provider' => 'pkg/a', - 'source' => 'stubs/a.txt', - 'mode' => 'replace', - ], - ], - ], - ); - - $out = new BufferedOutputWriter(); - $exitCode = (new ProvidersService())->run($this->tempDir, $out); - - self::assertSame( - 0, - $exitCode, - "Exit code must be '0' when providers exist, indicating successful execution.", - ); - self::assertStringContainsString( - 'Provider', - $out->stdoutBuffer, - "Output must include the 'Provider' header.", + Assert::same( + $out->stderrBuffer, + '', + 'Nothing may be written to stderr.', ); - self::assertStringContainsString( - 'Files', - $out->stdoutBuffer, - "Output must include the 'Files' header.", - ); - self::assertStringContainsString( - 'pkg/a', - $out->stdoutBuffer, - "Output must include the provider 'pkg/a'.", - ); - } - - public function testRunSeparatorRowIsExactly52DashesFollowedByPhpEol(): void - { - (new LockFile($this->tempDir))->write( - [ - 'providers' => [], - 'files' => [ - 'a.txt' => [ - 'hash' => 'sha256:a', - 'provider' => 'pkg/a', - 'source' => 'stubs/a.txt', - 'mode' => 'replace', - ], - ], - ], - ); - - $out = new BufferedOutputWriter(); - (new ProvidersService())->run($this->tempDir, $out); - - self::assertStringContainsString( - PHP_EOL . str_repeat('-', 52) . PHP_EOL, - $out->stdoutBuffer, - 'The horizontal separator row must be exactly 52 dashes on its own line.', - ); - self::assertStringNotContainsString( - str_repeat('-', 53), - $out->stdoutBuffer, - 'The separator must not contain 53 consecutive dashes.', - ); - } - - public function testRunTableOutputEndsWithSinglePhpEolSuffix(): void - { - (new LockFile($this->tempDir))->write( - [ - 'providers' => [], - 'files' => [ - 'a.txt' => [ - 'hash' => 'sha256:a', - 'provider' => 'pkg/a', - 'source' => 'stubs/a.txt', - 'mode' => 'replace', - ], - ], - ], - ); - - $out = new BufferedOutputWriter(); - (new ProvidersService())->run($this->tempDir, $out); - - self::assertStringEndsWith( - PHP_EOL, - $out->stdoutBuffer, - 'The rendered providers table must end with PHP_EOL so the final row is on its own terminal line.', - ); - self::assertStringEndsNotWith( - PHP_EOL . PHP_EOL, - $out->stdoutBuffer, - 'The rendered providers table must end with exactly one PHP_EOL.', - ); - self::assertStringStartsWith( - 'Provider', - $out->stdoutBuffer, - "The rendered providers table must start with the 'Provider' header (not a stray PHP_EOL).", - ); - self::assertStringContainsString( - 'pkg/a' . str_repeat(' ', 44 - strlen('pkg/a')) . ' 1' . PHP_EOL, - $out->stdoutBuffer, - 'The provider row must end with one PHP_EOL; the provider name must be left-padded to 44 chars.', - ); - } - - protected function setUp(): void - { - $this->setUpTempDirectory(); } - protected function tearDown(): void + /** + * Writes a lock with the given providers and `replace` entries. + * + * @param array $providers Provider versions keyed by name. + * @param array $files Provider names keyed by tracked destination. + */ + private function writeLock(array $providers, array $files): void { - $this->tearDownTempDirectory(); + $data = ['providers' => [], 'files' => []]; + + foreach ($providers as $name => $version) { + $data['providers'][$name] = ['version' => $version, 'path' => "vendor/{$name}"]; + } + + foreach ($files as $destination => $provider) { + $data['files'][$destination] = [ + 'hash' => 'sha256:abc', + 'provider' => $provider, + 'source' => "stubs/{$destination}", + 'mode' => 'replace', + ]; + } + + (new LockFile($this->tempDir))->write($data); } } diff --git a/tests/Services/PruneServiceTest.php b/tests/Services/PruneServiceTest.php new file mode 100644 index 0000000..cecdd82 --- /dev/null +++ b/tests/Services/PruneServiceTest.php @@ -0,0 +1,684 @@ +seedOrphans(); + + $out = new BufferedOutputWriter(); + + Assert::same( + (new PruneService())->run($project->context(), $out, true, true), + 0, + "Exit code must be '0'.", + ); + Assert::same( + $out->stdoutBuffer, + implode( + PHP_EOL, + [ + ConsoleMessage::PRUNE_DELETED->getMessage( + '.gitignore', + ConsoleMessage::FRAGMENT_PARENTHESIZED->getMessage('merged'), + ), + ConsoleMessage::PRUNE_DELETED->getMessage( + 'edited.txt', + ConsoleMessage::FRAGMENT_PARENTHESIZED->getMessage('modified'), + ), + ConsoleMessage::PRUNE_DELETED->getMessage('gone/deep/old.txt', ''), + ConsoleMessage::PRUNE_DELETED->getMessage('legacy.txt', ''), + ConsoleMessage::PRUNE_ENTRY_DROPPED->getMessage('missing.txt', 'missing'), + ConsoleMessage::PRUNE_SUMMARY->getMessage(5, 0, 0, ConsoleMessage::FRAGMENT_ERRORS->getMessage()), + '', + ], + ), + 'Every orphan must be deleted and counted as removed.', + ); + FileAssert::fileDoesNotExist( + "{$this->tempDir}/edited.txt", + 'Modified orphan must be deleted.', + ); + FileAssert::fileDoesNotExist( + "{$this->tempDir}/.gitignore", + 'Merged orphan must be deleted.', + ); + } + + public function dryRunListsIntegerLikeAndUnsafeOrphansWithMinimumColumnWidths(): void + { + $project = (new InspectionProject($this->tempDir)) + ->composer(['p/a']) + ->installed(['p/a' => '1.0.0']) + ->provider('p/a', ['kept.txt' => "kept\n"]) + ->file('1', "one\n") + ->track('1', 'p/a') + ->track('/x', 'p/a'); + + $out = new BufferedOutputWriter(); + + Assert::same( + (new PruneService())->run($project->context(), $out), + 0, + "Exit code of a preview must be '0'.", + ); + Assert::same( + $out->stdoutBuffer, + implode( + PHP_EOL, + [ + 'File Provider Disk With --force', + '----------------------------------------', + '/x p/a unsafe drop entry', + '1 p/a unmodified delete', + ConsoleMessage::PRUNE_DRY_RUN_SUMMARY->getMessage( + 2, + 0, + 0, + ConsoleMessage::FRAGMENT_ERRORS->getMessage(), + ), + '', + ], + ), + 'File column must keep its minimum width.', + ); + } + + public function dryRunListsOrphansWithoutTouchingAnything(): void + { + $project = $this->seedOrphans(); + $before = file_get_contents("{$this->tempDir}/scaffold-lock.json"); + $out = new BufferedOutputWriter(); + + Assert::same( + (new PruneService())->run($project->context(), $out), + 0, + "Exit code of a preview must be '0'.", + ); + Assert::same( + $out->stdoutBuffer, + self::orphanTable( + ConsoleMessage::PRUNE_DRY_RUN_SUMMARY->getMessage(3, 2, 0, ConsoleMessage::FRAGMENT_ERRORS->getMessage()), + ), + 'Preview table must list every orphan.', + ); + Assert::same( + $out->stderrBuffer, + '', + 'No warning expected.', + ); + Assert::same( + file_get_contents("{$this->tempDir}/scaffold-lock.json"), + $before, + 'Lock must stay untouched.', + ); + FileAssert::fileExists("{$this->tempDir}/gone/deep/old.txt", 'Files must stay on disk.'); + } + + public function dryRunSummaryUsesTheSingularForOneError(): void + { + $project = $this->seedOrphans() + ->composer(['p/a', 'p/broken']) + ->installed(['p/a' => '1.0.0', 'p/old' => '1.0.0', 'p/broken' => '1.0.0']) + ->file('vendor/p/broken/composer.json', '{broken'); + + $out = new BufferedOutputWriter(); + + Assert::same( + (new PruneService())->run($project->context(), $out), + 1, + "Exit code must be '1' for a broken manifest.", + ); + Assert::same( + $out->stdoutBuffer, + self::orphanTable( + ConsoleMessage::PRUNE_DRY_RUN_SUMMARY->getMessage(3, 2, 1, ConsoleMessage::FRAGMENT_ERROR->getMessage()), + ), + 'One error must use the singular.', + ); + } + + public function exitCodeReportsOrphansInPreview(): void + { + Assert::same( + (new PruneService())->run($this->seedOrphans()->context(), new BufferedOutputWriter(), exitCode: true), + 1, + "Exit code must be '1' for orphans with '--exit-code'.", + ); + } + + public function failedDeletionIsReportedAndKeepsTheEntry(): void + { + $project = $this->seedOrphans(); + + $this->restrictFileAccess("{$this->tempDir}/gone/deep", 0o555); + + $out = new BufferedOutputWriter(); + + error_clear_last(); + + try { + $exitCode = (new PruneService()) + ->run($project->context(), $out, true); + } finally { + chmod("{$this->tempDir}/gone/deep", 0o755); + } + + Assert::null( + error_get_last(), + 'The failure must be captured, not raised.', + ); + Assert::same( + $exitCode, + 1, + "Exit code must be '1' for an I/O failure.", + ); + Assert::same( + $out->stderrBuffer, + Message::FILESYSTEM_FAILED->getMessage( + ConsoleMessage::PRUNE_FILE_DELETE_FAILED->getMessage("{$this->tempDir}/gone/deep/old.txt"), + "unlink({$this->tempDir}/gone/deep/old.txt): Permission denied", + ) . PHP_EOL, + 'Failure must be reported with its reason.', + ); + Assert::true( + array_key_exists('gone/deep/old.txt', $project->lock()->read()['files']), + 'Entry of an undeleted file must stay.', + ); + Assert::string($out->stdoutBuffer)->endsWith( + ConsoleMessage::PRUNE_SUMMARY->getMessage(2, 2, 1, ConsoleMessage::FRAGMENT_ERROR->getMessage()) . PHP_EOL, + 'Summary must count the error.', + ); + } + + public function failedDirectoryRemovalIsReportedAfterTheFileIsDeleted(): void + { + $project = $this->seedOrphans(); + + // 'gone/deep' stays writable, so its file is deleted, but 'gone' blocks the removal of the empty 'gone/deep'. + $this->restrictFileAccess("{$this->tempDir}/gone", 0o555); + + $out = new BufferedOutputWriter(); + + try { + $exitCode = (new PruneService()) + ->run($project->context(), $out, true); + } finally { + chmod("{$this->tempDir}/gone", 0o755); + } + + Assert::same( + $exitCode, + 0, + "Exit code must be '0' when only an empty parent directory cannot be removed.", + ); + FileAssert::fileDoesNotExist( + "{$this->tempDir}/gone/deep/old.txt", + 'The orphan file must be deleted.', + ); + Assert::same( + $out->stderrBuffer, + Message::FILESYSTEM_FAILED->getMessage( + ConsoleMessage::PRUNE_DIRECTORY_REMOVE_FAILED->getMessage("{$this->tempDir}/gone/deep"), + "rmdir({$this->tempDir}/gone/deep): Permission denied", + ) . PHP_EOL, + 'The failed directory removal must be reported with its reason.', + ); + } + + public function forceDeletesOnlyUnmodifiedOrphansAndCleansTheLock(): void + { + $project = $this->seedOrphans(); + $out = new BufferedOutputWriter(); + + Assert::same( + (new PruneService())->run($project->context(), $out, true), + 0, + "Exit code must be '0'.", + ); + Assert::same( + $out->stdoutBuffer, + implode( + PHP_EOL, + [ + ConsoleMessage::PRUNE_KEPT->getMessage('.gitignore', 'merged'), + ConsoleMessage::PRUNE_KEPT->getMessage('edited.txt', 'modified'), + ConsoleMessage::PRUNE_DELETED->getMessage('gone/deep/old.txt', ''), + ConsoleMessage::PRUNE_DELETED->getMessage('legacy.txt', ''), + ConsoleMessage::PRUNE_ENTRY_DROPPED->getMessage('missing.txt', 'missing'), + ConsoleMessage::PRUNE_SUMMARY->getMessage(3, 2, 0, ConsoleMessage::FRAGMENT_ERRORS->getMessage()), + '', + ], + ), + 'Every orphan must be reported.', + ); + FileAssert::fileDoesNotExist( + "{$this->tempDir}/gone/deep/old.txt", + 'Unmodified orphan must be deleted.', + ); + FileAssert::directoryDoesNotExist( + "{$this->tempDir}/gone", + 'Empty parents must be removed.', + ); + FileAssert::directoryExists( + $this->tempDir, + 'Project root must stay.', + ); + FileAssert::fileDoesNotExist( + "{$this->tempDir}/legacy.txt", + 'Orphan of a removed provider must be deleted.', + ); + FileAssert::fileExists( + "{$this->tempDir}/edited.txt", + 'Modified orphan must stay.', + ); + FileAssert::fileExists( + "{$this->tempDir}/.gitignore", + 'Merged orphan must stay.', + ); + FileAssert::fileExists( + "{$this->tempDir}/kept.txt", + 'Shipped file must stay.', + ); + + $lock = $project->lock()->read(); + + Assert::same( + array_keys($lock['files']), + ['ej.txt', 'kept.txt'], + 'Shipped and ejected entries must remain.', + ); + Assert::same( + array_keys($lock['providers']), + ['p/a'], + 'Provider without entries must be removed.', + ); + + $again = new BufferedOutputWriter(); + + Assert::same( + (new PruneService())->run($project->context(), $again, true), + 0, + "Exit code of the second run must be '0'.", + ); + Assert::same( + $again->stdoutBuffer, + ConsoleMessage::PRUNE_NO_ORPHANS->getMessage() . PHP_EOL, + 'Nothing may be left to prune.', + ); + } + + public function forceKeepsDirectoriesThatStillHoldFiles(): void + { + $project = (new InspectionProject($this->tempDir)) + ->composer(['p/a']) + ->installed(['p/a' => '1.0.0']) + ->provider('p/a', ['kept.txt' => "kept\n"]) + ->file('shared/a.txt', "a\n") + ->file('shared/mine.txt', "mine\n") + ->track('shared/a.txt', 'p/a'); + + $out = new BufferedOutputWriter(); + + Assert::same( + (new PruneService())->run($project->context(), $out, true), + 0, + "Exit code must be '0'.", + ); + Assert::same( + $out->stderrBuffer, + '', + 'A non-empty directory must not be removed.', + ); + FileAssert::fileDoesNotExist( + "{$this->tempDir}/shared/a.txt", + 'Orphan must be deleted.', + ); + FileAssert::fileExists( + "{$this->tempDir}/shared/mine.txt", + 'Consumer file must stay.', + ); + } + + public function forceKeepsEmptyDirectoriesAboveAProjectRootWithTrailingSeparators(): void + { + $project = (new InspectionProject($this->tempDir)) + ->composer(['p/a']) + ->installed(['p/a' => '1.0.0']) + ->provider('p/a', ['kept.txt' => "kept\n"]) + ->file('s/a.txt', "a\n") + ->track('s/a.txt', 'p/a'); + + $context = ProjectContext::create("{$this->tempDir}//"); + + Assert::same( + (new PruneService())->run($context, new BufferedOutputWriter(), true), + 0, + "Exit code must be '0'.", + ); + FileAssert::directoryDoesNotExist( + "{$this->tempDir}/s", + 'Emptied directory must be removed.', + ); + FileAssert::directoryExists( + $this->tempDir, + 'Project root must stay.', + ); + Assert::false( + array_key_exists('s/a.txt', $project->lock()->read()['files']), + 'Entry must be removed.', + ); + } + + public function forceLeavesSymlinkedDirectoriesInPlace(): void + { + $project = (new InspectionProject($this->tempDir)) + ->composer(['p/a']) + ->installed(['p/a' => '1.0.0']) + ->provider('p/a', ['kept.txt' => "kept\n"]) + ->file('real/a.txt', "a\n"); + + if (@symlink("{$this->tempDir}/real", "{$this->tempDir}/link") === false) { + throw new SkipTest('Symbolic links are not available.'); + } + + $project->track('link/a.txt', 'p/a'); + + $out = new BufferedOutputWriter(); + + Assert::same( + (new PruneService())->run($project->context(), $out, true), + 0, + "Exit code must be '0'.", + ); + Assert::same( + $out->stderrBuffer, + '', + 'The symbolic link must not be removed as a directory.', + ); + FileAssert::fileDoesNotExist( + "{$this->tempDir}/real/a.txt", + 'Orphan must be deleted through the link.', + ); + FileAssert::directoryExists( + "{$this->tempDir}/real", + 'Link target must stay.', + ); + } + + public function forceRemovesOnlyProvidersThatAreUnusedAndNotAllowedAndInstalled(): void + { + $project = (new InspectionProject($this->tempDir)) + ->composer(['p/a', 'p/idle']) + ->installed(['p/a' => '1.0.0', 'p/idle' => '1.0.0']) + ->provider('p/a', ['kept.txt' => "kept\n"]) + ->provider('p/idle', ['idle.txt' => "idle\n"]) + ->file('kept.txt', "kept\n") + ->track('kept.txt', 'p/a') + ->file('gone.txt', "gone\n") + ->track('gone.txt', 'p/a') + ->file('ej.txt', "mine\n") + ->track('ej.txt', 'p/denied', extra: ['ejected' => true]) + ->track('stale.txt', 'p/old'); + + $data = $project->lock()->read(); + + $data['providers']['p/idle'] = ['version' => '1.0.0', 'path' => 'vendor/p/idle']; + + $project->lock()->write($data); + + Assert::same( + (new PruneService())->run($project->context(), new BufferedOutputWriter(), true), + 0, + "Exit code must be '0'.", + ); + Assert::same( + array_keys($project->lock()->read()['providers']), + ['p/a', 'p/denied', 'p/idle'], + 'Owners and allowed installed providers stay; the unused removed provider goes.', + ); + } + + #[DataSet([false], 'preview')] + #[DataSet([true], 'force')] + public function lockWithoutOrphansOrStaleProvidersIsNeverRewritten(bool $force): void + { + $project = $this->seedShippedOnly(); + $lock = (string) file_get_contents("{$this->tempDir}/scaffold-lock.json"); + + (new PruneService()) + ->run($project->context(), new BufferedOutputWriter(), $force); + + Assert::same( + file_get_contents("{$this->tempDir}/scaffold-lock.json"), + $lock, + 'Nothing to drop must leave the lock untouched.', + ); + } + + public function orphansOfAProviderWhoseManifestFailsAreNeverPruned(): void + { + $project = $this->seedOrphans()->file('vendor/p/a/composer.json', '{broken'); + + $out = new BufferedOutputWriter(); + + Assert::same( + (new PruneService())->run($project->context(), $out, true), + 1, + "Exit code must be '1' when a manifest fails.", + ); + Assert::same( + $out->stderrBuffer, + Message::SCAFFOLD_MANIFEST_LOAD_FAILED->getMessage('p/a', 'Syntax error') . PHP_EOL, + 'Cause must be the only stderr line.', + ); + FileAssert::fileExists( + "{$this->tempDir}/gone/deep/old.txt", + 'Files of the failed provider must stay.', + ); + FileAssert::fileDoesNotExist( + "{$this->tempDir}/legacy.txt", + 'Other orphans must still be pruned.', + ); + } + + public function orphanWhoseDestinationIsADirectoryIsAnErrorAndIsNeverDeleted(): void + { + $project = (new InspectionProject($this->tempDir)) + ->composer(['p/a']) + ->installed(['p/a' => '1.0.0']) + ->provider('p/a', ['kept.txt' => "kept\n"]) + ->track('dir.txt', 'p/a'); + + // A directory where the orphan file is expected cannot be hashed. + mkdir("{$this->tempDir}/dir.txt"); + + $preview = new BufferedOutputWriter(); + + Assert::same( + (new PruneService())->run($project->context(), $preview), + 1, + "Exit code must be '1' when an orphan cannot be read.", + ); + Assert::same( + $preview->stdoutBuffer, + implode( + PHP_EOL, + [ + 'File Provider Disk With --force', + '--------------------------------------', + 'dir.txt p/a error keep', + ConsoleMessage::PRUNE_DRY_RUN_SUMMARY->getMessage( + 0, + 1, + 1, + ConsoleMessage::FRAGMENT_ERROR->getMessage(), + ), + '', + ], + ), + "Preview must list the unreadable orphan as 'error' and 'keep'.", + ); + + $forced = new BufferedOutputWriter(); + + Assert::same( + (new PruneService())->run($project->context(), $forced, true, true), + 1, + "Exit code must be '1' when a forced prune meets an unreadable orphan.", + ); + FileAssert::directoryExists( + "{$this->tempDir}/dir.txt", + "An unreadable orphan must never be deleted, even with '--delete-modified'.", + ); + Assert::same( + $forced->stdoutBuffer, + ConsoleMessage::PRUNE_KEPT->getMessage('dir.txt', 'error') . PHP_EOL + . ConsoleMessage::PRUNE_SUMMARY->getMessage(0, 1, 1, ConsoleMessage::FRAGMENT_ERROR->getMessage()) . PHP_EOL, + 'Forced prune must report the unreadable orphan as kept.', + ); + } + + public function staleProviderWithoutOrphansIsDroppedOnlyWhenForced(): void + { + $project = $this->seedShippedOnly(); + + $data = $project->lock()->read(); + + $data['providers']['p/old'] = [ + 'version' => '1.0.0', + 'path' => 'vendor/p/old', + ]; + + file_put_contents( + "{$this->tempDir}/scaffold-lock.json", + json_encode($data, JSON_THROW_ON_ERROR), + ); + + $stale = (string) file_get_contents("{$this->tempDir}/scaffold-lock.json"); + + $out = new BufferedOutputWriter(); + + (new PruneService()) + ->run($project->context(), $out); + + Assert::same( + file_get_contents("{$this->tempDir}/scaffold-lock.json"), + $stale, + 'A preview must never drop providers.', + ); + Assert::same( + $out->stdoutBuffer, + ConsoleMessage::PRUNE_NO_ORPHANS->getMessage() . PHP_EOL, + 'No orphan must be reported.', + ); + + (new PruneService())->run($project->context(), new BufferedOutputWriter(), true); + + Assert::same( + array_keys($project->lock()->read()['providers']), + ['p/a'], + 'Forced prune must drop the stale provider.', + ); + } + + /** + * Returns the preview table of {@see self::seedOrphans()} followed by `$summary`. + */ + private static function orphanTable(string $summary): string + { + return implode( + PHP_EOL, + [ + 'File Provider Disk With --force', + '-----------------------------------------------------', + '.gitignore p/a merged keep', + 'edited.txt p/a modified keep', + 'gone/deep/old.txt p/a unmodified delete', + 'legacy.txt p/old unmodified delete', + 'missing.txt p/a missing drop entry', + $summary, + '', + ], + ); + } + + /** + * Builds a project whose lock holds a shipped file, an ejected file and five orphans in every disk state. + */ + private function seedOrphans(): InspectionProject + { + return (new InspectionProject($this->tempDir)) + ->composer(['p/a']) + ->installed(['p/a' => '1.0.0', 'p/old' => '1.0.0']) + ->provider('p/a', ['kept.txt' => "kept\n"]) + ->file('kept.txt', "kept\n") + ->track('kept.txt', 'p/a') + ->file('ej.txt', "ejected\n") + ->track('ej.txt', 'p/a', extra: ['ejected' => true]) + ->file('gone/deep/old.txt', "old\n") + ->track('gone/deep/old.txt', 'p/a') + ->file('edited.txt', "provider\n") + ->track('edited.txt', 'p/a') + ->file('edited.txt', "mine\n") + ->file('.gitignore', "/vendor\n/mine\n") + ->track('.gitignore', 'p/a', 'append') + ->track('missing.txt', 'p/a') + ->file('legacy.txt', "legacy\n") + ->track('legacy.txt', 'p/old'); + } + + /** + * Builds a project whose only entry is shipped, with its lock rewritten as compact JSON. + */ + private function seedShippedOnly(): InspectionProject + { + $project = (new InspectionProject($this->tempDir)) + ->composer(['p/a']) + ->installed(['p/a' => '1.0.0']) + ->provider('p/a', ['kept.txt' => "kept\n"]) + ->file('kept.txt', "kept\n") + ->track('kept.txt', 'p/a'); + + file_put_contents( + "{$this->tempDir}/scaffold-lock.json", + json_encode($project->lock()->read(), JSON_THROW_ON_ERROR), + ); + + return $project; + } +} diff --git a/tests/Services/ReapplyDryRunTest.php b/tests/Services/ReapplyDryRunTest.php new file mode 100644 index 0000000..4135313 --- /dev/null +++ b/tests/Services/ReapplyDryRunTest.php @@ -0,0 +1,497 @@ +tempDir)) + ->composer(['p/a']) + ->provider('p/a', ['a.txt' => "a1\n", 'b.txt' => "b1\n"]) + ->file('a.txt', "a1\n") + ->file('b.txt', "b1\n") + ->track('a.txt', 'p/a') + ->track('b.txt', 'p/a') + ->stub('p/a', 'a.txt', "a2\n") + ->stub('p/a', 'b.txt', "b2\n"); + + $out = new BufferedOutputWriter(); + + $this->reapply($project, $out, dryRun: true); + + Assert::same( + $out->stdoutBuffer, + ConsoleMessage::DIFF_PREVIEW_HEADER->getMessage('a.txt', 'replace', 'p/a', '') . PHP_EOL + . "--- a/a.txt\n+++ b/a.txt\n@@ -1 +1 @@\n-a1\n+a2" . PHP_EOL + . ConsoleMessage::DIFF_PREVIEW_HEADER->getMessage('b.txt', 'replace', 'p/a', '') . PHP_EOL + . "--- a/b.txt\n+++ b/b.txt\n@@ -1 +1 @@\n-b1\n+b2" . PHP_EOL + . ExpectedSummary::reapplyDryRun(2, 0, 0, 0) . PHP_EOL, + 'Both previews must be printed and counted.', + ); + } + + #[DataProvider(ReapplyServiceProvider::class . '::dryRunExitCodes')] + public function dryRunExitCodeReportsPendingChangesOnlyWhenRequested( + string $stub, + bool $exitCode, + int $expectedExitCode, + string $expectedStdout, + ): void { + $project = (new InspectionProject($this->tempDir)) + ->composer(['p/a']) + ->provider('p/a', ['a.txt' => "v1\n"]) + ->file('a.txt', "v1\n") + ->track('a.txt', 'p/a') + ->stub('p/a', 'a.txt', $stub); + + $out = new BufferedOutputWriter(); + + Assert::same( + $this->reapply($project, $out, dryRun: true, exitCode: $exitCode), + $expectedExitCode, + 'Exit code of the dry run must match.', + ); + Assert::same( + $out->stdoutBuffer, + $expectedStdout, + 'Preview and summary must match.', + ); + } + + public function dryRunOfAnAppendFileCountsUnchangedAndReportsAMissingStub(): void + { + $project = (new InspectionProject($this->tempDir)) + ->composer(['p/a']) + ->provider('p/a', ['.gitignore' => "/vendor\n", 'list.txt' => "a\n"], ['.gitignore' => 'append']) + ->file('.gitignore', "/vendor\n") + ->file('list.txt', "a\n") + ->track('.gitignore', 'p/a', 'append', ['merge' => 'unknown']) + ->track('list.txt', 'p/a', 'append') + ->delete('vendor/p/a/stubs/list.txt'); + + $out = new BufferedOutputWriter(); + + Assert::same( + $this->reapply($project, $out, dryRun: true), + 1, + "Exit code must be '1' when a stub is missing.", + ); + Assert::same( + $out->stderrBuffer, + ConsoleMessage::REAPPLY_MERGE_STRATEGY_UNKNOWN->getMessage('unknown', '.gitignore') . PHP_EOL + . ConsoleMessage::REAPPLY_STUB_NOT_FOUND->getMessage( + PathResolver::source((string) realpath("{$this->tempDir}/vendor/p/a"), 'stubs/list.txt'), + ) . PHP_EOL, + 'Unknown strategy and missing stub must be reported.', + ); + Assert::same( + $out->stdoutBuffer, + ConsoleMessage::DIFF_NO_CHANGES->getMessage('.gitignore') . PHP_EOL + . ExpectedSummary::reapplyDryRun(0, 1, 0, 1) . PHP_EOL, + 'Summary must count both entries.', + ); + } + public function dryRunPrintsTheDiffServiceOutputAndWritesNothing(): void + { + $project = (new InspectionProject($this->tempDir)) + ->composer(['p/a']) + ->provider('p/a', ['a.txt' => "v1\n", '.gitignore' => "/vendor\n"], ['.gitignore' => 'append']) + ->file('a.txt', "v1\n") + ->file('.gitignore', "/vendor\n") + ->track('a.txt', 'p/a') + ->track('.gitignore', 'p/a', 'append') + ->stub('p/a', 'a.txt', "v2\n") + ->stub('p/a', '.gitignore', "/vendor\n/.config/gh\n"); + + $lockBefore = file_get_contents( + "{$this->tempDir}/scaffold-lock.json", + ); + + $diff = new BufferedOutputWriter(); + + (new DiffService()) + ->run($project->context(), $diff); + + $out = new BufferedOutputWriter(); + + Assert::same( + $this->reapply($project, $out, dryRun: true), + 0, + "Exit code of a dry run without '--exit-code' must be '0'.", + ); + Assert::same( + $out->stdoutBuffer, + $diff->stdoutBuffer . ExpectedSummary::reapplyDryRun(2, 0, 0, 0) . PHP_EOL, + 'Dry run must print the diff output and a summary.', + ); + FileAssert::contentSame( + "{$this->tempDir}/a.txt", + "v1\n", + 'Replace file must be untouched.', + ); + FileAssert::contentSame( + "{$this->tempDir}/.gitignore", + "/vendor\n", + 'Append file must be untouched.', + ); + Assert::same( + file_get_contents("{$this->tempDir}/scaffold-lock.json"), + $lockBefore, + 'Lock must be untouched.', + ); + } + + public function dryRunWithForceShowsTheStubOverwriteOfAnAppendFile(): void + { + $project = (new InspectionProject($this->tempDir)) + ->composer(['p/a']) + ->provider('p/a', ['.gitignore' => "/vendor\n"], ['.gitignore' => 'append']) + ->file('.gitignore', "/vendor\n/mine\n") + ->track('.gitignore', 'p/a', 'append'); + + $out = new BufferedOutputWriter(); + + $this->reapply($project, $out, force: true, dryRun: true); + + Assert::same( + $out->stdoutBuffer, + ConsoleMessage::DIFF_PREVIEW_HEADER->getMessage('.gitignore', 'append', 'p/a', '') . PHP_EOL + . "--- a/.gitignore\n+++ b/.gitignore\n@@ -1,2 +1 @@\n /vendor\n-/mine" . PHP_EOL + . ExpectedSummary::reapplyDryRun(1, 0, 0, 0) . PHP_EOL, + 'Force must preview the stub overwrite of the append file.', + ); + FileAssert::contentSame( + "{$this->tempDir}/.gitignore", + "/vendor\n/mine\n", + 'Nothing may be written.', + ); + } + + public function forcedDryRunReportsAnUnreadableDestinationAndKeepsGoing(): void + { + $project = (new InspectionProject($this->tempDir)) + ->composer(['p/a']) + ->provider('p/a', ['a.txt' => "a2\n", 'b.txt' => "b2\n"]) + ->file('a.txt', "a1\n") + ->file('b.txt', "b1\n") + ->track('a.txt', 'p/a') + ->track('b.txt', 'p/a'); + + $this->restrictFileAccess("{$this->tempDir}/a.txt", 0o000); + + $out = new BufferedOutputWriter(); + + Assert::same( + $this->reapply($project, $out, force: true, dryRun: true), + 1, + "Exit code must be '1' when a destination cannot be read.", + ); + Assert::same( + $out->stderrBuffer, + ConsoleMessage::REAPPLY_FAILED->getMessage( + 'a.txt', + Message::FILESYSTEM_FAILED->getMessage( + Message::SERVICE_CURRENT_FILE_UNREADABLE->getMessage("{$this->tempDir}/a.txt"), + "file_get_contents({$this->tempDir}/a.txt): Failed to open stream: Permission denied", + ), + ) . PHP_EOL, + 'Unreadable destination must be reported with its reason.', + ); + Assert::same( + $out->stdoutBuffer, + ConsoleMessage::DIFF_PREVIEW_HEADER->getMessage('b.txt', 'replace', 'p/a', '') . PHP_EOL + . "--- a/b.txt\n+++ b/b.txt\n@@ -1 +1 @@\n-b1\n+b2" . PHP_EOL + . ExpectedSummary::reapplyDryRun(1, 0, 0, 1) . PHP_EOL, + 'Next file must still be previewed and the error counted.', + ); + } + + public function givenContextIsUsedInsteadOfTheComposerJsonOnDisk(): void + { + $project = (new InspectionProject($this->tempDir)) + ->composer(['p/a']) + ->provider('p/a', ['a.txt' => "a\n"]) + ->file('a.txt', "a\n") + ->track('a.txt', 'p/a'); + + $context = $project->context(); + + $project->composer([]); + + $out = new BufferedOutputWriter(); + + Assert::same( + (new ReapplyService())->run($context, $out), + 0, + "Exit code must be '0' with the allowlist of the given context.", + ); + Assert::same( + $out->stderrBuffer, + '', + 'No allowlist rejection may be reported.', + ); + Assert::same( + $out->stdoutBuffer, + ConsoleMessage::REAPPLY_APPLIED->getMessage('a.txt') . PHP_EOL + . ExpectedSummary::reapply(1, 0, 0, 0) . PHP_EOL, + 'Entry must be reapplied.', + ); + } + + public function lockIsNotRewrittenWhenNothingWasUpdated(): void + { + $project = (new InspectionProject($this->tempDir)) + ->composer(['p/a']) + ->provider('p/a', ['a.txt' => "a\n"]) + ->file('a.txt', "a\n") + ->track('a.txt', 'p/a') + ->file('a.txt', "mine\n"); + + $compact = json_encode($project->lock()->read(), JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR); + + file_put_contents( + "{$this->tempDir}/scaffold-lock.json", + $compact, + ); + + $this->reapply($project, new BufferedOutputWriter()); + + Assert::same( + file_get_contents("{$this->tempDir}/scaffold-lock.json"), + $compact, + 'Lock bytes must be unchanged.', + ); + } + + public function notAllowedProviderIsSkippedAndFails(): void + { + $project = (new InspectionProject($this->tempDir)) + ->composer(['p/a']) + ->provider('p/denied', ['d.txt' => "d\n"]) + ->file('d.txt', "x\n") + ->track('d.txt', 'p/denied'); + + $out = new BufferedOutputWriter(); + + Assert::same( + $this->reapply($project, $out, force: true), + 1, + "Exit code must be '1' for an allowlist rejection.", + ); + FileAssert::contentSame( + "{$this->tempDir}/d.txt", + "x\n", + 'File must never be written.', + ); + Assert::same( + $out->stderrBuffer, + ConsoleMessage::COMMAND_PROVIDER_NOT_ALLOWED->getMessage('d.txt', 'p/denied') . PHP_EOL, + 'Rejection must be reported.', + ); + Assert::same( + $out->stdoutBuffer, + ExpectedSummary::reapply(0, 0, 0, 1) . PHP_EOL, + 'Summary must count the error.', + ); + } + + #[DataSet([false], 'without force')] + #[DataSet([true], 'with force')] + public function orphanedEntryIsSkippedWithThePruneHint(bool $force): void + { + $project = (new InspectionProject($this->tempDir)) + ->composer(['p/a']) + ->provider('p/a', ['a.txt' => "a\n"]) + ->file('a.txt', "a\n") + ->file('old.txt', "old\n") + ->track('a.txt', 'p/a') + ->track('old.txt', 'p/a'); + + $lockBefore = file_get_contents( + "{$this->tempDir}/scaffold-lock.json", + ); + + $out = new BufferedOutputWriter(); + + Assert::same( + $this->reapply($project, $out, force: $force), + 0, + "Exit code of an orphan skip must be '0'.", + ); + Assert::same( + $out->stderrBuffer, + ConsoleMessage::REAPPLY_ORPHANED->getMessage('old.txt') . PHP_EOL, + 'Orphan must be reported with the prune hint.', + ); + Assert::same( + $out->stdoutBuffer, + ConsoleMessage::REAPPLY_APPLIED->getMessage('a.txt') . PHP_EOL + . ExpectedSummary::reapply(1, 0, 1, 0, 'orphaned') . PHP_EOL, + 'Summary must count the orphan as skipped.', + ); + FileAssert::contentSame( + "{$this->tempDir}/old.txt", + "old\n", + 'Orphan file must be untouched.', + ); + Assert::same( + file_get_contents("{$this->tempDir}/scaffold-lock.json"), + $lockBefore, + 'Lock must be unchanged: the shipped file was already synced and the orphan entry is kept.', + ); + } + + public function orphanedEntryOfAnAllowedProviderThatIsNotInstalledIsSkipped(): void + { + $project = (new InspectionProject($this->tempDir)) + ->composer(['p/a', 'p/gone']) + ->provider('p/a', ['a.txt' => "a\n"]) + ->file('a.txt', "a\n") + ->file('g.txt', "g\n") + ->track('a.txt', 'p/a') + ->track('g.txt', 'p/gone') + ->installed(['p/a' => '1.0.0']); + + $out = new BufferedOutputWriter(); + + Assert::same( + $this->reapply($project, $out), + 0, + "Exit code of an orphan skip must be '0'.", + ); + Assert::same( + $out->stderrBuffer, + ConsoleMessage::REAPPLY_ORPHANED->getMessage('g.txt') . PHP_EOL, + 'Orphan must be reported instead of a missing stub.', + ); + Assert::same( + $out->stdoutBuffer, + ConsoleMessage::REAPPLY_APPLIED->getMessage('a.txt') . PHP_EOL + . ExpectedSummary::reapply(1, 0, 1, 0, 'orphaned') . PHP_EOL, + 'Summary must count the orphan as skipped.', + ); + } + + public function skippedEntriesDoNotStopTheIteration(): void + { + $project = (new InspectionProject($this->tempDir)) + ->composer(['p/a']) + ->provider('p/a', ['b-ejected.txt' => "b\n", 'd-shipped.txt' => "d2\n"]) + ->provider('p/denied', ['a-denied.txt' => "x\n"]) + ->file('a-denied.txt', "x\n") + ->file('b-ejected.txt', "b\n") + ->file('c-orphan.txt', "c\n") + ->file('d-shipped.txt', "d1\n") + ->track('a-denied.txt', 'p/denied') + ->track('b-ejected.txt', 'p/a', extra: ['ejected' => true]) + ->track('c-orphan.txt', 'p/a') + ->track('d-shipped.txt', 'p/a'); + + $out = new BufferedOutputWriter(); + + $this->reapply($project, $out); + + Assert::same( + $out->stdoutBuffer, + ConsoleMessage::REAPPLY_APPLIED->getMessage('d-shipped.txt') . PHP_EOL + . ExpectedSummary::reapply( + 1, + 0, + 2, + 1, + ConsoleMessage::FRAGMENT_COUNT->getMessage(1, 'ejected'), + ConsoleMessage::FRAGMENT_COUNT->getMessage(1, 'orphaned'), + ) . PHP_EOL, + 'Entry after every skip must still be reapplied.', + ); + } + + public function summaryListsSkipReasons(): void + { + $project = (new InspectionProject($this->tempDir)) + ->composer(['p/a']) + ->provider('p/a', ['a.txt' => "a\n", 'b.txt' => "b\n", 'e.txt' => "e\n"], ['b.txt' => 'preserve']) + ->file('a.txt', "a\n") + ->file('b.txt', "b\n") + ->file('e.txt', "e\n") + ->track('a.txt', 'p/a') + ->track('b.txt', 'p/a', 'preserve') + ->track('e.txt', 'p/a', extra: ['ejected' => true]) + ->file('a.txt', "mine\n"); + + $out = new BufferedOutputWriter(); + + Assert::same( + $this->reapply($project, $out), + 0, + "Exit code of skips must be '0'.", + ); + Assert::same( + $out->stdoutBuffer, + ExpectedSummary::reapply( + 0, + 0, + 3, + 0, + ConsoleMessage::FRAGMENT_COUNT->getMessage(1, 'user-modified'), + ConsoleMessage::FRAGMENT_COUNT->getMessage(1, 'preserve'), + ConsoleMessage::FRAGMENT_COUNT->getMessage(1, 'ejected'), + ) . PHP_EOL, + 'Summary must list the skip reasons.', + ); + } + + /** + * Runs `reapply` over every tracked file of the project. + */ + private function reapply( + InspectionProject $project, + BufferedOutputWriter $out, + bool $force = false, + bool $dryRun = false, + bool $exitCode = false, + ): int { + return (new ReapplyService())->run( + $project->context(), + $out, + force: $force, + dryRun: $dryRun, + exitCode: $exitCode, + ); + } +} diff --git a/tests/Services/ReapplyServiceTest.php b/tests/Services/ReapplyServiceTest.php index 2d91b6e..7e82488 100644 --- a/tests/Services/ReapplyServiceTest.php +++ b/tests/Services/ReapplyServiceTest.php @@ -4,1325 +4,976 @@ namespace PHPForge\Scaffold\Tests\Services; +use PHPForge\Scaffold\Console\Message as ConsoleMessage; +use PHPForge\Scaffold\Exception\Message; use PHPForge\Scaffold\Scaffold\Lock\{Hasher, LockFile}; use PHPForge\Scaffold\Scaffold\PathResolver; -use PHPForge\Scaffold\Services\ReapplyService; -use PHPForge\Scaffold\Tests\Support\{BufferedOutputWriter, TempDirectoryTrait}; -use PHPUnit\Framework\Attributes\Group; -use PHPUnit\Framework\TestCase; -use Xepozz\InternalMocker\MockerState; +use PHPForge\Scaffold\Services\{ReapplyService, ReapplySummary}; +use PHPForge\Scaffold\Tests\Provider\ReapplyServiceProvider; +use PHPForge\Scaffold\Tests\Support\{ + BufferedOutputWriter, + ExpectedSummary, + FileAssert, + InspectionProject, + TempDirectoryTrait, +}; +use RuntimeException; +use Testo\Assert; +use Testo\Codecov\Covers; +use Testo\Core\Exception\SkipTest; +use Testo\Data\{DataProvider, DataSet}; +use Testo\Expect; +use Testo\Test; + +use function chmod; +use function dirname; +use function file_get_contents; +use function file_put_contents; +use function fileperms; +use function hash; +use function mkdir; +use function preg_quote; +use function realpath; +use function str_replace; +use function umask; /** - * Unit tests for {@see ReapplyService} covering single-file, provider-filter, force, and error-path branches. + * Unit tests for {@see ReapplyService} covering the write path: modes, filters, force, and the error paths. + * + * {@see ReapplyServiceProvider} for test case data providers. */ -#[Group('scaffold')] -#[Group('services')] -final class ReapplyServiceTest extends TestCase +#[Test] +#[Covers(ReapplyService::class)] +#[Covers(ReapplySummary::class)] +final class ReapplyServiceTest { use TempDirectoryTrait; - public function testAppendAndPrependModesCannotBeReapplied(): void + public function adoptedEntryIsTreatedAsUserModifiedUntilForced(): void { - $modes = ['append', 'prepend']; - - foreach ($modes as $mode) { - $file = ".env.{$mode}.dist"; - - $this->seedTracked($file, "A=1\n", "A=1\n", mode: $mode); - - $out = new BufferedOutputWriter(); - (new ReapplyService())->run( - $this->tempDir, - "{$this->tempDir}/vendor", - file: $file, - provider: '', - force: false, - out: $out, - ); - - self::assertStringContainsString( - 'cannot be safely reapplied', - $out->stdoutBuffer, - sprintf( - "When a file is in '%s' mode, it cannot be safely reapplied (message must emit for append and prepend).", - $mode, - ), - ); - self::assertStringContainsString( - sprintf('mode "%s"', $mode), - $out->stdoutBuffer, - sprintf( - "The diagnostic must name the actual mode ('%s') so users know which file-mapping entry skipped.", - $mode, - ), - ); - } - } - - public function testAppendModeOutputEndsWithSinglePhpEolSuffix(): void - { - $this->seedTracked('.env.dist', "A=1\n", "A=1\n", mode: 'append'); + $project = (new InspectionProject($this->tempDir)) + ->composer(['p/a']) + ->provider('p/a', ['ecs.php' => "stub\n"]) + ->file('ecs.php', "mine\n") + ->track('ecs.php', 'p/a', extra: ['adopted' => true]); $out = new BufferedOutputWriter(); - (new ReapplyService())->run( - $this->tempDir, - "{$this->tempDir}/vendor", - file: '.env.dist', - provider: '', - force: false, - out: $out, - ); - self::assertStringEndsWith( - PHP_EOL, - $out->stdoutBuffer, - "The 'cannot be safely reapplied' notice must end with PHP_EOL so shells render it on its own line.", + Assert::same( + $this->reapply($project, $out, 'ecs.php'), + 0, + "Exit code of a user-modified skip must be '0'.", ); - self::assertStringEndsNotWith( - PHP_EOL . PHP_EOL, - $out->stdoutBuffer, - "The 'cannot be safely reapplied' notice must end with exactly one PHP_EOL.", + Assert::same( + $out->stderrBuffer, + ConsoleMessage::REAPPLY_USER_MODIFIED->getMessage('ecs.php') . PHP_EOL, + 'Adopted file must be reported as user-modified.', ); - self::assertStringStartsNotWith( - PHP_EOL, + Assert::same( $out->stdoutBuffer, - "The 'cannot be safely reapplied' notice must not be prefixed with PHP_EOL.", + ExpectedSummary::reapply(0, 0, 1, 0, 'user-modified') . PHP_EOL, + 'Summary must count the skip.', + ); + FileAssert::contentSame( + "{$this->tempDir}/ecs.php", + "mine\n", + 'User content must be kept.', ); - } - public function testAppendPrependModeSkipContinuesIterationToNextReapplicableEntry(): void - { - // Append entry first (skipped) then replace entry: the skip must 'continue' so the replace entry is reapplied. - $this->seedTracked('.env.dist', "A=1\n", "A=1\n", mode: 'append'); - $this->seedTracked('config/params.php', "stub\n", "stub\n", mode: 'replace'); + $this->reapply($project, new BufferedOutputWriter(), 'ecs.php', force: true); - $out = new BufferedOutputWriter(); - (new ReapplyService())->run( - $this->tempDir, - "{$this->tempDir}/vendor", - file: '', - provider: '', - force: true, - out: $out, + FileAssert::contentSame( + "{$this->tempDir}/ecs.php", + "stub\n", + 'Force must rewrite from the stub.', ); - - self::assertStringContainsString( - 'cannot be safely reapplied', - $out->stdoutBuffer, - 'The append entry must produce the non-reapplicable diagnostic.', + Assert::same( + $project->lock()->read()['files']['ecs.php'] ?? null, + self::writtenEntry('ecs.php', "stub\n"), + "Force must record the stub hashes and clear 'adopted'.", ); - self::assertStringContainsString( - 'Reapplied "config/params.php"', - $out->stdoutBuffer, - "After the append skip, the foreach must 'continue' to the next entry, not 'break'.", + Assert::same( + $project->lock()->read()['providers'], + ['p/a' => ['version' => '1.0.0', 'path' => 'vendor/p/a']], + 'Rewritten lock must keep the providers.', ); } - public function testEmitsWarningWhenProviderPathEscapesVendor(): void + public function appendMergesTheMissingProviderLineAndRecordsTheStubHash(): void { - $this->seedTracked('config/params.php', "stub\n", "stub\n"); - - $lock = new LockFile($this->tempDir); - - $data = $lock->read(); - - $data['providers'] = [ - 'pkg/name' => [ - 'version' => '0.1.x-dev', - 'path' => '../outside-vendor', - ], - ]; - - $lock->write($data); + $project = (new InspectionProject($this->tempDir)) + ->composer(['p/a']) + ->provider('p/a', ['.env.dist' => "A=1\nB=2\n"], ['.env.dist' => 'append']) + ->file('.env.dist', "A=1\nC=3\n") + ->track('.env.dist', 'p/a', 'append'); $out = new BufferedOutputWriter(); - (new ReapplyService())->run( - $this->tempDir, - "{$this->tempDir}/vendor", - file: 'config/params.php', - provider: '', - force: true, - out: $out, - ); - self::assertStringContainsString( - 'resolves outside vendor dir', - $out->stderrBuffer, - 'When a provider path escapes the vendor directory, a warning must be emitted.', - ); - self::assertStringEndsWith( - PHP_EOL, - $out->stderrBuffer, - "The 'resolves outside vendor dir' warning must end with PHP_EOL.", + Assert::same( + $this->reapply($project, $out, '.env.dist'), + 0, + "Exit code of a merge must be '0'.", ); - self::assertStringEndsNotWith( - PHP_EOL . PHP_EOL, - $out->stderrBuffer, - "The 'resolves outside vendor dir' warning must end with exactly one PHP_EOL.", + FileAssert::contentSame( + "{$this->tempDir}/.env.dist", + "A=1\nC=3\n\nB=2\n", + 'Missing line must be merged and the consumer line kept.', ); - self::assertStringStartsNotWith( - PHP_EOL, - $out->stderrBuffer, - "The 'resolves outside vendor dir' warning must not start with PHP_EOL.", + Assert::same( + $out->stdoutBuffer, + ConsoleMessage::REAPPLY_APPLIED->getMessage('.env.dist') . PHP_EOL + . ExpectedSummary::reapply(1, 0, 0, 0) . PHP_EOL, + 'Write and summary must be reported.', ); - } - public function testEnsureDirectoryFailureIsReportedAsError(): void - { - $this->seedTracked('deep/config/params.php', "stub\n", "current\n", lockHashOf: "stub\n"); - - MockerState::addCondition( - 'PHPForge\\Scaffold\\Scaffold', - 'mkdir', - [], - false, - default: true, - ); - MockerState::addCondition( - 'PHPForge\\Scaffold\\Scaffold', - 'is_dir', - [], - false, - default: true, - ); - $out = new BufferedOutputWriter(); - (new ReapplyService())->run( - $this->tempDir, - "{$this->tempDir}/vendor", - file: 'deep/config/params.php', - provider: '', - force: true, - out: $out, - ); + $entry = $project->lock()->read()['files']['.env.dist'] ?? []; - self::assertStringContainsString( - 'Could not create directory', - $out->stderrBuffer, - 'When directory creation fails, an error must be reported.', + Assert::same( + [$entry['hash'] ?? null, $entry['stub-hash'] ?? null], + [Hasher::hash("{$this->tempDir}/.env.dist"), Hasher::hash("{$this->tempDir}/vendor/p/a/stubs/.env.dist")], + 'Hash and stub hash must be refreshed.', ); - } - public function testEnsureDirectoryFailureSkipContinuesIterationToNextReapplicableEntry(): void - { - // Entry 1 is deep-nested with its parent removed so the mocked 'mkdir' is reached; entry 2 must still be reapplied. - $this->seedTracked('deep/config/params.php', "stub\n", "stub\n"); - $this->seedTracked('top.txt', "stub\n", "stub\n"); - - $deepDestination = PathResolver::destination($this->tempDir, 'deep/config/params.php'); + $second = new BufferedOutputWriter(); - unlink($deepDestination); - rmdir(dirname($deepDestination)); + $this->reapply($project, $second, '.env.dist'); - MockerState::addCondition( - 'PHPForge\\Scaffold\\Scaffold', - 'mkdir', - [], - false, - default: true, + Assert::same( + $second->stdoutBuffer, + ConsoleMessage::REAPPLY_ALREADY_UP_TO_DATE->getMessage('.env.dist') . PHP_EOL + . ExpectedSummary::reapply(0, 1, 0, 0) . PHP_EOL, + 'Second run must be a no-op.', ); + } + + public function appendUpToDateContinuesToTheNextEntry(): void + { + $project = (new InspectionProject($this->tempDir)) + ->composer(['p/a']) + ->provider('p/a', ['.env.dist' => "A=1\n", 'config/params.php' => "stub\n"], ['.env.dist' => 'append']) + ->file('.env.dist', "A=1\n") + ->file('config/params.php', "stub\n") + ->track('.env.dist', 'p/a', 'append') + ->track('config/params.php', 'p/a'); $out = new BufferedOutputWriter(); - (new ReapplyService())->run( - $this->tempDir, - "{$this->tempDir}/vendor", - file: '', - provider: '', - force: true, - out: $out, - ); - self::assertStringContainsString( - 'Could not create directory', - $out->stderrBuffer, - "The 'ensureDirectory' failure diagnostic must be emitted for the deep entry.", + Assert::same( + $this->reapply($project, $out), + 0, + "Exit code must be '0'.", ); - self::assertStringContainsString( - 'Reapplied "top.txt"', + Assert::same( $out->stdoutBuffer, - "After the 'ensureDirectory' skip, the foreach must continue to the next entry.", + ConsoleMessage::REAPPLY_ALREADY_UP_TO_DATE->getMessage('.env.dist') . PHP_EOL + . ConsoleMessage::REAPPLY_APPLIED->getMessage('config/params.php') . PHP_EOL + . ExpectedSummary::reapply(1, 1, 0, 0) . PHP_EOL, + 'Iteration must continue to the replace entry.', ); } - public function testFileFilterSkipsNonMatchingEntriesWhileProcessingTheTarget(): void + public function appendUsesTheMergeStrategyRecordedInTheLock(): void { - $this->seedTracked('a.txt', "a\n", "a\n", provider: 'pkg/a'); - $this->seedTracked('b.txt', "b\n", "b\n", provider: 'pkg/a'); + $project = (new InspectionProject($this->tempDir)) + ->composer(['p/a']) + ->provider('p/a', ['.gitignore' => "# b\nx\n"], ['.gitignore' => 'append']) + ->file('.gitignore', "# a\nx\n") + ->track('.gitignore', 'p/a', 'append', ['merge' => 'text']); - $out = new BufferedOutputWriter(); - (new ReapplyService())->run( - $this->tempDir, - "{$this->tempDir}/vendor", - file: 'b.txt', - provider: '', - force: true, - out: $out, - ); + $this->reapply($project, new BufferedOutputWriter(), '.gitignore'); - self::assertStringContainsString( - 'Reapplied "b.txt"', - $out->stdoutBuffer, - 'When a specific file filter is supplied, only matching lock entries must be reapplied.', + FileAssert::contentSame( + "{$this->tempDir}/.gitignore", + "# a\nx\n\n# b\n", + "Recorded 'text' strategy must override the 'list' default.", ); - self::assertStringNotContainsString( - 'Reapplied "a.txt"', - $out->stdoutBuffer, - 'When a specific file filter is supplied, non-matching lock entries must be skipped.', + Assert::same( + $project->lock()->read()['files']['.gitignore']['merge'] ?? null, + 'text', + 'Recorded strategy must be kept.', ); } - public function testForceOverwritesUserModifiedFileAndUpdatesLockHash(): void + public function appendWithAnUnreadableDestinationIsAnError(): void { - $this->seedTracked('config/params.php', "stub\n", "user-edited\n", lockHashOf: "stub\n"); + $project = (new InspectionProject($this->tempDir)) + ->composer(['p/a']) + ->provider('p/a', ['.env.dist' => "A=1\n"], ['.env.dist' => 'append']) + ->track('.env.dist', 'p/a', 'append'); + + // A directory where the destination file is expected cannot be read as a file. + mkdir("{$this->tempDir}/.env.dist"); $out = new BufferedOutputWriter(); - (new ReapplyService())->run( - $this->tempDir, - "{$this->tempDir}/vendor", - file: 'config/params.php', - provider: '', - force: true, - out: $out, - ); - self::assertStringContainsString( - 'Reapplied', - $out->stdoutBuffer, - "When 'force=true', the stub content must overwrite the user's content.", - ); - self::assertSame( - "stub\n", - (string) file_get_contents($this->tempDir . '/config/params.php'), - "With 'force=true' the stub content must overwrite the user's content.", + Assert::same( + $this->reapply($project, $out, '.env.dist'), + 1, + "Exit code must be '1' when the destination cannot be read.", ); - $data = (new LockFile($this->tempDir))->read(); + // The PHP notice depends on the platform and the filesystem, so the reason is matched as a pattern. + $expected = ConsoleMessage::REAPPLY_FAILED->getMessage( + '.env.dist', + Message::FILESYSTEM_FAILED->getMessage( + Message::MODE_DESTINATION_UNREADABLE->getMessage(PathResolver::destination($this->tempDir, '.env.dist')), + 'file_get_contents(%REASON%', + ), + ) . PHP_EOL; - $entry = $data['files']['config/params.php'] ?? null; - - self::assertNotNull( - $entry, - "The entry for 'config/params.php' must survive the reapply.", + Assert::string($out->stderrBuffer)->matchesRegex( + '/\A' . str_replace('%REASON%', '.+', preg_quote($expected, '/')) . '\z/', + 'Mode failure must be the only stderr line, with its reason.', ); - self::assertSame( - 'sha256:' . hash('sha256', "stub\n"), - $entry['hash'], - 'Lock hash must be updated to reflect the newly written content.', + Assert::same( + $out->stdoutBuffer, + ExpectedSummary::reapply(0, 0, 0, 1) . PHP_EOL, + 'Summary must count the error.', ); } - public function testHashFailureBeforeWriteIsReported(): void + public function ejectedEntryIsSkippedWithoutForce(): void { - $this->seedTracked('config/params.php', "stub\n", "user-edited\n", lockHashOf: "stub\n"); + $project = (new InspectionProject($this->tempDir)) + ->composer(['p/a']) + ->provider('p/a', ['config/params.php' => "stub\n"]) + ->file('config/params.php', "stub\n") + ->track('config/params.php', 'p/a', extra: ['ejected' => true]); - MockerState::addCondition( - 'PHPForge\\Scaffold\\Scaffold\\Lock', - 'hash_file', - [], - false, - default: true, + $before = file_get_contents( + "{$this->tempDir}/scaffold-lock.json", ); + $out = new BufferedOutputWriter(); - (new ReapplyService())->run( - $this->tempDir, - "{$this->tempDir}/vendor", - file: 'config/params.php', - provider: '', - force: false, - out: $out, - ); - self::assertStringContainsString( - 'Could not hash', + $this->reapply($project, $out); + + Assert::same( $out->stderrBuffer, - 'When hashing fails before writing, an error must be reported.', + ConsoleMessage::REAPPLY_EJECTED->getMessage('config/params.php') . PHP_EOL, + 'Ejected entry must be reported.', + ); + Assert::same( + $out->stdoutBuffer, + ExpectedSummary::reapply(0, 0, 1, 0, 'ejected') . PHP_EOL, + 'Summary must count the skip.', + ); + Assert::same( + file_get_contents("{$this->tempDir}/scaffold-lock.json"), + $before, + 'Lock must be untouched.', ); } - public function testHashFailureSkipContinuesIterationToNextReapplicableEntry(): void + public function ensureDirectoryFailureContinuesToTheNextEntry(): void { - // Mock 'hash_file' to fail only on 'first.txt' so the continue-branch fires; 'second.txt' must still be reapplied. - $this->seedTracked('first.txt', "stub\n", "stub\n"); - $this->seedTracked('second.txt', "stub\n", "stub\n"); - - // Target the first destination exclusively so the mock does not leak into the second iteration's hash calls. - MockerState::addCondition( - 'PHPForge\\Scaffold\\Scaffold\\Lock', - 'hash_file', - ['sha256', PathResolver::destination($this->tempDir, 'first.txt'), false, []], - false, - ); + $project = (new InspectionProject($this->tempDir)) + ->composer(['p/a']) + ->provider('p/a', ['deep/config/params.php' => "stub\n", 'top.txt' => "stub\n"]) + // A regular file where the parent directory belongs blocks its creation. + ->file('deep/config', 'blocker') + ->file('top.txt', "stub\n") + ->track('deep/config/params.php', 'p/a') + ->track('top.txt', 'p/a'); $out = new BufferedOutputWriter(); - (new ReapplyService())->run( - $this->tempDir, - "{$this->tempDir}/vendor", - file: '', - provider: '', - force: false, - out: $out, - ); - self::assertStringContainsString( - 'Could not hash "first.txt"', + Assert::same( + $this->reapply($project, $out, force: true), + 1, + "Exit code must be '1' when a directory cannot be created.", + ); + Assert::same( $out->stderrBuffer, - "The hash-failure diagnostic must be emitted for 'first.txt'.", + ConsoleMessage::REAPPLY_FAILED->getMessage( + 'deep/config/params.php', + Message::FILESYSTEM_FAILED->getMessage( + Message::PATH_DIRECTORY_CREATE_FAILED->getMessage( + dirname(PathResolver::destination($this->tempDir, 'deep/config/params.php')), + ), + 'mkdir(): File exists', + ), + ) . PHP_EOL, + 'Directory failure must be reported with its reason.', ); - self::assertStringContainsString( - 'Reapplied "second.txt"', + Assert::same( $out->stdoutBuffer, - "After the 'Could not hash' skip, the foreach must 'continue' so 'second.txt' is still reapplied.", + ConsoleMessage::REAPPLY_APPLIED->getMessage('top.txt') . PHP_EOL + . ExpectedSummary::reapply(1, 0, 0, 1) . PHP_EOL, + 'Next entry must still be reapplied.', ); } - public function testMissingStubIsReportedAsError(): void + public function fileFilterReappliesOnlyTheMatchingEntry(): void { - $this->seedTracked('config/params.php', "stub\n", "stub\n"); - - unlink("{$this->tempDir}/vendor/pkg/name/stubs/config/params.php"); + $project = (new InspectionProject($this->tempDir)) + ->composer(['p/a']) + ->provider('p/a', ['a.txt' => "a\n", 'b.txt' => "b\n"]) + ->file('a.txt', "a\n") + ->file('b.txt', "b\n") + ->track('a.txt', 'p/a') + ->track('b.txt', 'p/a'); $out = new BufferedOutputWriter(); - (new ReapplyService())->run( - $this->tempDir, - "{$this->tempDir}/vendor", - file: 'config/params.php', - provider: '', - force: true, - out: $out, - ); - self::assertStringContainsString( - 'Stub not found', - $out->stderrBuffer, - 'When the stub is missing, an error must be reported.', + $this->reapply($project, $out, 'b.txt', force: true); + + Assert::same( + $out->stdoutBuffer, + ConsoleMessage::REAPPLY_APPLIED->getMessage('b.txt') . PHP_EOL + . ExpectedSummary::reapply(1, 0, 0, 0) . PHP_EOL, + "Only 'b.txt' must be reapplied.", ); } - public function testMissingStubSkipContinuesIterationToNextReapplicableEntry(): void + public function forceOverwritesAUserModifiedFileAndUpdatesTheLock(): void { - $this->seedTracked('first.txt', "stub\n", "stub\n"); - unlink("{$this->tempDir}/vendor/pkg/name/stubs/first.txt"); - - $this->seedTracked('second.txt', "stub\n", "stub\n"); + $project = (new InspectionProject($this->tempDir)) + ->composer(['p/a']) + ->provider('p/a', ['config/params.php' => "stub\n"]) + ->file('config/params.php', "stub\n") + ->track('config/params.php', 'p/a') + ->file('config/params.php', "user-edited\n"); $out = new BufferedOutputWriter(); - (new ReapplyService())->run( - $this->tempDir, - "{$this->tempDir}/vendor", - file: '', - provider: '', - force: true, - out: $out, - ); - self::assertStringContainsString( - 'Stub not found', - $out->stderrBuffer, - 'The missing stub must be reported as an error.', + Assert::same( + $this->reapply($project, $out, 'config/params.php', force: true), + 0, + "Exit code of a forced write must be '0'.", ); - self::assertStringContainsString( - 'Reapplied "second.txt"', + Assert::same( $out->stdoutBuffer, - "After 'Stub not found' the foreach must 'continue' so 'second.txt' can still be reapplied.", + ConsoleMessage::REAPPLY_APPLIED->getMessage('config/params.php') . PHP_EOL + . ExpectedSummary::reapply(1, 0, 0, 0) . PHP_EOL, + 'Write must be reported.', + ); + FileAssert::contentSame( + "{$this->tempDir}/config/params.php", + "stub\n", + 'Stub must overwrite the user content.', + ); + Assert::same( + $project->lock()->read(), + [ + 'providers' => ['p/a' => ['version' => '1.0.0', 'path' => 'vendor/p/a']], + 'files' => ['config/params.php' => self::writtenEntry('config/params.php', "stub\n")], + ], + 'Lock must hold the new hashes and keep the providers section.', ); } - public function testNoMatchErrorEndsWithSinglePhpEolSuffix(): void + public function forceReappliesAnEjectedEntryAndClearsTheFlag(): void { - (new LockFile($this->tempDir))->write(['providers' => [], 'files' => []]); + $project = (new InspectionProject($this->tempDir)) + ->composer(['p/a']) + ->provider('p/a', ['config/params.php' => "stub\n"]) + ->file('config/params.php', "mine\n") + ->track('config/params.php', 'p/a', extra: ['ejected' => true]); - $out = new BufferedOutputWriter(); - (new ReapplyService())->run( - $this->tempDir, - "{$this->tempDir}/vendor", - file: 'missing.php', - provider: '', - force: false, - out: $out, - ); + $this->reapply($project, new BufferedOutputWriter(), 'config/params.php', force: true); - self::assertStringEndsWith( - PHP_EOL, - $out->stderrBuffer, - "The 'No tracked files matched' error must end with PHP_EOL.", + FileAssert::contentSame( + "{$this->tempDir}/config/params.php", + "stub\n", + 'Stub must be written.', ); - self::assertStringEndsNotWith( - PHP_EOL . PHP_EOL, - $out->stderrBuffer, - "The 'No tracked files matched' error must end with exactly one PHP_EOL.", - ); - self::assertStringStartsNotWith( - PHP_EOL, - $out->stderrBuffer, - "The 'No tracked files matched' error must not be prefixed with PHP_EOL.", + Assert::same( + $project->lock()->read()['files']['config/params.php'] ?? null, + self::writtenEntry('config/params.php', "stub\n"), + "Force must clear 'ejected'.", ); } - public function testPostWriteHashFailureSkipContinuesIterationToNextReapplicableEntry(): void + /** + * Ensures force rewrites an `append` file from its stub, discarding the consumer additions. + */ + public function forceRewritesAnAppendFileFromTheStub(): void { - // 'hash_file' fails for both entries so each reapply emits its own diagnostic, proving the loop keeps iterating. - $this->seedTracked('first.txt', "new-stub\n", "user-edited\n", lockHashOf: "user-edited\n"); - $this->seedTracked('second.txt', "new-stub\n", "user-edited\n", lockHashOf: "user-edited\n"); - - MockerState::addCondition( - 'PHPForge\\Scaffold\\Scaffold\\Lock', - 'hash_file', - [], - false, - default: true, - ); + $project = (new InspectionProject($this->tempDir)) + ->composer(['p/a']) + ->provider('p/a', ['.env.dist' => "A=1\n"], ['.env.dist' => 'append']) + ->file('.env.dist', "A=1\nC=3\n") + ->track('.env.dist', 'p/a', 'append'); $out = new BufferedOutputWriter(); - (new ReapplyService())->run( - $this->tempDir, - "{$this->tempDir}/vendor", - file: '', - provider: '', - force: true, - out: $out, - ); - self::assertStringContainsString( - 'first.txt', - $out->stderrBuffer, - "The first entry must emit its own 'Could not hash written file' diagnostic naming 'first.txt'.", + $this->reapply($project, $out, '.env.dist', force: true); + + FileAssert::contentSame( + "{$this->tempDir}/.env.dist", + "A=1\n", + 'Force must discard additions.', ); - self::assertStringContainsString( - 'second.txt', - $out->stderrBuffer, - "After the first post-write hash failure, the foreach must 'continue' so 'second.txt' emits its own diagnostic.", + Assert::same( + $out->stdoutBuffer, + ConsoleMessage::REAPPLY_APPLIED->getMessage('.env.dist') . PHP_EOL + . ExpectedSummary::reapply(1, 0, 0, 0) . PHP_EOL, + 'Rewrite must be reported.', ); } - public function testPostWriteHashFailureSkipsLockUpdate(): void + public function hashFailureBeforeTheWriteContinuesToTheNextEntry(): void { - // Divergent stub vs current content so the success path would update the hash; the failure path must leave it. - $this->seedTracked( - 'config/params.php', - stubContent: "new-stub\n", - currentContent: "user-edited\n", - lockHashOf: "user-edited\n", - ); + $project = (new InspectionProject($this->tempDir)) + ->composer(['p/a']) + ->provider('p/a', ['first.txt' => "stub\n", 'second.txt' => "stub\n"]) + ->file('first.txt', "stub\n") + ->file('second.txt', "stub\n") + ->track('first.txt', 'p/a') + ->track('second.txt', 'p/a'); - $originalLockHash = 'sha256:' . hash('sha256', "user-edited\n"); + $first = PathResolver::destination($this->tempDir, 'first.txt'); - self::assertSame( - $originalLockHash, - (new LockFile($this->tempDir))->read()['files']['config/params.php']['hash'] ?? null, - 'Pre-condition: lock hash must reflect the seeded current-content hash before the reapply runs.', - ); + $this->restrictFileAccess($first, 0o000); - MockerState::addCondition( - 'PHPForge\\Scaffold\\Scaffold\\Lock', - 'hash_file', - [], - false, - default: true, - ); $out = new BufferedOutputWriter(); - (new ReapplyService())->run( - $this->tempDir, - "{$this->tempDir}/vendor", - file: 'config/params.php', - provider: '', - force: true, - out: $out, - ); - self::assertStringContainsString( - 'Could not hash', - $out->stderrBuffer, - "Post-write 'hash_file' failure must surface via the 'Could not hash' diagnostic on stderr.", - ); - self::assertSame( - $originalLockHash, - (new LockFile($this->tempDir))->read()['files']['config/params.php']['hash'] ?? null, - 'When the post-write hash throws, the lock entry must stay frozen at the pre-run hash.', + Assert::same( + $this->reapply($project, $out), + 1, + "Exit code must be '1' when a destination cannot be hashed.", ); - } - - public function testPreserveModeIsSkippedWithoutForce(): void - { - $this->seedTracked('config/web.php', "stub\n", "current\n", mode: 'preserve', lockHashOf: "stub\n"); - - $out = new BufferedOutputWriter(); - (new ReapplyService())->run( - $this->tempDir, - "{$this->tempDir}/vendor", - file: 'config/web.php', - provider: '', - force: false, - out: $out, + Assert::same( + $out->stderrBuffer, + ConsoleMessage::REAPPLY_FAILED->getMessage( + 'first.txt', + Message::FILESYSTEM_FAILED->getMessage( + Message::LOCK_HASH_FAILED->getMessage($first), + "hash_file({$first}): Failed to open stream: Permission denied", + ), + ) . PHP_EOL, + "Hash failure of 'first.txt' must be reported with its reason.", ); - - self::assertStringContainsString( - 'mode "preserve"', + Assert::same( $out->stdoutBuffer, - 'When preserve mode is active, a message must be displayed.', - ); - self::assertSame( - "current\n", - (string) file_get_contents($this->tempDir . '/config/web.php'), - 'Preserve mode must leave the on-disk content untouched without force.', + ConsoleMessage::REAPPLY_APPLIED->getMessage('second.txt') . PHP_EOL + . ExpectedSummary::reapply(1, 0, 0, 1) . PHP_EOL, + "'second.txt' must still be reapplied.", ); } - public function testPreserveModeRewritesWhenDestinationIsMissing(): void + public function hashFailureOfADirectoryDestinationContinuesToTheNextEntry(): void { - $this->seedTracked('config/web.php', "stub\n", "stub\n", mode: 'preserve'); + $project = (new InspectionProject($this->tempDir)) + ->composer(['p/a']) + ->provider('p/a', ['first.txt' => "stub\n", 'second.txt' => "stub\n"]) + ->file('second.txt', "stub\n") + ->track('first.txt', 'p/a') + ->track('second.txt', 'p/a'); - unlink($this->tempDir . '/config/web.php'); + // A directory where the destination file is expected cannot be hashed before it is overwritten. + mkdir("{$this->tempDir}/first.txt"); $out = new BufferedOutputWriter(); - (new ReapplyService())->run( - $this->tempDir, - "{$this->tempDir}/vendor", - file: 'config/web.php', - provider: '', - force: false, - out: $out, + + Assert::same( + $this->reapply($project, $out, force: true), + 1, + "Exit code must be '1' when a destination cannot be hashed.", ); - self::assertFileExists( - "{$this->tempDir}/config/web.php", - 'Preserve mode must rewrite when the destination is missing, even without force.', + // The PHP notice depends on the platform and the filesystem, so the reason is matched as a pattern. + $expected = ConsoleMessage::REAPPLY_FAILED->getMessage( + 'first.txt', + Message::FILESYSTEM_FAILED->getMessage( + Message::LOCK_HASH_FAILED->getMessage(PathResolver::destination($this->tempDir, 'first.txt')), + 'hash_file(%REASON%', + ), + ) . PHP_EOL; + + Assert::string($out->stderrBuffer)->matchesRegex( + '/\A' . str_replace('%REASON%', '.+', preg_quote($expected, '/')) . '\z/', + "Hash failure of 'first.txt' must be the only stderr line, with its reason.", ); - self::assertSame( - "stub\n", - (string) file_get_contents("{$this->tempDir}/config/web.php"), - 'Preserve mode must restore the exact stub content (not an empty file) when the destination is missing.', + Assert::same( + $out->stdoutBuffer, + ConsoleMessage::REAPPLY_APPLIED->getMessage('second.txt') . PHP_EOL + . ExpectedSummary::reapply(1, 0, 0, 1) . PHP_EOL, + "'second.txt' must still be reapplied.", ); } - public function testPreserveModeSkipNoticeEndsWithSinglePhpEolSuffix(): void + public function missingStubContinuesToTheNextEntry(): void { - $this->seedTracked('config/web.php', "stub\n", "current\n", mode: 'preserve', lockHashOf: "stub\n"); + $project = (new InspectionProject($this->tempDir)) + ->composer(['p/a']) + ->provider('p/a', ['first.txt' => "stub\n", 'second.txt' => "stub\n"]) + ->file('first.txt', "stub\n") + ->file('second.txt', "stub\n") + ->track('first.txt', 'p/a') + ->track('second.txt', 'p/a') + ->delete('vendor/p/a/stubs/first.txt'); $out = new BufferedOutputWriter(); - (new ReapplyService())->run( - $this->tempDir, - "{$this->tempDir}/vendor", - file: 'config/web.php', - provider: '', - force: false, - out: $out, - ); - self::assertStringEndsWith( - PHP_EOL, - $out->stdoutBuffer, - "The 'preserve' skip notice must end with PHP_EOL.", + Assert::same( + $this->reapply($project, $out, force: true), + 1, + "Exit code must be '1' when a stub is missing.", ); - self::assertStringEndsNotWith( - PHP_EOL . PHP_EOL, - $out->stdoutBuffer, - "The 'preserve' skip notice must end with exactly one PHP_EOL.", + Assert::same( + $out->stderrBuffer, + ConsoleMessage::REAPPLY_STUB_NOT_FOUND->getMessage( + PathResolver::source((string) realpath("{$this->tempDir}/vendor/p/a"), 'stubs/first.txt'), + ) . PHP_EOL, + 'Missing stub must be reported.', ); - self::assertStringStartsNotWith( - PHP_EOL, + Assert::same( $out->stdoutBuffer, - "The 'preserve' skip notice must not be prefixed with PHP_EOL.", + ConsoleMessage::REAPPLY_APPLIED->getMessage('second.txt') . PHP_EOL + . ExpectedSummary::reapply(1, 0, 0, 1) . PHP_EOL, + "'second.txt' must still be reapplied.", ); } - public function testPreserveSkipContinuesIterationToNextReapplicableEntry(): void + public function noFilterOnAnEmptyLockPrintsOnlyTheSummary(): void { - // Entry 1 (preserve) triggers the skip-continue; entry 2 (replace) must still be reapplied. - $this->seedTracked('config/web.php', "stub\n", "current\n", mode: 'preserve', lockHashOf: "stub\n"); - $this->seedTracked('config/params.php', "stub\n", "stub\n", mode: 'replace'); + $project = (new InspectionProject($this->tempDir))->composer(['p/a']); + + $project->lock()->write(['providers' => [], 'files' => []]); $out = new BufferedOutputWriter(); - (new ReapplyService())->run( - $this->tempDir, - "{$this->tempDir}/vendor", - file: '', - provider: '', - force: false, - out: $out, - ); - self::assertStringContainsString( - 'uses mode "preserve"', - $out->stdoutBuffer, - 'The preserve-mode entry must produce the skip diagnostic.', + Assert::same( + $this->reapply($project, $out), + 0, + "Exit code of an empty lock without filters must be '0'.", + ); + Assert::same( + $out->stderrBuffer, + '', + 'No no-match error may be written without filters.', ); - self::assertStringContainsString( - 'Reapplied "config/params.php"', + Assert::same( $out->stdoutBuffer, - "After the preserve skip, the foreach must 'continue' so the next replace-mode entry is reapplied.", + ExpectedSummary::reapply(0, 0, 0, 0) . PHP_EOL, + 'Only the summary may be printed.', ); } - public function testProviderFilterOnlyProcessesMatchingEntries(): void + public function prependAddsTheMissingBlockOnlyOnce(): void { - $this->seedTracked('a.txt', "a\n", "a\n", provider: 'pkg/a'); - $this->seedTracked('b.txt', "b\n", "b\n", provider: 'pkg/b'); + $project = (new InspectionProject($this->tempDir)) + ->composer(['p/a']) + ->provider('p/a', ['src/a.php' => "// header\n"], ['src/a.php' => 'prepend']) + ->file('src/a.php', "code\n") + ->track('src/a.php', 'p/a', 'prepend'); - $out = new BufferedOutputWriter(); - (new ReapplyService())->run( - $this->tempDir, - "{$this->tempDir}/vendor", - file: '', - provider: 'pkg/a', - force: true, - out: $out, - ); + $this->reapply($project, new BufferedOutputWriter(), 'src/a.php'); - self::assertStringContainsString( - 'Reapplied "a.txt"', - $out->stdoutBuffer, - 'Only the matching provider entries must be processed.', + $second = new BufferedOutputWriter(); + + $this->reapply($project, $second, 'src/a.php'); + + FileAssert::contentSame( + "{$this->tempDir}/src/a.php", + "// header\ncode\n", + 'Block must appear once.', ); - self::assertStringNotContainsString( - 'Reapplied "b.txt"', - $out->stdoutBuffer, - 'Non-matching provider entries must be skipped.', + Assert::same( + $second->stdoutBuffer, + ConsoleMessage::REAPPLY_ALREADY_UP_TO_DATE->getMessage('src/a.php') . PHP_EOL + . ExpectedSummary::reapply(0, 1, 0, 0) . PHP_EOL, + 'Second run must be a no-op.', ); } - public function testProviderFilterSkipOnFirstEntryContinuesIterationToNextMatchingEntry(): void + public function preserveFileIsRestoredWhenTheDestinationIsMissing(): void { - // Non-matching entry first so the provider-filter guard 'continues'; the matching entry must still be processed. - $this->seedTracked('non-match.txt', "x\n", "x\n", provider: 'pkg/other'); - $this->seedTracked('match.txt', "y\n", "y\n", provider: 'pkg/target'); + $project = (new InspectionProject($this->tempDir)) + ->composer(['p/a']) + ->provider('p/a', ['config/web.php' => "stub\n"], ['config/web.php' => 'preserve']) + ->track('config/web.php', 'p/a', 'preserve'); $out = new BufferedOutputWriter(); - (new ReapplyService())->run( - $this->tempDir, - "{$this->tempDir}/vendor", - file: '', - provider: 'pkg/target', - force: true, - out: $out, - ); - self::assertStringContainsString( - 'Reapplied "match.txt"', + $this->reapply($project, $out, 'config/web.php'); + + FileAssert::contentSame( + "{$this->tempDir}/config/web.php", + "stub\n", + 'Missing preserve file must be restored with the exact stub content.', + ); + Assert::same( $out->stdoutBuffer, - "After the provider-filter guard rejects an entry, the foreach must 'continue' so 'match.txt' is processed.", + ConsoleMessage::REAPPLY_APPLIED->getMessage('config/web.php') . PHP_EOL + . ExpectedSummary::reapply(1, 0, 0, 0) . PHP_EOL, + 'Restore must be reported.', ); } - public function testReappliedMessageEndsWithSinglePhpEolSuffix(): void + public function preserveSkipContinuesToTheNextEntry(): void { - $this->seedTracked('config/params.php', "stub\n", "stub\n"); + $project = (new InspectionProject($this->tempDir)) + ->composer(['p/a']) + ->provider( + 'p/a', + ['config/web.php' => "stub\n", 'config/params.php' => "stub\n"], + ['config/web.php' => 'preserve'], + ) + ->file('config/web.php', "current\n") + ->file('config/params.php', "stub\n") + ->track('config/web.php', 'p/a', 'preserve') + ->track('config/params.php', 'p/a'); $out = new BufferedOutputWriter(); - (new ReapplyService())->run( - $this->tempDir, - "{$this->tempDir}/vendor", - file: 'config/params.php', - provider: '', - force: true, - out: $out, - ); - self::assertStringEndsWith( - PHP_EOL, - $out->stdoutBuffer, - "The 'Reapplied' confirmation must end with PHP_EOL.", + Assert::same( + $this->reapply($project, $out), + 0, + "Exit code of a preserve skip must be '0'.", ); - self::assertStringEndsNotWith( - PHP_EOL . PHP_EOL, - $out->stdoutBuffer, - "The 'Reapplied' confirmation must end with exactly one PHP_EOL.", + Assert::same( + $out->stderrBuffer, + ConsoleMessage::REAPPLY_PRESERVE->getMessage('config/web.php') . PHP_EOL, + 'Preserve skip must be reported.', ); - self::assertStringStartsNotWith( - PHP_EOL, + Assert::same( $out->stdoutBuffer, - "The 'Reapplied' confirmation must not be prefixed with PHP_EOL.", + ConsoleMessage::REAPPLY_APPLIED->getMessage('config/params.php') . PHP_EOL + . ExpectedSummary::reapply(1, 0, 1, 0, 'preserve') . PHP_EOL, + 'Next entry must still be reapplied.', + ); + FileAssert::contentSame( + "{$this->tempDir}/config/web.php", + "current\n", + 'Preserve file must stay untouched without force.', ); } - public function testReapplySyncsSourceExecutableBitOntoDestination(): void + public function providerFilterReappliesOnlyTheMatchingEntries(): void { - if (DIRECTORY_SEPARATOR === '\\') { - self::markTestSkipped('POSIX umask-based permissions do not apply to NTFS (Windows always reports 0777).'); - } + $project = (new InspectionProject($this->tempDir)) + ->composer(['p/a', 'p/b']) + ->provider('p/a', ['a.txt' => "a\n"]) + ->provider('p/b', ['b.txt' => "b2\n"]) + ->file('a.txt', "a\n") + ->file('b.txt', "b1\n") + ->track('a.txt', 'p/a') + ->track('b.txt', 'p/b'); - $this->seedTracked('yii', "#!/usr/bin/env php\n", "#!/usr/bin/env php\n"); - - $stubPath = "{$this->tempDir}/vendor/pkg/name/stubs/yii"; - - chmod($stubPath, 0o755); - - $destination = "{$this->tempDir}/yii"; - - chmod($destination, 0o644); - - $oldUmask = umask(0o022); + $out = new BufferedOutputWriter(); - try { - $out = new BufferedOutputWriter(); - (new ReapplyService())->run( - $this->tempDir, - "{$this->tempDir}/vendor", - file: 'yii', - provider: '', - force: true, - out: $out, - ); - - self::assertSame( - 0o755, - fileperms($destination) & 0o777, - "After 'ReapplyService' rewrites the stub, 'syncPermissions' must propagate the source exec bit (0755).", - ); - } finally { - umask($oldUmask); - } - } + $this->reapply($project, $out, provider: 'p/b'); - public function testRejectsLockEntryWithUnsafeDestination(): void - { - (new LockFile($this->tempDir))->write( - [ - 'providers' => [ - 'pkg/name' => [ - 'version' => '0.1.x-dev', - 'path' => 'vendor/pkg/name', - ], - ], - 'files' => [ - '../escape.php' => [ - 'hash' => 'sha256:abc', - 'provider' => 'pkg/name', - 'source' => 'stubs/escape.php', - 'mode' => 'replace', - ], - ], - ], + Assert::same( + $out->stdoutBuffer, + ConsoleMessage::REAPPLY_APPLIED->getMessage('b.txt') . PHP_EOL + . ExpectedSummary::reapply(1, 0, 0, 0) . PHP_EOL, + "Only the entry of 'p/b' must be reapplied.", ); - - $out = new BufferedOutputWriter(); - (new ReapplyService())->run( - $this->tempDir, - "{$this->tempDir}/vendor", - file: '', - provider: '', - force: true, - out: $out, - ); - - self::assertStringContainsString( - 'Unsafe lock entry', - $out->stderrBuffer, - 'Unsafe lock entries must be reported as errors.', + FileAssert::contentSame( + "{$this->tempDir}/b.txt", + "b2\n", + "'b.txt' must be rewritten from its stub.", ); } - public function testRejectsLockEntryWithUnsafeSourceEvenWhenDestinationIsSafe(): void + public function providerPathOutsideTheVendorDirectoryIsWarned(): void { - // Safe destination + unsafe source isolates the 'validateSource' guard inside the try block. - $providerRoot = "{$this->tempDir}/vendor/pkg/name"; - - $this->ensureTestDirectory($providerRoot); - - (new LockFile($this->tempDir))->write( - [ - 'providers' => [ - 'pkg/name' => [ - 'version' => '0.1.x-dev', - 'path' => 'vendor/pkg/name', - ], - ], - 'files' => [ - 'config/params.php' => [ - 'hash' => 'sha256:abc', - 'provider' => 'pkg/name', - 'source' => '../escape.php', - 'mode' => 'replace', - ], - ], - ], - ); + $project = (new InspectionProject($this->tempDir)) + ->composer(['p/a']) + ->provider('p/a', ['config/params.php' => "stub\n"]) + ->file('config/params.php', "stub\n") + ->track('config/params.php', 'p/a'); - $out = new BufferedOutputWriter(); - (new ReapplyService())->run( - $this->tempDir, - "{$this->tempDir}/vendor", - file: '', - provider: '', - force: true, - out: $out, - ); + $data = $project->lock()->read(); - self::assertStringContainsString( - 'Unsafe lock entry', - $out->stderrBuffer, - "'validateSource' must catch the traversal source and emit the 'Unsafe lock entry' diagnostic.", - ); - } + $data['providers']['p/a'] = [ + 'version' => '1.0.0', + 'path' => '../outside-vendor', + ]; - public function testReturnsErrorWhenBothFileAndProviderFiltersAreSetButNothingMatches(): void - { - (new LockFile($this->tempDir))->write(['providers' => [], 'files' => []]); + $project->lock()->write($data); $out = new BufferedOutputWriter(); - $exitCode = (new ReapplyService())->run( - $this->tempDir, - "{$this->tempDir}/vendor", - file: 'missing.php', - provider: 'pkg/missing', - force: false, - out: $out, - ); - self::assertSame( - 1, - $exitCode, - 'When both filters are set and nothing matches, the service must emit an error exit code.', - ); - self::assertStringContainsString( - 'No tracked files matched', + $this->reapply($project, $out, 'config/params.php', force: true); + + Assert::same( $out->stderrBuffer, - 'The no-match diagnostic must be emitted when both filters are present and the lock is empty.', + ConsoleMessage::SCAFFOLD_PROVIDER_ROOT_OUTSIDE_VENDOR->getMessage('p/a') . PHP_EOL, + 'Escaping provider path must be warned about once.', ); } - public function testReturnsErrorWhenFilterMatchesNothing(): void + public function reapplySyncsTheExecutableBitOfTheStub(): void { - (new LockFile($this->tempDir))->write(['providers' => [], 'files' => []]); + if (DIRECTORY_SEPARATOR === '\\') { + throw new SkipTest('POSIX permissions do not apply to NTFS, where Windows always reports 0777.'); + } - $out = new BufferedOutputWriter(); - $exitCode = (new ReapplyService())->run( - $this->tempDir, - "{$this->tempDir}/vendor", - file: 'missing.php', - provider: '', - force: false, - out: $out, - ); + $project = (new InspectionProject($this->tempDir)) + ->composer(['p/a']) + ->provider('p/a', ['yii' => "#!/usr/bin/env php\n"]) + ->file('yii', "#!/usr/bin/env php\n") + ->track('yii', 'p/a'); - self::assertSame( - 1, - $exitCode, - 'When no tracked files match the filter, the service must return a non-zero exit code.', - ); - self::assertStringContainsString( - 'No tracked files matched', - $out->stderrBuffer, - 'An error must be reported when no files match the filter.', - ); - } + chmod("{$this->tempDir}/vendor/p/a/stubs/yii", 0o755); + chmod("{$this->tempDir}/yii", 0o644); - public function testReturnsOkWhenNoFiltersAndLockIsEmpty(): void - { - (new LockFile($this->tempDir))->write(['providers' => [], 'files' => []]); + $oldUmask = umask(0o022); - $out = new BufferedOutputWriter(); - $exitCode = (new ReapplyService())->run( - $this->tempDir, - "{$this->tempDir}/vendor", - file: '', - provider: '', - force: false, - out: $out, - ); + try { + $this->reapply($project, new BufferedOutputWriter(), 'yii', force: true); + } finally { + umask($oldUmask); + } - self::assertSame( - 0, - $exitCode, - "When no filter is supplied, running against an empty lock must be a silent no-op (no 'no match' error).", - ); - self::assertStringNotContainsString( - 'No tracked files matched', - $out->stderrBuffer, - "Without any filter, the no-match diagnostic must stay silent for users running 'reapply' on a fresh project.", + Assert::same( + fileperms("{$this->tempDir}/yii") & 0o777, + 0o755, + "Destination must get the stub mode '0755'.", ); } - public function testSkipsUserModifiedFileWithoutForce(): void + #[DataSet(['append'], 'append')] + #[DataSet(['prepend'], 'prepend')] + public function satisfiedMergeFileIsUpToDate(string $mode): void { - $this->seedTracked('config/params.php', "stub\n", "user-edited\n", lockHashOf: "stub\n"); + $file = ".env.{$mode}.dist"; + + $project = (new InspectionProject($this->tempDir)) + ->composer(['p/a']) + ->provider('p/a', [$file => "A=1\n"], [$file => $mode]) + ->file($file, "A=1\n") + ->track($file, 'p/a', $mode); $out = new BufferedOutputWriter(); - (new ReapplyService())->run( - $this->tempDir, - "{$this->tempDir}/vendor", - file: 'config/params.php', - provider: '', - force: false, - out: $out, - ); - self::assertStringContainsString( - 'user-modified', + $this->reapply($project, $out, $file); + + Assert::same( $out->stdoutBuffer, - 'When a file is user-modified and force is false, a message must be displayed.', + ConsoleMessage::REAPPLY_ALREADY_UP_TO_DATE->getMessage($file) . PHP_EOL + . ExpectedSummary::reapply(0, 1, 0, 0) . PHP_EOL, + 'Satisfied file must be reported as up to date.', ); - self::assertSame( - "user-edited\n", - (string) file_get_contents($this->tempDir . '/config/params.php'), - 'Without force the on-disk file must be preserved.', + FileAssert::contentSame( + "{$this->tempDir}/{$file}", + "A=1\n", + 'File must be untouched.', ); } - public function testStubNotFoundErrorEndsWithSinglePhpEolSuffix(): void + public function stubReadFailureContinuesToTheNextEntry(): void { - $this->seedTracked('config/params.php', "stub\n", "stub\n"); + $project = (new InspectionProject($this->tempDir)) + ->composer(['p/a']) + ->provider('p/a', ['first.txt' => "stub\n", 'second.txt' => "stub\n"]) + ->file('first.txt', "stub\n") + ->file('second.txt', "stub\n") + ->track('first.txt', 'p/a') + ->track('second.txt', 'p/a'); + + $stub = "{$this->tempDir}/vendor/p/a/stubs/first.txt"; - unlink("{$this->tempDir}/vendor/pkg/name/stubs/config/params.php"); + $this->restrictFileAccess($stub, 0o000); $out = new BufferedOutputWriter(); - (new ReapplyService())->run( - $this->tempDir, - "{$this->tempDir}/vendor", - file: 'config/params.php', - provider: '', - force: true, - out: $out, - ); - self::assertStringEndsWith( - PHP_EOL, - $out->stderrBuffer, - "The 'Stub not found' error must end with PHP_EOL.", - ); - self::assertStringEndsNotWith( - PHP_EOL . PHP_EOL, - $out->stderrBuffer, - "The 'Stub not found' error must end with exactly one PHP_EOL.", + Assert::same( + $this->reapply($project, $out, force: true), + 1, + "Exit code must be '1' when a stub cannot be read.", ); - self::assertStringStartsNotWith( - PHP_EOL, + Assert::same( $out->stderrBuffer, - "The 'Stub not found' error must not be prefixed with PHP_EOL.", - ); - } - - public function testStubReadFailureIsReportedAsError(): void - { - $this->seedTracked('config/params.php', "stub\n", "stub\n"); - - MockerState::addCondition( - 'PHPForge\\Scaffold\\Services', - 'file_get_contents', - [], - false, - default: true, - ); - $out = new BufferedOutputWriter(); - (new ReapplyService())->run( - $this->tempDir, - "{$this->tempDir}/vendor", - file: 'config/params.php', - provider: '', - force: true, - out: $out, + ConsoleMessage::REAPPLY_FAILED->getMessage( + 'first.txt', + Message::FILESYSTEM_FAILED->getMessage( + Message::MODE_COPY_FAILED->getMessage( + $stub, + PathResolver::destination($this->tempDir, 'first.txt'), + ), + "copy({$stub}): Failed to open stream: Permission denied", + ), + ) . PHP_EOL, + 'Stub read failure must be reported with its reason.', ); - - self::assertStringContainsString( - 'Could not read stub', - $out->stderrBuffer, - 'An error must be reported when a stub cannot be read.', + Assert::same( + $out->stdoutBuffer, + ConsoleMessage::REAPPLY_APPLIED->getMessage('second.txt') . PHP_EOL + . ExpectedSummary::reapply(1, 0, 0, 1) . PHP_EOL, + "'second.txt' must still be reapplied.", ); } - public function testStubReadFailureSkipContinuesIterationToNextReapplicableEntry(): void + public function throwRuntimeExceptionWhenLockContainsGitConflictMarkers(): void { - // Two entries with 'file_get_contents' mocked to fail; both must emit their own diagnostic, proving loop iteration. - $this->seedTracked('first.txt', "stub\n", "stub\n"); - $this->seedTracked('second.txt', "stub\n", "stub\n"); + $project = (new InspectionProject($this->tempDir))->composer(['p/a']); - MockerState::addCondition( - 'PHPForge\\Scaffold\\Services', - 'file_get_contents', - [], - false, - default: true, + file_put_contents( + "{$this->tempDir}/scaffold-lock.json", + "{\n<<<<<<< HEAD\n \"files\": {}\n=======\n \"files\": {\"a\": {}}\n>>>>>>> main\n}\n", ); - $out = new BufferedOutputWriter(); - (new ReapplyService())->run( - $this->tempDir, - "{$this->tempDir}/vendor", - file: '', - provider: '', - force: true, - out: $out, + Expect::exception(RuntimeException::class)->withMessage( + Message::LOCK_CONFLICT_MARKERS->getMessage((new LockFile($this->tempDir))->getPath(), 'Syntax error'), ); - self::assertStringContainsString( - 'first.txt', - $out->stderrBuffer, - "The first entry must emit its own 'Could not read stub' diagnostic naming 'first.txt'.", - ); - self::assertStringContainsString( - 'second.txt', - $out->stderrBuffer, - "After the first stub-read failure, the foreach must 'continue' so 'second.txt' emits its own diagnostic.", - ); + $this->reapply($project, new BufferedOutputWriter(), force: true); } - public function testSuccessfulReapplyUpdatesLockHashAndPreservesProvidersKey(): void + public function unknownLockModeIsAnError(): void { - // Divergent stub vs current content so a force-reapply must flip the lock hash to 'sha256(stub)'. - $this->seedTracked( - 'config/params.php', - stubContent: "new-stub\n", - currentContent: "user-edited\n", - lockHashOf: "user-edited\n", - ); - - $originalHash = 'sha256:' . hash('sha256', "user-edited\n"); - $expectedHash = 'sha256:' . hash('sha256', "new-stub\n"); - - self::assertSame( - $originalHash, - (new LockFile($this->tempDir))->read()['files']['config/params.php']['hash'] ?? null, - 'Pre-condition: lock hash must match the seeded current-content hash before the reapply runs.', - ); + $project = (new InspectionProject($this->tempDir)) + ->composer(['p/a']) + ->provider('p/a', ['a.txt' => "stub\n"]) + ->file('a.txt', "stub\n") + ->track('a.txt', 'p/a', 'copy'); $out = new BufferedOutputWriter(); - (new ReapplyService())->run( - $this->tempDir, - "{$this->tempDir}/vendor", - file: 'config/params.php', - provider: '', - force: true, - out: $out, - ); - - $data = (new LockFile($this->tempDir))->read(); - self::assertArrayHasKey( - 'config/params.php', - $data['files'], - "The reapplied destination must remain tracked in 'files' after the lock rewrite.", - ); - self::assertSame( - $expectedHash, - $data['files']['config/params.php']['hash'], - 'After a successful reapply the lock hash must reflect the newly written stub contents.', - ); - self::assertArrayHasKey( - 'pkg/name', - $data['providers'], - "The 'providers' key must survive the lock rewrite; top-level provider metadata is required downstream.", + Assert::same( + $this->reapply($project, $out), + 1, + "Exit code must be '1' for an unknown mode.", ); - - $providerEntry = $data['providers']['pkg/name'] ?? null; - - self::assertIsArray( - $providerEntry, - "The 'pkg/name' provider entry must be a structured array carrying 'version' and 'path' fields.", + Assert::same( + $out->stderrBuffer, + ConsoleMessage::REAPPLY_FAILED->getMessage('a.txt', Message::LOCK_MODE_UNKNOWN->getMessage('copy')) . PHP_EOL, + 'Unknown mode must be reported.', ); - self::assertSame( - 'vendor/pkg/name', - $providerEntry['path'] ?? null, - 'The preserved provider entry must retain its recorded install path.', + Assert::same( + $out->stdoutBuffer, + ExpectedSummary::reapply(0, 0, 0, 1) . PHP_EOL, + 'Summary must count the error.', ); } - public function testUnsafeLockEntrySkipContinuesIterationToNextFile(): void + #[DataProvider(ReapplyServiceProvider::class . '::unmatchedFilters')] + public function unmatchedFilterIsAnError(string $file, string $provider): void { - // First entry has an unsafe destination that triggers skip-continue; the second must still be reapplied. - $unsafeDestination = '../escape.php'; - $validDestination = 'config/params.php'; - - $providerRoot = "{$this->tempDir}/vendor/pkg/name"; + $project = (new InspectionProject($this->tempDir))->composer(['p/a']); - $this->ensureTestDirectory("{$providerRoot}/stubs/config"); - - file_put_contents("{$providerRoot}/stubs/config/params.php", "stub\n"); - - $this->ensureTestDirectory("{$this->tempDir}/config"); - - file_put_contents("{$this->tempDir}/config/params.php", "stub\n"); - - (new LockFile($this->tempDir))->write( - [ - 'providers' => [ - 'pkg/name' => [ - 'version' => '0.1.x-dev', - 'path' => 'vendor/pkg/name', - ], - ], - 'files' => [ - $unsafeDestination => [ - 'hash' => 'sha256:abc', - 'provider' => 'pkg/name', - 'source' => 'stubs/escape.php', - 'mode' => 'replace', - ], - $validDestination => [ - 'hash' => 'sha256:' . hash('sha256', "stub\n"), - 'provider' => 'pkg/name', - 'source' => 'stubs/config/params.php', - 'mode' => 'replace', - ], - ], - ], - ); + $project->lock()->write(['providers' => [], 'files' => []]); $out = new BufferedOutputWriter(); - (new ReapplyService())->run( - $this->tempDir, - "{$this->tempDir}/vendor", - file: '', - provider: '', - force: true, - out: $out, - ); - self::assertStringContainsString( - 'Unsafe lock entry', + Assert::same( + $this->reapply($project, $out, $file, $provider), + 1, + "Exit code must be '1' when no tracked file matches.", + ); + Assert::same( $out->stderrBuffer, - 'The unsafe entry must be surfaced via stderr as an error.', + ConsoleMessage::REAPPLY_NO_MATCH->getMessage() . PHP_EOL, + 'No-match error must be the only stderr line.', ); - self::assertStringContainsString( - 'Reapplied "config/params.php"', + Assert::same( $out->stdoutBuffer, - 'After the unsafe entry triggers the skip branch, the foreach must keep iterating to reapply the valid entry.', + '', + 'No summary may be printed.', ); } - public function testUserModifiedSkipContinuesIterationToNextReapplicableEntry(): void - { - // Entry 1 (user-modified) triggers skip-continue; entry 2 (in-sync replace) must still be reapplied. - $this->seedTracked('config/params.php', "stub\n", "user-edited\n", lockHashOf: "stub\n"); - $this->seedTracked('config/web.php', "stub\n", "stub\n"); + /** + * @param array $extra Extra lock entry keys of the unsafe entry. + */ + #[DataProvider(ReapplyServiceProvider::class . '::unsafeEntries')] + public function unsafeEntryContinuesToTheNextEntry( + string $destination, + array $extra, + string $kind, + string $value, + ): void { + $project = (new InspectionProject($this->tempDir)) + ->composer(['p/a']) + ->provider('p/a', ['a.txt' => "a\n", 'b.txt' => "b2\n"]) + ->file('a.txt', "a\n") + ->file('b.txt', "b1\n") + ->track($destination, 'p/a', extra: $extra) + ->track('b.txt', 'p/a'); $out = new BufferedOutputWriter(); - (new ReapplyService())->run( - $this->tempDir, - "{$this->tempDir}/vendor", - file: '', - provider: '', - force: false, - out: $out, - ); - self::assertStringContainsString( - 'user-modified', - $out->stdoutBuffer, - 'The user-modified entry must produce the skip diagnostic.', + Assert::same( + $this->reapply($project, $out), + 1, + "Exit code must be '1' for an unsafe entry.", + ); + Assert::same( + $out->stderrBuffer, + ConsoleMessage::REAPPLY_UNSAFE_ENTRY->getMessage( + $destination, + Message::PATH_TRAVERSAL->getMessage($kind, $value), + ) . PHP_EOL, + 'Unsafe entry must be reported.', ); - self::assertStringContainsString( - 'Reapplied "config/web.php"', + Assert::same( $out->stdoutBuffer, - "After 'is user-modified' the foreach must 'continue' so the next in-sync entry is reapplied.", + ConsoleMessage::REAPPLY_APPLIED->getMessage('b.txt') . PHP_EOL + . ExpectedSummary::reapply(1, 0, 0, 1) . PHP_EOL, + "'b.txt' must still be reapplied.", ); } - public function testWriteFailureIsReportedAsError(): void + public function userModifiedSkipContinuesToTheNextEntry(): void { - $this->seedTracked('config/params.php', "stub\n", "stub\n"); + $project = (new InspectionProject($this->tempDir)) + ->composer(['p/a']) + ->provider('p/a', ['config/params.php' => "stub\n", 'config/web.php' => "stub\n"]) + ->file('config/params.php', "stub\n") + ->file('config/web.php', "stub\n") + ->track('config/params.php', 'p/a') + ->track('config/web.php', 'p/a') + ->file('config/params.php', "user-edited\n"); - MockerState::addCondition( - 'PHPForge\\Scaffold\\Services', - 'file_put_contents', - [], - false, - default: true, - ); $out = new BufferedOutputWriter(); - (new ReapplyService())->run( - $this->tempDir, - "{$this->tempDir}/vendor", - file: 'config/params.php', - provider: '', - force: true, - out: $out, - ); - - self::assertStringContainsString( - 'Could not write', - $out->stderrBuffer, - 'An error must be reported when a file cannot be written.', - ); - } - public function testWriteFailureSkipContinuesIterationToNextReapplicableEntry(): void - { - // Mock 'file_put_contents' to fail for both entries; each must emit its own diagnostic, proving loop iteration. - $this->seedTracked('first.txt', "stub\n", "stub\n"); - $this->seedTracked('second.txt', "stub\n", "stub\n"); - - MockerState::addCondition( - 'PHPForge\\Scaffold\\Services', - 'file_put_contents', - [], - false, - default: true, - ); - - $out = new BufferedOutputWriter(); - (new ReapplyService())->run( - $this->tempDir, - "{$this->tempDir}/vendor", - file: '', - provider: '', - force: true, - out: $out, + Assert::same( + $this->reapply($project, $out), + 0, + "Exit code of a user-modified skip must be '0'.", ); - - self::assertStringContainsString( - 'first.txt', + Assert::same( $out->stderrBuffer, - "The first entry must emit its own 'Could not write' diagnostic naming 'first.txt'.", + ConsoleMessage::REAPPLY_USER_MODIFIED->getMessage('config/params.php') . PHP_EOL, + 'User-modified skip must be reported.', ); - self::assertStringContainsString( - 'second.txt', - $out->stderrBuffer, - "After the first write failure, the foreach must 'continue' so the second entry still emits a diagnostic.", + Assert::same( + $out->stdoutBuffer, + ConsoleMessage::REAPPLY_APPLIED->getMessage('config/web.php') . PHP_EOL + . ExpectedSummary::reapply(1, 0, 1, 0, 'user-modified') . PHP_EOL, + 'Next entry must still be reapplied.', ); - } - - protected function setUp(): void - { - $this->setUpTempDirectory(); - } - - protected function tearDown(): void - { - $this->tearDownTempDirectory(); - } - - private function seedTracked( - string $destination, - string $stubContent, - string $currentContent, - string $mode = 'replace', - string $provider = 'pkg/name', - string|null $lockHashOf = null, - ): void { - $providerRoot = "{$this->tempDir}/vendor/{$provider}"; - - $stubRelative = "stubs/$destination"; - $stubPath = "$providerRoot/$stubRelative"; - - $this->ensureTestDirectory(dirname($stubPath)); - - file_put_contents($stubPath, $stubContent); - - $destAbsolute = $this->tempDir . '/' . $destination; - - $this->ensureTestDirectory(dirname($destAbsolute)); - - file_put_contents($destAbsolute, $currentContent); - - $hasher = new Hasher(); - - $lockHash = $lockHashOf !== null - ? 'sha256:' . hash('sha256', $lockHashOf) - : $hasher->hash($destAbsolute); - - $lock = new LockFile($this->tempDir); - - $data = is_file("{$this->tempDir}/scaffold-lock.json") ? $lock->read() : ['providers' => [], 'files' => []]; - - $data['providers'][$provider] = [ - 'version' => '0.1.x-dev', - 'path' => "vendor/{$provider}", - ]; - $data['files'][$destination] = [ - 'hash' => $lockHash, - 'provider' => $provider, - 'source' => $stubRelative, - 'mode' => $mode, + FileAssert::contentSame( + "{$this->tempDir}/config/params.php", + "user-edited\n", + 'User content must be kept without force.', + ); + } + + /** + * Runs `reapply` over the project without dry run. + */ + private function reapply( + InspectionProject $project, + BufferedOutputWriter $out, + string $file = '', + string $provider = '', + bool $force = false, + ): int { + return (new ReapplyService())->run($project->context(), $out, $file, $provider, $force); + } + + /** + * Returns the lock entry recorded after `$destination` of provider `p/a` was written from a stub with `$stub`. + * + * @return array Expected `replace` lock entry. + */ + private static function writtenEntry(string $destination, string $stub): array + { + $hash = 'sha256:' . hash('sha256', $stub); + + return [ + 'hash' => $hash, + 'provider' => 'p/a', + 'source' => "stubs/{$destination}", + 'mode' => 'replace', + 'stub-hash' => $hash, ]; - - $lock->write($data); } } diff --git a/tests/Services/StatusServiceTest.php b/tests/Services/StatusServiceTest.php index d915d3a..9333076 100644 --- a/tests/Services/StatusServiceTest.php +++ b/tests/Services/StatusServiceTest.php @@ -4,493 +4,508 @@ namespace PHPForge\Scaffold\Tests\Services; -use PHPForge\Scaffold\Scaffold\Lock\{Hasher, LockFile}; +use Closure; +use PHPForge\Scaffold\Config\ProjectContext; +use PHPForge\Scaffold\Console\Message as ConsoleMessage; +use PHPForge\Scaffold\Exception\Message; use PHPForge\Scaffold\Services\StatusService; -use PHPForge\Scaffold\Tests\Support\{BufferedOutputWriter, TempDirectoryTrait}; -use PHPUnit\Framework\Attributes\Group; -use PHPUnit\Framework\TestCase; -use Xepozz\InternalMocker\MockerState; +use PHPForge\Scaffold\Tests\Provider\StatusServiceProvider; +use PHPForge\Scaffold\Tests\Support\{BufferedOutputWriter, FileAssert, InspectionProject, TempDirectoryTrait}; +use RuntimeException; +use Testo\Assert; +use Testo\Codecov\Covers; +use Testo\Core\Exception\SkipTest; +use Testo\Data\DataProvider; +use Testo\Expect; +use Testo\Test; + +use function array_keys; +use function array_map; +use function implode; +use function json_decode; +use function str_repeat; +use function symlink; +use function unlink; /** - * Unit tests for {@see StatusService} covering the status-computation branches and rendered output. + * Unit tests for {@see StatusService} covering the state model per mode, provider drift, the JSON report and the exit + * codes. + * + * {@see StatusServiceProvider} for test case data providers. */ -#[Group('scaffold')] -#[Group('services')] -final class StatusServiceTest extends TestCase +#[Test] +#[Covers(StatusService::class)] +final class StatusServiceTest { use TempDirectoryTrait; - public function testGetStatusesContinuesPastErrorEntryToReportSubsequentValidEntries(): void + public function driftLineReportsLockAndInstalledVersions(): void { - $filePath = "{$this->tempDir}/valid.txt"; + $project = $this->project() + ->provider('p/a', ['a.txt' => "a\n"]) + ->file('a.txt', "a\n") + ->track('a.txt', 'p/a', version: '0.2.0') + ->installed(['p/a' => '0.3.0']); - file_put_contents($filePath, 'stub content'); + $out = new BufferedOutputWriter(); - $hash = (new Hasher())->hash($filePath); - (new LockFile($this->tempDir))->write( - [ - 'providers' => [], - 'files' => [ - // First entry fails validation (path traversal) and must emit 'error' while the loop continues. - '../escape.php' => [ - 'hash' => 'sha256:abc', - 'provider' => 'pkg/name', - 'source' => 'stubs/escape.php', - 'mode' => 'replace', - ], - // Second entry must still be reported after the first hit the error-continue path. - 'valid.txt' => [ - 'hash' => $hash, - 'provider' => 'pkg/name', - 'source' => 'stubs/valid.txt', - 'mode' => 'replace', - ], - ], - ], + (new StatusService()) + ->run($project->context(), $out); + + Assert::same( + $out->stderrBuffer, + ConsoleMessage::STATUS_PROVIDER_DRIFT->getMessage('p/a', '0.2.0', '0.3.0') . PHP_EOL, + 'Drift must be the only stderr line.', ); + } - $statuses = (new StatusService())->getStatuses($this->tempDir); + public function ejectedEntryOfProviderNoLongerAllowedProducesNoNotice(): void + { + $this->project() + ->file('e.txt', "mine\n") + ->track('e.txt', 'p/denied', extra: ['ejected' => true]); - self::assertArrayHasKey( - '../escape.php', - $statuses, - "Invalid entries must still appear in the status map (with status 'error') so the CLI can surface them.", - ); - self::assertArrayHasKey( - 'valid.txt', - $statuses, - "An earlier unsafe-destination entry must not 'break' the foreach; the next valid entry must still report.", - ); - self::assertSame( - 'synced', - $statuses['valid.txt']['status'] ?? null, - "The second entry's status must be computed (here 'synced'), confirming the loop kept iterating.", + $out = new BufferedOutputWriter(); + + (new StatusService()) + ->run(ProjectContext::create($this->tempDir), $out); + + Assert::same( + $out->stderrBuffer, + '', + 'Ejected entries belong to the user.', ); } - public function testGetStatusesMarksEntryAsErrorWhenDestinationIsUnsafe(): void + public function entryWithUnreadableDestinationIsError(): void { - (new LockFile($this->tempDir))->write( - [ - 'providers' => [], - 'files' => [ - '../escape.php' => [ - 'hash' => 'sha256:abc', - 'provider' => 'pkg/name', - 'source' => 'stubs/escape.php', - 'mode' => 'replace', - ], - ], - ], - ); + $project = $this->project() + ->provider('p/a', ['a.txt' => "a\n"]) + ->file('a.txt', "a\n") + ->track('a.txt', 'p/a'); - $statuses = (new StatusService())->getStatuses($this->tempDir); + $this->restrictFileAccess("{$this->tempDir}/a.txt", 0o000); - self::assertSame( - 'error', - $statuses['../escape.php']['status'] ?? null, - 'Lock entries whose destination fails path validation must surface status "error".', + Assert::same( + $this->states($project), + ['a.txt' => 'error'], + "Unreadable destination must be in the 'error' state.", ); } - public function testGetStatusesMarksEntryAsErrorWhenHashThrows(): void + public function expectedFilesWithoutLockEntryArePending(): void { - $filePath = "{$this->tempDir}/unreadable.txt"; + $project = $this->project() + ->provider('p/a', ['a.txt' => "a\n", 'new.txt' => "new\n"]) + ->file('a.txt', "a\n") + ->track('a.txt', 'p/a'); - file_put_contents($filePath, 'content'); + $out = new BufferedOutputWriter(); - (new LockFile($this->tempDir))->write( - [ - 'providers' => [], - 'files' => [ - 'unreadable.txt' => [ - 'hash' => 'sha256:abc', - 'provider' => 'pkg/name', - 'source' => 'stubs/unreadable.txt', - 'mode' => 'replace', - ], - ], - ], - ); - MockerState::addCondition( - 'PHPForge\\Scaffold\\Scaffold\\Lock', - 'is_readable', - [], - false, - default: true, + Assert::same( + (new StatusService())->run($project->context(), $out, false, true), + 1, + "Exit code must be '1' for pending files with '--exit-code'.", ); - $statuses = (new StatusService())->getStatuses($this->tempDir); - - self::assertSame( - 'error', - $statuses['unreadable.txt']['status'] ?? null, - "When 'hash' throws because the file is unreadable, the destination must surface with status 'error'.", + Assert::same( + $out->stdoutBuffer, + 'File Provider Mode Status' . PHP_EOL + . str_repeat('-', 35) . PHP_EOL + . 'a.txt p/a replace synced' . PHP_EOL + . 'new.txt p/a replace pending' . PHP_EOL + . self::summary(2, ['synced' => 1, 'pending' => 1]) . PHP_EOL, + 'Untracked provider file must be listed as pending and counted.', ); } - - public function testGetStatusesReturnsAllEntriesUnchangedWithoutSlicingToTheFirst(): void + public function jsonReportContainsFilesProvidersAndSummaryOnly(): void { - $first = "{$this->tempDir}/first.txt"; - $second = "{$this->tempDir}/second.txt"; - - file_put_contents($first, 'first content'); - file_put_contents($second, 'second content'); + $project = $this->project() + ->provider('p/a', ['a.txt' => "a\n", 'b.txt' => "b\n"]) + ->file('a.txt', "a\n") + ->file('b.txt', "b\n") + ->track('a.txt', 'p/a', version: '0.2.0') + ->track('b.txt', 'p/a', version: '0.2.0') + ->file('b.txt', "mine\n") + ->installed(['p/a' => '0.3.0']); - $hasher = new Hasher(); + $out = new BufferedOutputWriter(); - (new LockFile($this->tempDir))->write( + Assert::same( + (new StatusService())->run($project->context(), $out, true), + 0, + "Exit code must be '0': JSON output alone does not fail.", + ); + Assert::same( + json_decode($out->stdoutBuffer, true, flags: JSON_THROW_ON_ERROR), [ - 'providers' => [], 'files' => [ - 'first.txt' => [ - 'hash' => $hasher->hash($first), - 'provider' => 'pkg/name', - 'source' => 'stubs/first.txt', - 'mode' => 'replace', - ], - 'second.txt' => [ - 'hash' => $hasher->hash($second), - 'provider' => 'pkg/name', - 'source' => 'stubs/second.txt', - 'mode' => 'replace', - ], + 'a.txt' => ['provider' => 'p/a', 'mode' => 'replace', 'status' => 'synced'], + 'b.txt' => ['provider' => 'p/a', 'mode' => 'replace', 'status' => 'modified'], + ], + 'providers' => ['p/a' => ['lock' => '0.2.0', 'installed' => '0.3.0']], + 'summary' => [ + 'total' => 2, + 'synced' => 1, + 'pending' => 0, + 'outdated' => 0, + 'modified' => 1, + 'conflict' => 0, + 'missing' => 0, + 'orphan' => 0, + 'ejected' => 0, + 'error' => 0, ], ], + 'Stdout must hold only the JSON document.', ); - - $statuses = (new StatusService())->getStatuses($this->tempDir); - - self::assertCount( - 2, - $statuses, - 'The status map must contain every tracked entry; dropping rows would mislead the CLI.', - ); - self::assertArrayHasKey( - 'second.txt', - $statuses, - 'The second entry must be present; keeping only the first would mask out subsequent rows.', + Assert::same( + $out->stderrBuffer, + '', + 'Drift is part of the JSON document, not a stderr line.', ); } - public function testGetStatusesReturnsEmptyArrayWhenNoLockFile(): void + public function jsonReportOfEmptyLockUsesObjects(): void { - self::assertSame( - [], - (new StatusService())->getStatuses($this->tempDir), - 'Expected empty array when no lock file is present.', - ); - } + $out = new BufferedOutputWriter(); - public function testGetStatusesReturnsMissingWhenFileAbsentFromDisk(): void - { - (new LockFile($this->tempDir))->write( - [ - 'providers' => [], - 'files' => [ - 'config/params.php' => [ - 'hash' => 'sha256:abc', - 'provider' => 'pkg/name', - 'source' => 'stubs/config/params.php', - 'mode' => 'replace', - ], - ], - ], - ); + (new StatusService()) + ->run($this->project()->context(), $out, true); - self::assertSame( - 'missing', - (new StatusService())->getStatuses($this->tempDir)['config/params.php']['status'] ?? null, - "Expected status 'missing' when the destination file is absent from disk.", + Assert::same( + $out->stdoutBuffer, + "{\n \"files\": {},\n \"providers\": {},\n \"summary\": {\n \"total\": 0,\n" + . " \"synced\": 0,\n \"pending\": 0,\n \"outdated\": 0,\n \"modified\": 0,\n" + . " \"conflict\": 0,\n \"missing\": 0,\n \"orphan\": 0,\n \"ejected\": 0,\n" + . " \"error\": 0\n }\n}" . PHP_EOL, + "Empty 'files' and 'providers' must encode as objects.", ); } - - public function testGetStatusesReturnsModifiedWhenHashDiffers(): void + public function notAllowedProviderIsReported(): void { - $filePath = "{$this->tempDir}/output.txt"; + $project = $this->project() + ->provider('p/denied', ['d.txt' => "d\n"]) + ->file('d.txt', "d\n") + ->track('d.txt', 'p/denied'); - file_put_contents($filePath, 'user-modified content'); + $out = new BufferedOutputWriter(); - (new LockFile($this->tempDir))->write( - [ - 'providers' => [], - 'files' => [ - 'output.txt' => [ - 'hash' => 'sha256:' . hash('sha256', 'original stub content'), - 'provider' => 'pkg/name', - 'source' => 'stubs/output.txt', - 'mode' => 'replace', - ], - ], - ], - ); + (new StatusService()) + ->run($project->context(), $out); - self::assertSame( - 'modified', - (new StatusService())->getStatuses($this->tempDir)['output.txt']['status'] ?? null, - "Expected status 'modified' when the on-disk hash differs from the recorded hash.", + Assert::same( + $out->stderrBuffer, + ConsoleMessage::COMMAND_PROVIDER_NOT_ALLOWED->getMessage('d.txt', 'p/denied') . PHP_EOL, + 'Allowlist rejection must be the only stderr line.', ); } - public function testGetStatusesReturnsSyncedWhenHashMatches(): void + public function noticeIsPrintedOnceForEntriesWithoutStubHash(): void { - $filePath = "{$this->tempDir}/output.txt"; + $project = $this->project() + ->provider('p/a', ['a.txt' => "a\n", 'b.txt' => "b\n"]) + ->file('a.txt', "a\n") + ->file('b.txt', "b\n") + ->track('a.txt', 'p/a', extra: ['stub-hash' => null]) + ->track('b.txt', 'p/a', extra: ['stub-hash' => null]); - file_put_contents($filePath, 'stub content'); + $out = new BufferedOutputWriter(); - $hash = (new Hasher())->hash($filePath); - (new LockFile($this->tempDir))->write( - [ - 'providers' => [], - 'files' => [ - 'output.txt' => [ - 'hash' => $hash, - 'provider' => 'pkg/name', - 'source' => 'stubs/output.txt', - 'mode' => 'preserve', - ], - ], - ], - ); + (new StatusService()) + ->run($project->context(), $out); - self::assertSame( - 'synced', - (new StatusService())->getStatuses($this->tempDir)['output.txt']['status'] ?? null, - "Expected status 'synced' when the on-disk hash matches the recorded hash.", + Assert::same( + $out->stderrBuffer, + ConsoleMessage::STATUS_STUB_HASH_MISSING->getMessage( + 2, + ConsoleMessage::FRAGMENT_ENTRIES_LACK->getMessage(), + ) . PHP_EOL, + 'One notice must cover every legacy entry.', + ); + Assert::same( + $this->states($project), + ['a.txt' => 'synced', 'b.txt' => 'synced'], + "Legacy entries identical to their stubs must be 'synced'.", ); } - public function testRunEmptyStatusMessageEndsWithSinglePhpEolSuffix(): void + public function pendingFilesAreListedWithoutLock(): void { - (new LockFile($this->tempDir))->write(['providers' => [], 'files' => []]); + $project = $this->project()->provider('p/a', ['a.txt' => "a\n"]); $out = new BufferedOutputWriter(); - (new StatusService())->run($this->tempDir, $out); - self::assertStringEndsWith( - PHP_EOL, - $out->stdoutBuffer, - "The 'No files tracked' empty-state message must end with PHP_EOL.", + Assert::same( + (new StatusService())->run($project->context(), $out), + 0, + "Exit code must be '0': pending alone is not an error.", ); - self::assertStringEndsNotWith( - PHP_EOL . PHP_EOL, + Assert::same( $out->stdoutBuffer, - "The 'No files tracked' message must end with exactly one PHP_EOL.", + 'File Provider Mode Status' . PHP_EOL + . str_repeat('-', 33) . PHP_EOL + . 'a.txt p/a replace pending' . PHP_EOL + . self::summary(1, ['pending' => 1]) . PHP_EOL, + 'Pending row must be listed.', ); - self::assertStringStartsNotWith( - PHP_EOL, - $out->stdoutBuffer, - "The 'No files tracked' empty-state message must not be prefixed with PHP_EOL.", + FileAssert::fileDoesNotExist( + "{$this->tempDir}/scaffold-lock.json", + 'Status must not create the lock.', ); } - public function testRunHeaderEndsWithSinglePhpEolSuffix(): void + /** + * @param Closure(InspectionProject): void $arrange Arranges the project. + * @param array $expected Expected states keyed by destination. + */ + #[DataProvider(StatusServiceProvider::class . '::states')] + public function reportsTheStateOfEveryFile(Closure $arrange, array $expected, int $exitCode): void { - $filePath = "{$this->tempDir}/output.txt"; + $project = $this->project(); - file_put_contents($filePath, 'content'); + $arrange($project); - $hash = (new Hasher())->hash($filePath); - (new LockFile($this->tempDir))->write( - [ - 'providers' => [], - 'files' => [ - 'output.txt' => [ - 'hash' => $hash, - 'provider' => 'pkg/name', - 'source' => 'stubs/output.txt', - 'mode' => 'replace', - ], - ], - ], + Assert::same( + $this->states($project), + $expected, + 'States of the files must match.', + ); + Assert::same( + (new StatusService())->run($project->context(), new BufferedOutputWriter(), exitCode: true), + $exitCode, + "Exit code with '--exit-code' must follow the states.", ); + } + + public function runPadsTheStatusColumnToItsMinimumWidth(): void + { + $this->project()->track('../evil', 'p/a'); $out = new BufferedOutputWriter(); - (new StatusService())->run($this->tempDir, $out); - self::assertStringStartsWith( - 'File', - $out->stdoutBuffer, - "The rendered status table must start with the 'File' header, not a stray leading PHP_EOL.", - ); - self::assertStringEndsWith( - PHP_EOL, - $out->stdoutBuffer, - 'The final row must be terminated by PHP_EOL so shells render it on its own line.', - ); - self::assertStringEndsNotWith( - PHP_EOL . PHP_EOL, + (new StatusService()) + ->run(ProjectContext::create($this->tempDir), $out); + + Assert::same( $out->stdoutBuffer, - 'The final row must end with exactly one PHP_EOL.', + 'File Provider Mode Status' . PHP_EOL + . str_repeat('-', 34) . PHP_EOL + . '../evil p/a replace error' . PHP_EOL + . self::summary(1, ['error' => 1]) . PHP_EOL, + 'Status column must be at least six characters wide.', ); } - public function testRunPinsColStatusToLiteralSixWhenObservedStatusIsShorter(): void + public function runPrintsEmptyMessageWhenNoFilesTracked(): void { - // 'getStatuses' returns status='error' (length 5); separator width therefore depends on the 'max(6,...)' literal. - (new LockFile($this->tempDir))->write( - [ - 'providers' => [], - 'files' => [ - '../x' => [ - 'hash' => 'sha256:abc', - 'provider' => 'p', - 'source' => 'stubs/x', - 'mode' => 'x', - ], - ], - ], - ); + $this->project(); $out = new BufferedOutputWriter(); - (new StatusService())->run($this->tempDir, $out); - // colFile=max(4, len('../x')=4)=4, colProvider=max(8,1)=8, colMode=max(4,1)=4, colStatus=max(6, 5)=6 - // Separator width = 4 + 8 + 4 + 6 + 6 = 28 dashes. - self::assertStringContainsString( - PHP_EOL . str_repeat('-', 28) . PHP_EOL, - $out->stdoutBuffer, - "The separator row must be exactly 28 dashes on its own line when status='error' pins colStatus to 6.", - ); - self::assertStringNotContainsString( - PHP_EOL . str_repeat('-', 27) . PHP_EOL, - $out->stdoutBuffer, - 'The separator must not collapse to 27 dashes.', + Assert::same( + (new StatusService())->run(ProjectContext::create($this->tempDir), $out, false, true), + 0, + "Exit code must be '0': an empty lock is clean.", ); - self::assertStringNotContainsString( - PHP_EOL . str_repeat('-', 29) . PHP_EOL, + Assert::same( $out->stdoutBuffer, - 'The separator must not widen to 29 dashes.', + ConsoleMessage::STATUS_NO_FILES->getMessage() . PHP_EOL, + 'Empty message must be the only output.', ); } - public function testRunPrintsEmptyMessageWhenNoFilesTracked(): void + public function runPrintsTableAndSummaryLine(): void { - (new LockFile($this->tempDir))->write(['providers' => [], 'files' => []]); + $this->project() + ->provider('p/a', ['a' => "a\n", 'b' => "b\n", 'c' => "c\n"]) + ->file('a', "a\n") + ->file('b', "b\n") + ->file('c', "c\n") + ->track('a', 'p/a') + ->track('b', 'p/a') + ->track('c', 'p/a') + ->file('b', "mine\n") + ->stub('p/a', 'c', "c2\n"); $out = new BufferedOutputWriter(); - $exitCode = (new StatusService())->run($this->tempDir, $out); - self::assertSame( + Assert::same( + (new StatusService())->run(ProjectContext::create($this->tempDir), $out), 0, - $exitCode, - "Expected exit code '0' when no files are tracked, indicating successful execution.", + "Exit code must be '0': drift does not fail without '--exit-code'.", ); - self::assertStringContainsString( - 'No files tracked in scaffold-lock.json', + Assert::same( $out->stdoutBuffer, - "Expected message indicating no files are tracked when 'scaffold-lock.json' is empty.", + 'File Provider Mode Status' . PHP_EOL + . str_repeat('-', 33) . PHP_EOL + . 'a p/a replace synced' . PHP_EOL + . 'b p/a replace modified' . PHP_EOL + . 'c p/a replace outdated' . PHP_EOL + . self::summary(3, ['synced' => 1, 'outdated' => 1, 'modified' => 1]) . PHP_EOL, + 'Table rows and summary must match.', ); } - public function testRunPrintsHeaderAndRowsForTrackedFiles(): void + public function runReturnsErrorWhenAnyEntryIsInErrorState(): void { - $filePath = "{$this->tempDir}/output.txt"; - - file_put_contents($filePath, 'synced content'); - - $hash = (new Hasher())->hash($filePath); - (new LockFile($this->tempDir))->write( - [ - 'providers' => [], - 'files' => [ - 'output.txt' => [ - 'hash' => $hash, - 'provider' => 'pkg/name', - 'source' => 'stubs/output.txt', - 'mode' => 'replace', - ], - ], - ], + $this + ->project() + ->provider('p/a', ['a.txt' => "a\n"]) + ->file('a.txt', "a\n") + ->track('a.txt', 'p/a') + ->track('../evil', 'p/a'); + + Assert::same( + (new StatusService())->run(ProjectContext::create($this->tempDir), new BufferedOutputWriter()), + 1, + "Exit code must be '1' for an 'error' state.", ); + } + + public function runSizesTheStatusColumnByItsLongestValue(): void + { + $this + ->project() + ->provider('p/a', ['a' => "a\n"]) + ->file('a', "a\n") + ->track('a', 'p/a'); $out = new BufferedOutputWriter(); - $exitCode = (new StatusService())->run($this->tempDir, $out); - self::assertSame( - 0, - $exitCode, - "Expected exit code '0' when files are tracked, indicating successful execution.", - ); - self::assertStringContainsString( - 'File', - $out->stdoutBuffer, - "Expected header 'File' to be printed for tracked files.", - ); - self::assertStringContainsString( - 'Provider', - $out->stdoutBuffer, - "Expected header 'Provider' to be printed for tracked files.", - ); - self::assertStringContainsString( - 'Mode', - $out->stdoutBuffer, - "Expected header 'Mode' to be printed for tracked files.", - ); - self::assertStringContainsString( - 'Status', - $out->stdoutBuffer, - "Expected header 'Status' to be printed for tracked files.", - ); - self::assertStringContainsString( - 'output.txt', - $out->stdoutBuffer, - "Expected tracked file 'output.txt' to be listed.", - ); - self::assertStringContainsString( - 'synced', + (new StatusService()) + ->run(ProjectContext::create($this->tempDir), $out); + + Assert::same( $out->stdoutBuffer, - "Expected status 'synced' to be printed for tracked file 'output.txt'.", + 'File Provider Mode Status' . PHP_EOL + . str_repeat('-', 31) . PHP_EOL + . 'a p/a replace synced' . PHP_EOL + . self::summary(1, ['synced' => 1]) . PHP_EOL, + 'Separator must cover a six-character status column.', ); } - public function testRunRendersSeparatorRowWithWidthExactlyMatchingColumnLiteralsPlusSixPaddingForShortData(): void + public function stubSymlinkEscapingTheProviderIsError(): void { - $filePath = "{$this->tempDir}/a"; + $project = $this->project() + ->provider('p/a', ['a.txt' => "a\n"]) + ->file('a.txt', "a\n") + ->track('a.txt', 'p/a') + ->file('outside.txt', "a\n"); - file_put_contents($filePath, 'c'); + unlink("{$this->tempDir}/vendor/p/a/stubs/a.txt"); - $hash = (new Hasher())->hash($filePath); + if (@symlink("{$this->tempDir}/outside.txt", "{$this->tempDir}/vendor/p/a/stubs/a.txt") === false) { + throw new SkipTest('Symbolic links are not available.'); + } - // All fields shorter than the column literals (4/8/4/6) so the separator width depends solely on those literals. - (new LockFile($this->tempDir))->write( - [ - 'providers' => [], - 'files' => [ - 'a' => [ - 'hash' => $hash, - 'provider' => 'p', - 'source' => 'stubs/a', - 'mode' => 'x', - // ^ artificial short mode; status is computed from disk state (synced/missing/modified/error). - ], - ], - ], + Assert::same( + $this->states($project), + ['a.txt' => 'error'], + "Escaping stub must be in the 'error' state.", ); + } + + public function throwRuntimeExceptionWhenJsonReportCannotBeEncoded(): void + { + $project = $this + ->project() + ->provider('p/a', ['a.txt' => "a\n"]) + ->file('a.txt', "a\n") + ->track('a.txt', 'p/a') + ->installed(['p/a' => "\xB1"]); + + Expect::exception(RuntimeException::class) + ->withMessage( + Message::SERVICE_STATUS_ENCODE_FAILED->getMessage( + 'Malformed UTF-8 characters, possibly incorrectly encoded', + ), + ) + ->withCode(0); + + (new StatusService())->run($project->context(), new BufferedOutputWriter(), true); + } + + public function throwRuntimeExceptionWhenProjectManifestIsMissing(): void + { + Expect::exception(RuntimeException::class) + ->withMessage( + Message::CONFIG_MANIFEST_NOT_FOUND->getMessage("{$this->tempDir}/vendor/composer.json"), + ); + + (new StatusService())->run(ProjectContext::create("{$this->tempDir}/vendor"), new BufferedOutputWriter()); + } + + public function unloadableProviderManifestIsReported(): void + { + $project = $this->project() + ->provider('p/a', ['a.txt' => "a\n"]) + ->file('a.txt', "a\n") + ->track('a.txt', 'p/a') + ->file('vendor/p/a/composer.json', '{"extra": {"scaffold": {"copy": "nope"}}}'); $out = new BufferedOutputWriter(); - (new StatusService())->run($this->tempDir, $out); - // colFile=max(4,1)=4, colProvider=max(8,1)=8, colMode=max(4,1)=4, colStatus=max(6,6 for 'synced')=6 - // Separator width = 4 + 8 + 4 + 6 + 6 = 28 dashes. - self::assertStringContainsString( - PHP_EOL . str_repeat('-', 28) . PHP_EOL, - $out->stdoutBuffer, - 'The separator row must be exactly 28 dashes on its own line when every column is short.', - ); - self::assertStringNotContainsString( - str_repeat('-', 29), - $out->stdoutBuffer, - 'The separator must not contain 29 consecutive dashes.', + (new StatusService()) + ->run($project->context(), $out); + + Assert::same( + $out->stderrBuffer, + Message::SCAFFOLD_MANIFEST_LOAD_FAILED->getMessage('p/a', Message::MANIFEST_COPY_MISSING->getMessage()) + . PHP_EOL, + 'Manifest failure must be the only stderr line.', ); } - protected function setUp(): void + /** + * Returns the builder of the temporary project, with `p/a` and `other/pkg` allowed. + */ + private function project(): InspectionProject { - $this->setUpTempDirectory(); + return (new InspectionProject($this->tempDir))->composer(['p/a', 'other/pkg']); } - protected function tearDown(): void + /** + * Returns the state of every file of the JSON status report, keyed by destination. + * + * @return array States keyed by destination. + */ + private function states(InspectionProject $project): array { - $this->tearDownTempDirectory(); + $out = new BufferedOutputWriter(); + + (new StatusService())->run($project->context(), $out, true); + + /** @var array{files: array} $report */ + $report = json_decode($out->stdoutBuffer, true, flags: JSON_THROW_ON_ERROR); + + return array_map(static fn(array $info): string => $info['status'], $report['files']); + } + + /** + * Returns the status summary line for `$total` files and the non-zero counts of `$counts`. + * + * @param int $total Number of files in the table. + * @param array $counts Non-zero counts keyed by state, in summary order. + * + * @return string Summary line without the trailing newline. + */ + private static function summary(int $total, array $counts): string + { + return ConsoleMessage::STATUS_SUMMARY->getMessage( + $total, + $total === 1 ? ConsoleMessage::FRAGMENT_FILE->getMessage() : ConsoleMessage::FRAGMENT_FILES->getMessage(), + implode( + ', ', + array_map( + static fn(string $state, int $count): string => ConsoleMessage::FRAGMENT_COUNT->getMessage( + $count, + $state, + ), + array_keys($counts), + $counts, + ), + ), + ); } } diff --git a/tests/Services/SyncServiceTest.php b/tests/Services/SyncServiceTest.php new file mode 100644 index 0000000..5255cde --- /dev/null +++ b/tests/Services/SyncServiceTest.php @@ -0,0 +1,541 @@ +seedProject(); + + $out = new BufferedOutputWriter(); + + Assert::same( + (new SyncService())->run($project->context(), $out), + 0, + "Exit code must be '0'.", + ); + FileAssert::contentSame( + "{$this->tempDir}/a.txt", + "a\n", + 'Replace file must be written.', + ); + FileAssert::contentSame( + "{$this->tempDir}/.gitignore", + "/vendor\n", + 'Append file must be written.', + ); + Assert::same( + $out->stdoutBuffer, + ExpectedSummary::withCommand('sync', 2, 0) . PHP_EOL, + 'Summary must count the written files.', + ); + Assert::same( + $out->stderrBuffer, + '', + 'No warning expected.', + ); + + $lock = file_get_contents( + "{$this->tempDir}/scaffold-lock.json", + ); + + $again = new BufferedOutputWriter(); + + Assert::same( + (new SyncService())->run($project->context(), $again), + 0, + "Exit code of the second sync must be '0'.", + ); + Assert::same( + $again->stdoutBuffer, + ExpectedSummary::withCommand('sync', 0, 2) . PHP_EOL, + 'Second run must change nothing.', + ); + Assert::same( + file_get_contents("{$this->tempDir}/scaffold-lock.json"), + $lock, + 'Lock must be stable.', + ); + } + + public function dryRunCountsUnchangedFilesAndSucceedsWithoutExitCode(): void + { + $project = $this->seedProject(); + + (new SyncService()) + ->run($project->context(), new BufferedOutputWriter()); + + $project->stub('p/a', 'a.txt', "a2\n"); + + $out = new BufferedOutputWriter(); + + Assert::same( + (new SyncService())->run($project->context(), $out, dryRun: true), + 0, + "Exit code must be '0': changes fail the preview only with '--exit-code'.", + ); + Assert::same( + $out->stdoutBuffer, + ConsoleMessage::DIFF_PREVIEW_HEADER->getMessage('a.txt', 'replace', 'p/a', '') . PHP_EOL + . "--- a/a.txt\n+++ b/a.txt\n@@ -1 +1 @@\n-a\n+a2" . PHP_EOL + . ConsoleMessage::DIFF_NO_CHANGES->getMessage('.gitignore') . PHP_EOL + . ConsoleMessage::SYNC_DRY_RUN_SUMMARY->getMessage( + 1, + ConsoleMessage::FRAGMENT_FILE->getMessage(), + 1, + 0, + 0, + ConsoleMessage::FRAGMENT_ERRORS->getMessage(), + ) . PHP_EOL, + 'Preview must show the change and count the unchanged file.', + ); + } + + public function dryRunCountsUserModifiedReplaceFileOnlyWithForce(): void + { + $project = $this->seedProject(); + + (new SyncService()) + ->run($project->context(), new BufferedOutputWriter()); + + $project->file('a.txt', "mine\n"); + + $plain = new BufferedOutputWriter(); + + Assert::same( + (new SyncService())->run($project->context(), $plain, dryRun: true, exitCode: true), + 0, + "Exit code must be '0': a skipped user edit is not a change.", + ); + Assert::same( + $plain->stdoutBuffer, + ConsoleMessage::DIFF_PREVIEW_HEADER->getMessage( + 'a.txt', + 'replace', + 'p/a', + ConsoleMessage::FRAGMENT_USER_MODIFIED_PREVIEW->getMessage(), + ) . PHP_EOL + . "--- a/a.txt\n+++ b/a.txt\n@@ -1 +1 @@\n-mine\n+a" . PHP_EOL + . ConsoleMessage::DIFF_NO_CHANGES->getMessage('.gitignore') . PHP_EOL + . ConsoleMessage::SYNC_DRY_RUN_SUMMARY->getMessage( + 0, + ConsoleMessage::FRAGMENT_FILES->getMessage(), + 2, + 0, + 0, + ConsoleMessage::FRAGMENT_ERRORS->getMessage(), + ) . PHP_EOL, + 'User edit must be flagged and counted as unchanged.', + ); + Assert::same( + (new SyncService())->run( + $project->context(), + new BufferedOutputWriter(), + dryRun: true, + exitCode: true, + force: true, + ), + 1, + "Exit code must be '1': a forced overwrite is a change.", + ); + FileAssert::contentSame( + "{$this->tempDir}/a.txt", + "mine\n", + 'Dry run must not write.', + ); + } + + public function dryRunPreviewsPendingFilesAndOrphansWithoutWriting(): void + { + $project = $this->seedProject() + ->file('old.txt', "old\n") + ->track('old.txt', 'p/a'); + + $before = file_get_contents( + "{$this->tempDir}/scaffold-lock.json", + ); + + $out = new BufferedOutputWriter(); + + Assert::same( + (new SyncService())->run($project->context(), $out, dryRun: true, exitCode: true), + 1, + "Exit code must be '1' for pending files with '--exit-code'.", + ); + Assert::same( + $out->stdoutBuffer, + ConsoleMessage::DIFF_PREVIEW_HEADER->getMessage('a.txt', 'replace', 'p/a', '') . PHP_EOL + . "--- a/a.txt\n+++ b/a.txt\n@@ -0,0 +1 @@\n+a" . PHP_EOL + . ConsoleMessage::DIFF_PREVIEW_HEADER->getMessage('.gitignore', 'append', 'p/a', '') . PHP_EOL + . "--- a/.gitignore\n+++ b/.gitignore\n@@ -0,0 +1 @@\n+/vendor" . PHP_EOL + . ConsoleMessage::SYNC_DRY_RUN_SUMMARY->getMessage( + 2, + ConsoleMessage::FRAGMENT_FILES->getMessage(), + 0, + 1, + 0, + ConsoleMessage::FRAGMENT_ERRORS->getMessage(), + ) . PHP_EOL, + 'Pending files must be previewed and counted with the orphan.', + ); + Assert::same( + $out->stderrBuffer, + ConsoleMessage::SCAFFOLD_ORPHAN_HEADER->getMessage(1, ConsoleMessage::FRAGMENT_FILE->getMessage()) . PHP_EOL + . ConsoleMessage::SCAFFOLD_ORPHAN_ENTRY->getMessage('old.txt', 'p/a') . PHP_EOL, + 'Orphans must be listed.', + ); + FileAssert::fileDoesNotExist( + "{$this->tempDir}/a.txt", + 'Dry run must not write files.', + ); + Assert::same( + file_get_contents("{$this->tempDir}/scaffold-lock.json"), + $before, + 'Lock must not change.', + ); + + (new SyncService()) + ->run($project->context(), new BufferedOutputWriter()); + + Assert::same( + (new SyncService())->run($project->context(), new BufferedOutputWriter(), dryRun: true, exitCode: true), + 0, + "Exit code must be '0' once the project is synced.", + ); + } + + public function dryRunReportsEscapingStubs(): void + { + $project = $this->seedProject()->file('outside.txt', "a\n"); + + unlink("{$this->tempDir}/vendor/p/a/stubs/a.txt"); + + if (@symlink("{$this->tempDir}/outside.txt", "{$this->tempDir}/vendor/p/a/stubs/a.txt") === false) { + throw new SkipTest( + 'Symbolic links are not available.', + ); + } + + $out = new BufferedOutputWriter(); + + Assert::same( + (new SyncService())->run($project->context(), $out, dryRun: true), + 1, + "Exit code must be '1' for an escaping stub.", + ); + Assert::same( + $out->stderrBuffer, + ConsoleMessage::COMMAND_FILE_ERROR->getMessage( + 'a.txt', + Message::PATH_SYMLINK_ESCAPE->getMessage('Source', 'stubs/a.txt'), + ) . PHP_EOL, + 'Escaping stub must be the only stderr line.', + ); + } + + public function dryRunReportsUnsafeDestinations(): void + { + $project = $this->seedProject()->file( + 'vendor/p/a/composer.json', + json_encode( + [ + 'name' => 'p/a', + 'extra' => [ + 'scaffold' => [ + 'copy' => [ + ['from' => 'stubs/a.txt', 'to' => 'scaffold-lock.json'], + ['from' => 'stubs/a.txt', 'to' => 'a.txt'], + ], + ], + ], + ], + JSON_THROW_ON_ERROR, + ), + ); + + $out = new BufferedOutputWriter(); + + Assert::same( + (new SyncService())->run($project->context(), $out, dryRun: true), + 1, + "Exit code must be '1' for an unsafe destination.", + ); + Assert::same( + $out->stdoutBuffer, + ConsoleMessage::DIFF_PREVIEW_HEADER->getMessage('a.txt', 'replace', 'p/a', '') . PHP_EOL + . "--- a/a.txt\n+++ b/a.txt\n@@ -0,0 +1 @@\n+a" . PHP_EOL + . ConsoleMessage::SYNC_DRY_RUN_SUMMARY->getMessage( + 1, + ConsoleMessage::FRAGMENT_FILE->getMessage(), + 0, + 0, + 1, + ConsoleMessage::FRAGMENT_ERROR->getMessage(), + ) . PHP_EOL, + 'Later files must still be previewed and the error counted.', + ); + Assert::same( + $out->stderrBuffer, + ConsoleMessage::COMMAND_FILE_ERROR->getMessage( + 'scaffold-lock.json', + Message::PATH_RESERVED->getMessage('scaffold-lock.json'), + ) . PHP_EOL, + 'Reserved destination must be reported.', + ); + } + + public function failsWhenAFileCannotBeApplied(): void + { + $project = $this->seedProject()->file( + 'vendor/p/a/composer.json', + json_encode( + [ + 'name' => 'p/a', + 'extra' => [ + 'scaffold' => [ + 'copy' => [ + ['from' => 'stubs/a.txt', 'to' => 'a.txt'], + ['from' => 'stubs/a.txt', 'to' => 'scaffold-lock.json'], + ], + ], + ], + ], + JSON_THROW_ON_ERROR, + ), + ); + + $out = new BufferedOutputWriter(); + + Assert::same( + (new SyncService())->run($project->context(), $out), + 1, + "Exit code must be '1' when a file fails.", + ); + Assert::same( + $out->stderrBuffer, + ConsoleMessage::SCAFFOLD_APPLY_FAILED->getMessage( + 'scaffold-lock.json', + Message::PATH_RESERVED->getMessage('scaffold-lock.json'), + ) . PHP_EOL, + 'Cause must be the only stderr line.', + ); + Assert::same( + $out->stdoutBuffer, + ExpectedSummary::withCommand('sync', 1, 0, ExpectedSummary::part(1, ConsoleMessage::FRAGMENT_ERROR)) + . PHP_EOL, + 'Summary must count the error.', + ); + } + + public function failsWhenTheLockCannotBeWritten(): void + { + $project = $this->seedProject(); + + // A non-empty directory at the lock path reads as an absent lock, and makes the final rename fail. + mkdir("{$this->tempDir}/scaffold-lock.json/entry", 0o777, true); + + $out = new BufferedOutputWriter(); + + Assert::same( + (new SyncService())->run($project->context(), $out), + 1, + "Exit code must be '1' when the lock cannot be written.", + ); + // The reason names a temporary file with a unique suffix and depends on the platform, so it is a pattern. + Assert::string($out->stderrBuffer)->matchesRegex( + '/\A' . preg_quote( + ConsoleMessage::SYNC_ABORTED->getMessage( + Message::LOCK_UNWRITABLE->getMessage((new LockFile($this->tempDir))->getPath()) . ' Reason: rename(', + ), + '/', + ) . '.+\R\z/', + "Cause must be the only stderr line, with the failed 'rename()'.", + ); + Assert::same( + $out->stdoutBuffer, + ExpectedSummary::withCommand('sync', 2, 0, ExpectedSummary::part(1, ConsoleMessage::FRAGMENT_ERROR)) + . PHP_EOL, + 'Summary must count the error.', + ); + } + + public function failsWithoutWritingWhenAProviderManifestIsInvalid(): void + { + $project = $this + ->seedProject() + ->file('vendor/p/a/composer.json', '{"extra": {"scaffold": {"copi": []}}}'); + + $out = new BufferedOutputWriter(); + + Assert::same( + (new SyncService())->run($project->context(), $out), + 1, + "Exit code must be '1' for an invalid manifest.", + ); + Assert::same( + $out->stderrBuffer, + Message::SCAFFOLD_MANIFEST_LOAD_FAILED->getMessage( + 'p/a', + Message::MANIFEST_KEY_UNKNOWN->getMessage( + 'copi', + 'allowed-packages, auto, copy, exclude, manifest, merge, modes', + ), + ) . PHP_EOL, + 'Cause must be the only stderr line.', + ); + Assert::same( + $out->stdoutBuffer, + ExpectedSummary::withCommand('sync', 0, 0, ExpectedSummary::part(1, ConsoleMessage::FRAGMENT_ERROR)) + . PHP_EOL, + 'Summary must still be printed.', + ); + FileAssert::fileDoesNotExist( + "{$this->tempDir}/scaffold-lock.json", + 'Nothing may be recorded.', + ); + } + + public function forceOverwritesUserModifiedReplaceFile(): void + { + $project = $this->seedProject(); + + (new SyncService()) + ->run($project->context(), new BufferedOutputWriter()); + + $project->file('a.txt', "mine\n"); + + $out = new BufferedOutputWriter(); + + Assert::same( + (new SyncService())->run($project->context(), $out), + 0, + "Exit code of a plain sync must be '0'.", + ); + FileAssert::contentSame( + "{$this->tempDir}/a.txt", + "mine\n", + 'Edit must survive a plain sync.', + ); + Assert::same( + $out->stderrBuffer, + ConsoleMessage::SCAFFOLD_PREFIXED->getMessage( + ConsoleMessage::SCAFFOLD_USER_MODIFIED_SKIPPED->getMessage('a.txt'), + ) . PHP_EOL, + 'Skip must be warned.', + ); + Assert::same( + (new SyncService())->run($project->context(), new BufferedOutputWriter(), force: true), + 0, + "Exit code of a forced sync must be '0'.", + ); + FileAssert::contentSame( + "{$this->tempDir}/a.txt", + "a\n", + 'Force must restore the stub.', + ); + } + + public function notInstalledProviderIsWarnedInBothModes(): void + { + $project = $this->seedProject(['p/a', 'p/missing']); + + $warning = ConsoleMessage::SCAFFOLD_PROVIDER_NOT_INSTALLED->getMessage('p/missing') . PHP_EOL; + + $preview = new BufferedOutputWriter(); + + (new SyncService()) + ->run($project->context(), $preview, dryRun: true); + + Assert::same( + $preview->stderrBuffer, + $warning, + 'Dry run must warn.', + ); + + $out = new BufferedOutputWriter(); + + Assert::same( + (new SyncService())->run($project->context(), $out), + 0, + "Exit code must be '0': a missing provider is a warning.", + ); + Assert::same( + $out->stderrBuffer, + $warning, + 'Sync must warn.', + ); + Assert::same( + $out->stdoutBuffer, + ExpectedSummary::withCommand('sync', 2, 0, ExpectedSummary::part(1, ConsoleMessage::FRAGMENT_WARNING)) + . PHP_EOL, + 'Warning must be counted.', + ); + } + + public function withoutAllowedPackagesNothingIsSynced(): void + { + $project = $this->seedProject([]); + $out = new BufferedOutputWriter(); + + Assert::same( + (new SyncService())->run($project->context(), $out), + 0, + "Exit code must be '0': an empty allowlist is not an error.", + ); + Assert::same( + $out->stdoutBuffer, + ConsoleMessage::SYNC_NO_ALLOWED_PACKAGES->getMessage() . PHP_EOL, + 'Notice must be the only output.', + ); + FileAssert::fileDoesNotExist( + "{$this->tempDir}/scaffold-lock.json", + 'No lock may be created.', + ); + } + + /** + * Builds a project with `auto: false` and provider `p/a` shipping a replace and an append file. + * + * @param list $allowed Providers allowed to write files. + */ + private function seedProject(array $allowed = ['p/a']): InspectionProject + { + return (new InspectionProject($this->tempDir)) + ->file( + 'composer.json', + json_encode( + ['extra' => ['scaffold' => ['allowed-packages' => $allowed, 'auto' => false]]], + JSON_THROW_ON_ERROR, + ), + ) + ->installed(['p/a' => '1.0.0']) + ->provider('p/a', ['a.txt' => "a\n", '.gitignore' => "/vendor\n"], ['.gitignore' => 'append']); + } +} diff --git a/tests/Support/ComposerEventHarness.php b/tests/Support/ComposerEventHarness.php index 19aa91e..5914a70 100644 --- a/tests/Support/ComposerEventHarness.php +++ b/tests/Support/ComposerEventHarness.php @@ -6,136 +6,97 @@ use Composer\Composer; use Composer\Factory; -use Composer\IO\{BufferIO, IOInterface}; -use Composer\Package\{CompletePackage, PackageInterface}; -use Composer\Script\Event as ScriptEvent; -use Composer\Script\ScriptEvents; +use Composer\IO\BufferIO; +use Composer\Package\CompletePackage; +use Composer\Script\{Event as ScriptEvent, ScriptEvents}; use PHPForge\Scaffold\EventSubscriber; -use ReflectionClass; -use RuntimeException; - -use function sprintf; +use ReflectionProperty; +use Testo\Lifecycle\{AfterTest, BeforeTest}; /** - * Harness for functional tests that need a real {@see Composer} instance and programmatically dispatched script events. - * - * Centralizes the boilerplate of (1) calling {@see Factory::create()} against a fake project, (2) seeding the local - * repository with mock provider packages, and (3) building {@see ScriptEvent} instances for the three lifecycle events - * the scaffold plugin subscribes to. + * Dispatches Composer script events to {@see EventSubscriber} for a fake project built by {@see FakeProjectBuilder}, + * with a real {@see Composer} instance whose local repository holds the provider `demo/scaffold`. * - * Tests dispatch events directly against a {@see \PHPForge\Scaffold\EventSubscriber} instance, bypassing the full - * Composer installation pipeline. This exercises the same code path the plugin runs in production without the cost - * and brittleness of shelling out to `composer install`. + * This runs the code path of the plugin in production without shelling out to `composer install`. The class that uses + * this trait must also use {@see TempDirectoryTrait}, which holds the fake project. */ trait ComposerEventHarness { /** - * Adds a mock provider package to the local repository with the given scaffold manifest. - * - * @param Composer $composer Live Composer instance whose local repository receives the package. - * @param string $name Composer package name (for example, `demo/scaffold`). - * @param array $scaffoldManifest Raw `extra.scaffold` array, typically a `{copy: [...]}` inline - * manifest or an external `{manifest: "scaffold.json"}` pointer. - * @param string $version Pretty version string persisted into `scaffold-lock.json`. - * - * @return PackageInterface Package that was added to the local repository. + * Clears the process-wide run flag of {@see EventSubscriber} before and after each test, so + * `post-create-project-cmd` runs unless the test itself dispatched `post-install-cmd` or `post-update-cmd` first. */ - protected function addMockProvider( - Composer $composer, - string $name, - array $scaffoldManifest, - string $version = '1.0.0', - ): PackageInterface { - $package = new CompletePackage($name, "{$version}.0", $version); - - $package->setType('library'); - $package->setExtra(['scaffold' => $scaffoldManifest]); - $composer->getRepositoryManager()->getLocalRepository()->addPackage($package); - - return $package; + #[BeforeTest] + #[AfterTest] + public function resetScaffoldRanFlag(): void + { + (new ReflectionProperty(EventSubscriber::class, 'scaffoldRan'))->setValue(null, false); } /** - * Creates a {@see Composer} instance for a fake project using {@see Factory::create()}. + * Dispatches `$event` to a new {@see EventSubscriber} for a fresh Composer instance of the project of `$builder` + * that has `demo/scaffold` installed with `$manifest`, and returns the Composer output. * - * Plugins are disabled because tests manually instantiate {@see \PHPForge\Scaffold\EventSubscriber} and dispatch - * events against it, so the plugin manager does not need to auto-load this package. + * @param FakeProjectBuilder $builder Fake project, with its `composer.json` written by {@see self::project()}. + * @param array $manifest Raw `extra.scaffold` of `demo/scaffold`. + * @param string $event Script event name, such as {@see ScriptEvents::POST_INSTALL_CMD}. + * @param string $version Pretty version of `demo/scaffold`. + * @param BufferIO $io IO of the run, which keeps the output when the run throws. * - * @param string $projectRoot Absolute path to the fake project directory containing `composer.json`. - * @param IOInterface|null $io Optional IO; a {@see BufferIO} is created when omitted so callers can inspect output. - * - * @return Composer Composer instance bootstrapped for the fake project, with plugins disabled. + * @return string Output written to `$io`. */ - protected function buildComposerForProject(string $projectRoot, IOInterface|null $io = null): Composer - { - $io ??= new BufferIO(); + protected function dispatch( + FakeProjectBuilder $builder, + array $manifest, + string $event = ScriptEvents::POST_INSTALL_CMD, + string $version = '1.0.0', + BufferIO $io = new BufferIO(), + ): string { + $composer = Factory::create( + $io, + "{$builder->getProjectRoot()}/composer.json", + disablePlugins: true, + disableScripts: true, + ); + + $package = new CompletePackage('demo/scaffold', "{$version}.0", $version); + + $package->setExtra(['scaffold' => $manifest]); + $composer->getRepositoryManager()->getLocalRepository()->addPackage($package); - $composerJson = $projectRoot . '/composer.json'; + $subscriber = new EventSubscriber(); + $scriptEvent = new ScriptEvent($event, $composer, $io, true); - if (!is_file($composerJson)) { - throw new RuntimeException( - sprintf( - 'Fake project "%s" is missing composer.json; call FakeProjectBuilder::createComposerJson first.', - $projectRoot, - ), - ); + if ($event === ScriptEvents::POST_CREATE_PROJECT_CMD) { + $subscriber->onPostCreateProject($scriptEvent); + } elseif ($event === ScriptEvents::POST_UPDATE_CMD) { + $subscriber->onPostUpdate($scriptEvent); + } else { + $subscriber->onPostInstall($scriptEvent); } - return Factory::create($io, $composerJson, disablePlugins: true, disableScripts: true); - } - - /** - * Builds a `post-create-project-cmd` script event bound to `$composer` and `$io`. - * - * @param Composer $composer Live Composer instance to bind to the event. - * @param IOInterface $io IO instance to bind to the event. - * - * @return ScriptEvent Script event instance with name `post-create-project-cmd` and the given composer and IO. - */ - protected function makePostCreateProjectEvent(Composer $composer, IOInterface $io): ScriptEvent - { - return new ScriptEvent(ScriptEvents::POST_CREATE_PROJECT_CMD, $composer, $io, true); - } - - /** - * Builds a `post-install-cmd` script event bound to `$composer` and `$io`. - * - * @param Composer $composer Live Composer instance to bind to the event. - * @param IOInterface $io IO instance to bind to the event. - * - * @return ScriptEvent Script event instance with name `post-install-cmd` and the given composer and IO. - */ - protected function makePostInstallEvent(Composer $composer, IOInterface $io): ScriptEvent - { - return new ScriptEvent(ScriptEvents::POST_INSTALL_CMD, $composer, $io, true); - } - - /** - * Builds a `post-update-cmd` script event bound to `$composer` and `$io`. - * - * @param Composer $composer Live Composer instance to bind to the event. - * @param IOInterface $io IO instance to bind to the event. - * - * @return ScriptEvent Script event instance with name `post-update-cmd` and the given composer and IO. - */ - protected function makePostUpdateEvent(Composer $composer, IOInterface $io): ScriptEvent - { - return new ScriptEvent(ScriptEvents::POST_UPDATE_CMD, $composer, $io, true); + return $io->getOutput(); } /** - * Resets the process-wide {@see EventSubscriber::$installScaffoldRan} flag via reflection. + * Creates the fake project in the temporary directory, with a `composer.json` that pins the root version, points + * `vendor-dir` at the fake vendor directory and holds `$scaffold` as `extra.scaffold`. * - * The flag persists across tests by design (it guards against duplicate scaffolding within a single Composer - * invocation). Tests that dispatch multiple events across different scenarios must reset it to get deterministic - * behavior. + * @param array $scaffold Root `extra.scaffold`. */ - protected function resetInstallScaffoldRanFlag(): void + protected function project(array $scaffold = ['allowed-packages' => ['demo/scaffold']]): FakeProjectBuilder { - $reflection = new ReflectionClass(EventSubscriber::class); - - $property = $reflection->getProperty('installScaffoldRan'); - - $property->setValue(null, false); + $builder = new FakeProjectBuilder($this->tempDir); + + $builder->createComposerJson( + [ + 'name' => 'demo/project', + 'version' => '1.0.0', + 'config' => ['vendor-dir' => $builder->getVendorDir()], + 'extra' => ['scaffold' => $scaffold], + ], + ); + + return $builder; } } diff --git a/tests/Support/ExpectedSummary.php b/tests/Support/ExpectedSummary.php new file mode 100644 index 0000000..4921bc9 --- /dev/null +++ b/tests/Support/ExpectedSummary.php @@ -0,0 +1,148 @@ +getMessage($count, $label->getMessage()); + } + + /** + * Returns the `reapply` summary line for the given counts. + * + * @param int $written Number of written entries, or of entries that would be written with `$dryRun`. + * @param int $unchanged Number of unchanged entries. + * @param int $skipped Number of skipped entries. + * @param int $errors Number of errors. + * @param string ...$reasons Rendered skip reasons, such as `FRAGMENT_COUNT` results, in output order. + * + * @return string Expected summary line of a run that writes the files. + */ + public static function reapply(int $written, int $unchanged, int $skipped, int $errors, string ...$reasons): string + { + return self::reapplyLine('', Message::FRAGMENT_WRITTEN, $written, $unchanged, $skipped, $errors, $reasons); + } + + /** + * Returns the `reapply --dry-run` summary line for the given counts. + * + * @param int $written Number of entries that would be written. + * @param int $unchanged Number of unchanged entries. + * @param int $skipped Number of skipped entries. + * @param int $errors Number of errors. + * @param string ...$reasons Rendered skip reasons, such as `FRAGMENT_COUNT` results, in output order. + * + * @return string Expected summary line of a run that only previews the files. + */ + public static function reapplyDryRun( + int $written, + int $unchanged, + int $skipped, + int $errors, + string ...$reasons, + ): string { + return self::reapplyLine( + Message::FRAGMENT_DRY_RUN->getMessage(), + Message::FRAGMENT_WOULD_BE_WRITTEN, + $written, + $unchanged, + $skipped, + $errors, + $reasons, + ); + } + + /** + * Returns the scaffold summary line of `$command` with the written and unchanged counts followed by `$parts`. + * + * @param string $command Command name, or an empty string for none. + * @param int $written Number of written files. + * @param int $unchanged Number of unchanged files. + * @param string ...$parts Rendered attention parts, such as {@see self::part()} results. + * + * @return string Expected summary line. + */ + public static function withCommand(string $command, int $written, int $unchanged, string ...$parts): string + { + $all = [ + Message::FRAGMENT_COUNT_WRITTEN->getMessage( + $written, + $written === 1 ? Message::FRAGMENT_FILE->getMessage() : Message::FRAGMENT_FILES->getMessage(), + ), + Message::FRAGMENT_COUNT_UNCHANGED->getMessage($unchanged), + ...$parts, + ]; + + return Message::SCAFFOLD_SUMMARY->getMessage( + $command === '' ? '' : Message::FRAGMENT_COMMAND->getMessage($command), + implode(', ', $all), + ); + } + + /** + * Returns the `reapply` summary line with the given prefix and written label. + * + * @param string $dryRun Rendered dry-run marker, or an empty string for none. + * @param Message $writtenLabel Fragment that labels the written count. + * @param int $written Number of written entries. + * @param int $unchanged Number of unchanged entries. + * @param int $skipped Number of skipped entries. + * @param int $errors Number of errors. + * @param array $reasons Rendered skip reasons, in output order. + * + * @return string Expected summary line. + */ + private static function reapplyLine( + string $dryRun, + Message $writtenLabel, + int $written, + int $unchanged, + int $skipped, + int $errors, + array $reasons, + ): string { + return Message::REAPPLY_SUMMARY->getMessage( + $dryRun, + $written, + $writtenLabel->getMessage(), + $unchanged, + $skipped, + $reasons === [] ? '' : Message::FRAGMENT_PARENTHESIZED->getMessage(implode(', ', $reasons)), + $errors, + $errors === 1 ? Message::FRAGMENT_ERROR->getMessage() : Message::FRAGMENT_ERRORS->getMessage(), + ); + } +} diff --git a/tests/Support/FakeProjectBuilder.php b/tests/Support/FakeProjectBuilder.php index 7129045..af6f4f1 100644 --- a/tests/Support/FakeProjectBuilder.php +++ b/tests/Support/FakeProjectBuilder.php @@ -6,52 +6,50 @@ use RuntimeException; +use function dirname; +use function file_put_contents; +use function is_dir; +use function json_encode; +use function mkdir; +use function sprintf; + /** * Builds a temporary fake project and vendor directory for functional scaffold tests. */ final readonly class FakeProjectBuilder { + /** + * Absolute path of the fake project root. + */ private string $projectRoot; + /** + * Absolute path of the fake vendor directory, a sibling of the project root. + */ private string $vendorDir; + /** + * @param string $tempBase Absolute path of the temporary directory of the test. + */ public function __construct(string $tempBase) { - $this->projectRoot = $tempBase . '/project'; - $this->vendorDir = $tempBase . '/vendor'; + $this->projectRoot = "{$tempBase}/project"; + $this->vendorDir = "{$tempBase}/vendor"; - if (!is_dir($this->projectRoot) - && mkdir($this->projectRoot, 0o777, recursive: true) === false - && !is_dir($this->projectRoot) - ) { - throw new RuntimeException(sprintf('Could not create project root "%s".', $this->projectRoot)); - } - - if (!is_dir($this->vendorDir) - && mkdir($this->vendorDir, 0o777, recursive: true) === false - && !is_dir($this->vendorDir) - ) { - throw new RuntimeException(sprintf('Could not create vendor dir "%s".', $this->vendorDir)); - } + self::ensureDirectory($this->projectRoot); + self::ensureDirectory($this->vendorDir); } /** * Writes a `composer.json` at the project root from the given array. * * @param array $config Root composer.json content to serialize. - * - * @return string Absolute path to the written `composer.json`. */ - public function createComposerJson(array $config): string + public function createComposerJson(array $config): void { - $path = $this->projectRoot . '/composer.json'; - - $json = json_encode($config, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR); - - if (file_put_contents($path, $json) === false) { - throw new RuntimeException(sprintf('Could not write composer.json at "%s".', $path)); - } - - return $path; + self::write( + "{$this->projectRoot}/composer.json", + json_encode($config, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR), + ); } /** @@ -62,16 +60,7 @@ public function createComposerJson(array $config): string */ public function createProjectFile(string $relPath, string $content): void { - $full = $this->projectRoot . '/' . $relPath; - $dir = dirname($full); - - if (!is_dir($dir) && mkdir($dir, 0o777, recursive: true) === false && !is_dir($dir)) { - throw new RuntimeException(sprintf('Could not create directory "%s".', $dir)); - } - - if (file_put_contents($full, $content) === false) { - throw new RuntimeException(sprintf('Could not write file "%s".', $full)); - } + self::write("{$this->projectRoot}/{$relPath}", $content); } /** @@ -83,22 +72,11 @@ public function createProjectFile(string $relPath, string $content): void */ public function createStubFile(string $providerName, string $relPath, string $content): void { - $full = $this->vendorDir . '/' . $providerName . '/' . $relPath; - $dir = dirname($full); - - if (!is_dir($dir) && mkdir($dir, 0o777, recursive: true) === false && !is_dir($dir)) { - throw new RuntimeException(sprintf('Could not create directory "%s".', $dir)); - } - - if (file_put_contents($full, $content) === false) { - throw new RuntimeException(sprintf('Could not write file "%s".', $full)); - } + self::write("{$this->vendorDir}/{$providerName}/{$relPath}", $content); } /** * Returns the absolute path to the fake project root. - * - * @return string Absolute path to the fake project root. */ public function getProjectRoot(): string { @@ -107,11 +85,35 @@ public function getProjectRoot(): string /** * Returns the absolute path to the fake vendor directory. - * - * @return string Absolute path to the fake vendor directory. */ public function getVendorDir(): string { return $this->vendorDir; } + + /** + * Creates `$path` when it does not exist. + * + * @throws RuntimeException if the directory cannot be created. + */ + private static function ensureDirectory(string $path): void + { + if (!is_dir($path) && !mkdir($path, 0o777, recursive: true) && !is_dir($path)) { + throw new RuntimeException(sprintf('Could not create directory "%s".', $path)); + } + } + + /** + * Writes `$content` to `$path`, creating the parent directory. + * + * @throws RuntimeException if the file cannot be written. + */ + private static function write(string $path, string $content): void + { + self::ensureDirectory(dirname($path)); + + if (file_put_contents($path, $content) === false) { + throw new RuntimeException(sprintf('Could not write file "%s".', $path)); + } + } } diff --git a/tests/Support/FileAssert.php b/tests/Support/FileAssert.php new file mode 100644 index 0000000..4890be8 --- /dev/null +++ b/tests/Support/FileAssert.php @@ -0,0 +1,80 @@ +/vendor` and a hand-written `scaffold-lock.json`, for the + * inspection services and commands. + */ +final readonly class InspectionProject +{ + /** + * @param string $root Absolute path to the project root; it must exist. + */ + public function __construct(public string $root) {} + + /** + * Writes the root `composer.json` with the given `allowed-packages`. + * + * @param list $allowed Package names allowed to write scaffold files. + */ + public function composer(array $allowed): self + { + $this->write( + 'composer.json', + json_encode(['extra' => ['scaffold' => ['allowed-packages' => $allowed]]], JSON_THROW_ON_ERROR), + ); + + return $this; + } + + /** + * Returns the context of the project, whose `composer.json` keeps the default vendor directory `/vendor`. + */ + public function context(): ProjectContext + { + return ProjectContext::create($this->root); + } + + /** + * Removes a project file. + */ + public function delete(string $destination): self + { + unlink("{$this->root}/{$destination}"); + + return $this; + } + + /** + * Writes a project file. + */ + public function file(string $destination, string $content): self + { + $this->write($destination, $content); + + return $this; + } + + /** + * Writes `vendor/composer/installed.php` listing the given packages with their versions. + * + * @param array $versions Pretty versions keyed by package name. + */ + public function installed(array $versions): self + { + $packages = []; + + foreach ($versions as $name => $version) { + $packages[$name] = ['pretty_version' => $version, 'install_path' => "{$this->root}/vendor/{$name}"]; + } + + $this->write( + 'vendor/composer/installed.php', + ' [], 'versions' => $packages], true) . ';', + ); + + return $this; + } + + /** + * Returns the lock file of the project. + */ + public function lock(): LockFile + { + return new LockFile($this->root); + } + + /** + * Writes a provider package with one stub per destination at `stubs/`. + * + * @param string $name Provider package name. + * @param array $files Stub contents keyed by destination. + * @param array $modes Manifest `modes` map. + * @param array $merge Manifest `merge` map. + */ + public function provider(string $name, array $files, array $modes = [], array $merge = []): self + { + $copy = []; + + foreach ($files as $destination => $content) { + $copy[] = ['from' => "stubs/{$destination}", 'to' => $destination]; + + $this->stub($name, $destination, $content); + } + + $scaffold = ['copy' => $copy]; + + if ($modes !== []) { + $scaffold['modes'] = $modes; + } + + if ($merge !== []) { + $scaffold['merge'] = $merge; + } + + $this->write( + "vendor/{$name}/composer.json", + json_encode(['name' => $name, 'extra' => ['scaffold' => $scaffold]], JSON_THROW_ON_ERROR), + ); + + return $this; + } + + /** + * Overwrites the stub of a destination in a provider package. + */ + public function stub(string $provider, string $destination, string $content): self + { + $this->write("vendor/{$provider}/stubs/{$destination}", $content); + + return $this; + } + + /** + * Records a lock entry with the current disk hash and the current stub hash, merged with `$extra`. + * + * @param array $extra Entry keys that replace or extend the computed ones; `null` removes + * the key. + */ + public function track( + string $destination, + string $provider, + string $mode = 'replace', + array $extra = [], + string $version = '1.0.0', + ): self { + $lock = $this->lock(); + + $data = $lock->read(); + + $diskPath = "{$this->root}/{$destination}"; + $stubPath = "{$this->root}/vendor/{$provider}/stubs/{$destination}"; + + $entry = [ + 'hash' => is_file($diskPath) ? Hasher::hash($diskPath) : 'sha256:none', + 'provider' => $provider, + 'source' => "stubs/{$destination}", + 'mode' => $mode, + ]; + + if (is_file($stubPath)) { + $entry['stub-hash'] = Hasher::hash($stubPath); + } + + $data['providers'][$provider] = ['version' => $version, 'path' => "vendor/{$provider}"]; + $data['files'][$destination] = array_filter( + [...$entry, ...$extra], + static fn(bool|string|null $value): bool => $value !== null, + ); + + $lock->write($data); + + return $this; + } + + /** + * Writes `$content` to a path relative to the project root, creating parent directories. + */ + private function write(string $relative, string $content): void + { + $path = "{$this->root}/{$relative}"; + $dir = dirname($path); + + if (!is_dir($dir) && !mkdir($dir, 0o777, true) && !is_dir($dir)) { + throw new RuntimeException(sprintf('Could not create directory "%s".', $dir)); + } + + if (file_put_contents($path, $content) === false) { + throw new RuntimeException(sprintf('Could not write "%s".', $path)); + } + } +} diff --git a/tests/Support/MergeAssertionsTrait.php b/tests/Support/MergeAssertionsTrait.php new file mode 100644 index 0000000..5d3d258 --- /dev/null +++ b/tests/Support/MergeAssertionsTrait.php @@ -0,0 +1,123 @@ +merge($provider, $consumer); + $second = $strategy->merge($provider, $result->content); + $consumerLines = self::linesOf($consumer); + + self::assertMergeSame( + $result->content, + $expected, + 'Merged bytes must match the golden fixture.', + ); + self::assertMergeSame( + $result->changed, + $expected !== $consumer, + 'Changed flag must reflect a content change.', + ); + self::assertMergeSame( + self::linesKeptInOrder($consumerLines, self::linesOf($result->content)), + $consumerLines, + 'Every consumer line must be kept in its original order.', + ); + self::assertMergeSame( + $second->changed, + false, + "Second run must report 'changed' as 'false'.", + ); + self::assertMergeSame( + $second->content, + $result->content, + 'Second run must return identical bytes.', + ); + } + + /** + * Asserts that `$actual` is identical to `$expected`. + * + * @param mixed $actual Actual value. + * @param mixed $expected Expected value. + * @param string $message Failure message. + */ + private static function assertMergeSame(mixed $actual, mixed $expected, string $message): void + { + Assert::same($actual, $expected, $message); + } + + /** + * Returns the lines of `$consumer` that appear in `$merged` in the same relative order, scanning `$merged` once. + * + * The result equals `$consumer` exactly when every consumer line is kept in order. + * + * @param list $consumer Consumer lines. + * @param list $merged Merged lines. + * + * @return list Consumer lines found in order. + */ + private static function linesKeptInOrder(array $consumer, array $merged): array + { + $kept = []; + $position = 0; + $total = count($merged); + + foreach ($consumer as $line) { + while ($position < $total && ($merged[$position] ?? null) !== $line) { + $position++; + } + + if ($position < $total) { + $kept[] = $line; + $position++; + } + } + + return $kept; + } + + /** + * Returns the lines of `$content` with terminators normalised. + * + * @param string $content Content to split. + * + * @return list Lines. + */ + private static function linesOf(string $content): array + { + $normalised = trim((string) preg_replace('/\r\n|\r/', "\n", $content), "\n"); + + return $normalised === '' ? [] : explode("\n", $normalised); + } +} diff --git a/tests/Support/MockerExtension.php b/tests/Support/MockerExtension.php deleted file mode 100644 index 2ee4dff..0000000 --- a/tests/Support/MockerExtension.php +++ /dev/null @@ -1,110 +0,0 @@ -registerSubscribers( - new class implements StartedSubscriber { - public function notify(Started $event): void - { - MockerExtension::load(); - } - }, - new class implements PreparationStartedSubscriber { - public function notify(PreparationStarted $event): void - { - MockerState::resetState(); - MockerExtension::resetDefaults(); - } - }, - new class implements FinishedSubscriber { - public function notify(Finished $event): void - { - MockerState::resetState(); - MockerExtension::resetDefaults(); - } - }, - ); - } - - /** - * Loads configured function mocks into scaffold namespaces and snapshots their initial state. - */ - public static function load(): void - { - $mocks = [ - ['namespace' => 'PHPForge\\Scaffold\\Scaffold\\Lock', 'name' => 'is_readable'], - ['namespace' => 'PHPForge\\Scaffold\\Scaffold\\Lock', 'name' => 'file_get_contents'], - ['namespace' => 'PHPForge\\Scaffold\\Scaffold\\Lock', 'name' => 'file_put_contents'], - ['namespace' => 'PHPForge\\Scaffold\\Scaffold\\Lock', 'name' => 'rename'], - ['namespace' => 'PHPForge\\Scaffold\\Scaffold\\Lock', 'name' => 'hash_file'], - ['namespace' => 'PHPForge\\Scaffold\\Scaffold\\Modes', 'name' => 'file_put_contents'], - ['namespace' => 'PHPForge\\Scaffold\\Scaffold\\Modes', 'name' => 'file_get_contents'], - ['namespace' => 'PHPForge\\Scaffold\\Scaffold\\Modes', 'name' => 'copy'], - ['namespace' => 'PHPForge\\Scaffold\\Scaffold', 'name' => 'mkdir'], - ['namespace' => 'PHPForge\\Scaffold\\Scaffold', 'name' => 'is_dir'], - ['namespace' => 'PHPForge\\Scaffold\\Manifest', 'name' => 'file_get_contents'], - ['namespace' => 'PHPForge\\Scaffold\\Services', 'name' => 'file_get_contents'], - ['namespace' => 'PHPForge\\Scaffold\\Services', 'name' => 'file_put_contents'], - ['namespace' => 'PHPForge\\Scaffold\\Console\\Command', 'name' => 'getcwd'], - ]; - - $mocksPath = __DIR__ . '/../../runtime/.phpunit.cache/internal-mocker/mocks.php'; - $stubPath = __DIR__ . '/internal-mocker-stubs.php'; - - /** - * Force regeneration of the namespaced wrappers on every run so a stale cache persisted by a CI runner, - * an opcache layer, or a previous local session with a different mock list cannot silently shadow the current - * configuration. `Mocker::load()` uses `require_once`, so the very first require in this process binds the - * namespaced function symbols; deleting the cached file here ensures that require loads the freshly generated - * content rather than an outdated copy. - */ - if (is_file($mocksPath)) { - unlink($mocksPath); - } - - $mocker = new Mocker($mocksPath, $stubPath); - - $mocker->load($mocks); - - MockerState::saveState(); - } - - /** - * Clears {@see MockerState::$defaults} via reflection between tests. - * - * `MockerState::resetState()` only restores `$state` to its saved snapshot but leaves the `$defaults` map - * (populated via `addCondition(..., default: true)`) untouched. That causes a default set in one test to silently - * shadow real function calls in every subsequent test. This helper restores clean isolation. - */ - public static function resetDefaults(): void - { - $reflection = new ReflectionClass(MockerState::class); - - $property = $reflection->getProperty('defaults'); - - $property->setValue(null, []); - } -} diff --git a/tests/Support/ProcessResult.php b/tests/Support/ProcessResult.php new file mode 100644 index 0000000..21ea494 --- /dev/null +++ b/tests/Support/ProcessResult.php @@ -0,0 +1,39 @@ +stdout}\n--- stderr\n{$this->stderr}"; + } + + /** + * Returns the exit code as a string, followed by both streams when it differs from `$expected`, so a failed + * comparison with `$expected` shows the output of the process. + * + * @param int $expected Expected exit code. + */ + public function status(int $expected = 0): string + { + return $this->exitCode === $expected ? (string) $this->exitCode : "{$this->exitCode}\n{$this->output()}"; + } +} diff --git a/tests/Support/RealComposer.php b/tests/Support/RealComposer.php new file mode 100644 index 0000000..92ac4a4 --- /dev/null +++ b/tests/Support/RealComposer.php @@ -0,0 +1,418 @@ +> + */ + public static function repositories(string $plugin, string $providerVersion = '1.0.0'): array + { + $variant = $providerVersion === '1.0.0' ? 'provider-v1' : 'provider-v2'; + + return [ + ['packagist.org' => false], + self::pathRepository($plugin, 'php-forge/scaffold', self::PLUGIN_VERSION), + self::pathRepository( + self::root() . "/tests/Fixtures/composer/providers/{$variant}", + 'fixture/provider', + $providerVersion, + ), + ...self::dependencies(), + ]; + } + + /** + * Returns the command prefix that runs Composer: `COMPOSER_BINARY`, then `composer.phar` or `composer` on `PATH`, + * executed with the current PHP binary, skipping the current test when none is found. + * + * Call it from the test body, directly or through a helper: a skip thrown from a Testo hook aborts the test + * instead. + * + * @throws SkipTest when no Composer binary is found. + * + * @return list + */ + public static function requireCommand(): array + { + return self::locate() ?? throw new SkipTest( + 'Composer is not available; set COMPOSER_BINARY or add composer to PATH.', + ); + } + + /** + * Returns the requirements of a consumer project that installs the plugin snapshot: the plugin at + * {@see self::PLUGIN_VERSION}, plus every plugin requirement whose constraint carries a stability flag, such as + * `@dev`, because Composer honors stability flags only in the root package. + * + * @return array + */ + public static function requirements(): array + { + $requirements = ['php-forge/scaffold' => self::PLUGIN_VERSION]; + + foreach (self::pluginRequirements() as $name => $constraint) { + if (preg_match('/@(?:stable|rc|beta|alpha|dev)\b/i', $constraint) === 1) { + $requirements[$name] = $constraint; + } + } + + return $requirements; + } + + /** + * Runs `$arguments` with Composer in `$cwd`, offline, without interaction, and with `$home` as `COMPOSER_HOME`. + * + * @param list $arguments Composer arguments, such as `['install']`. + * @param string $cwd Working directory. + * @param string $home Absolute path of the `COMPOSER_HOME` directory, created by Composer when missing. + */ + public static function run(array $arguments, string $cwd, string $home): ProcessResult + { + return self::process([...self::requireCommand(), ...$arguments], $cwd, $home); + } + + /** + * Runs a PHP script, such as `vendor/bin/scaffold`, with the current PHP binary in `$cwd`. + * + * @param list $arguments Script path followed by its arguments. + * @param string $cwd Working directory. + */ + public static function runPhp(array $arguments, string $cwd): ProcessResult + { + return self::process([PHP_BINARY, ...$arguments], $cwd); + } + + /** + * Copies the entries of this working tree that make up the plugin package to `$target`. + * + * @param string $target Absolute path of the snapshot directory. + */ + public static function snapshot(string $target): void + { + self::ensureDirectory($target); + + foreach (self::PLUGIN_ENTRIES as $entry) { + $source = self::root() . "/{$entry}"; + + if (is_file($source)) { + self::copyFile($source, "{$target}/{$entry}"); + + continue; + } + + $iterator = new RecursiveIteratorIterator( + new RecursiveDirectoryIterator($source, FilesystemIterator::SKIP_DOTS), + RecursiveIteratorIterator::SELF_FIRST, + ); + + /** @var SplFileInfo $file */ + foreach ($iterator as $file) { + $destination = "{$target}/{$entry}/" . substr($file->getPathname(), strlen($source) + 1); + + $file->isDir() + ? self::ensureDirectory($destination) + : self::copyFile($file->getPathname(), $destination); + } + } + } + + /** + * Copies `$source` to `$destination`, creating the parent directory. + */ + private static function copyFile(string $source, string $destination): void + { + self::ensureDirectory(dirname($destination)); + + if (!copy($source, $destination)) { + throw new RuntimeException(sprintf('Could not copy "%s".', $source)); + } + } + + /** + * Returns the path repositories of the packages that the plugin requires, directly or transitively, read from this + * `vendor/`; a package that this `vendor/` holds as a symlink, such as one installed from a path repository, is + * linked instead of copied. + * + * @return list> + */ + private static function dependencies(): array + { + $installed = json_decode( + (string) file_get_contents(self::root() . '/vendor/composer/installed.json'), + true, + flags: JSON_THROW_ON_ERROR, + ); + + $packages = is_array($installed) && is_array($installed['packages'] ?? null) ? $installed['packages'] : []; + $byName = []; + + foreach ($packages as $package) { + if (is_array($package) && is_string($package['name'] ?? null) && is_string($package['version'] ?? null)) { + $byName[$package['name']] = $package; + } + } + + $repositories = []; + $queue = array_keys(self::pluginRequirements()); + + while ($queue !== []) { + $name = array_shift($queue); + $package = $byName[$name] ?? null; + + if ($package === null) { + continue; + } + + unset($byName[$name]); + + $path = self::root() . "/vendor/{$name}"; + + $repositories[] = self::pathRepository($path, $name, $package['version'], is_link($path)); + + foreach (is_array($package['require'] ?? null) ? array_keys($package['require']) : [] as $required) { + if (is_string($required) && str_contains($required, '/')) { + $queue[] = $required; + } + } + } + + return $repositories; + } + + /** + * Creates `$path` when it does not exist. + */ + private static function ensureDirectory(string $path): void + { + if (!is_dir($path) && !mkdir($path, 0o777, true) && !is_dir($path)) { + throw new RuntimeException(sprintf('Could not create directory "%s".', $path)); + } + } + + /** + * Returns the environment of a subprocess: the current one, offline, without interaction, Xdebug or audit, with + * `$home` as `COMPOSER_HOME` when given, and without the variables that redirect Composer. + * + * @return array + */ + private static function environment(string|null $home): array + { + $environment = getenv(); + + foreach (['COMPOSER', 'COMPOSER_VENDOR_DIR', 'COMPOSER_BIN_DIR', 'COMPOSER_AUTH', 'XDEBUG_CONFIG'] as $name) { + unset($environment[$name]); + } + + if ($home !== null) { + $environment['COMPOSER_HOME'] = $home; + $environment['COMPOSER_CACHE_DIR'] = "{$home}/cache"; + } + + return [ + ...$environment, + 'COMPOSER_DISABLE_NETWORK' => '1', + 'COMPOSER_NO_INTERACTION' => '1', + 'COMPOSER_NO_AUDIT' => '1', + 'COMPOSER_ALLOW_SUPERUSER' => '1', + 'XDEBUG_MODE' => 'off', + ]; + } + + /** + * Returns the command prefix for the first Composer found, or `null`. + * + * @return list|null + */ + private static function locate(): array|null + { + $configured = getenv('COMPOSER_BINARY'); + + if (is_string($configured) && $configured !== '') { + return is_file($configured) ? self::prefix($configured) : null; + } + + foreach (explode(PATH_SEPARATOR, (string) getenv('PATH')) as $directory) { + foreach (['composer.phar', 'composer'] as $name) { + $candidate = rtrim($directory, '/\\') . DIRECTORY_SEPARATOR . $name; + + if ($directory !== '' && is_file($candidate)) { + return self::prefix($candidate); + } + } + } + + return null; + } + + /** + * Returns a path repository that installs `$url` as `$name` at `$version`. + * + * @param bool $symlink Whether to link `$url` instead of copying it. + * + * @return array + */ + private static function pathRepository(string $url, string $name, string $version, bool $symlink = false): array + { + return [ + 'type' => 'path', + 'url' => $url, + 'options' => ['symlink' => $symlink, 'versions' => [$name => $version]], + ]; + } + + /** + * Returns the package requirements of the plugin, platform requirements such as `php` excluded, read from the + * `require` section of this `composer.json`. + * + * @return array + */ + private static function pluginRequirements(): array + { + $manifest = json_decode( + (string) file_get_contents(self::root() . '/composer.json'), + true, + flags: JSON_THROW_ON_ERROR, + ); + + $require = is_array($manifest) && is_array($manifest['require'] ?? null) ? $manifest['require'] : []; + $requirements = []; + + foreach ($require as $name => $constraint) { + if (is_string($name) && is_string($constraint) && str_contains($name, '/')) { + $requirements[$name] = $constraint; + } + } + + return $requirements; + } + + /** + * Returns the command prefix that executes a Composer file: the file itself on Windows when it is a batch file + * without a PHP sibling, otherwise the current PHP binary followed by the file. + * + * @return list + */ + private static function prefix(string $file): array + { + if (str_ends_with($file, '.bat') || str_ends_with($file, '.cmd')) { + $sibling = substr($file, 0, -4); + + foreach ([$sibling . '.phar', $sibling] as $candidate) { + if (is_file($candidate)) { + return [PHP_BINARY, $candidate]; + } + } + + return [$file]; + } + + return [PHP_BINARY, $file]; + } + + /** + * Runs `$command` in `$cwd` and captures its output through temporary files, which cannot dead-lock. + * + * @param list $command Executable followed by its arguments. + * @param string $cwd Working directory. + * @param string|null $home `COMPOSER_HOME` of the process, or `null` to keep the inherited one. + */ + private static function process(array $command, string $cwd, string|null $home = null): ProcessResult + { + $base = sys_get_temp_dir() . '/scaffold-process-' . uniqid('', true); + + $process = proc_open( + $command, + [0 => ['pipe', 'r'], 1 => ['file', "{$base}.out", 'w'], 2 => ['file', "{$base}.err", 'w']], + $pipes, + $cwd, + self::environment($home), + ); + + if ($process === false) { + throw new RuntimeException(sprintf('Could not start "%s".', implode(' ', $command))); + } + + if (isset($pipes[0])) { + fclose($pipes[0]); + } + + $result = new ProcessResult( + proc_close($process), + (string) file_get_contents("{$base}.out"), + (string) file_get_contents("{$base}.err"), + ); + + unlink("{$base}.out"); + unlink("{$base}.err"); + + return $result; + } + + /** + * Returns the absolute path of this working tree. + */ + private static function root(): string + { + return dirname(__DIR__, 2); + } +} diff --git a/tests/Support/RecordingEventDispatcher.php b/tests/Support/RecordingEventDispatcher.php new file mode 100644 index 0000000..435ec28 --- /dev/null +++ b/tests/Support/RecordingEventDispatcher.php @@ -0,0 +1,52 @@ + + */ + public array $calls = []; + + public function __construct() + { + parent::__construct(new Composer(), new NullIO()); + } + + /** + * Records the subscriber, then registers its listeners. + * + * @param EventSubscriberInterface $subscriber Subscriber to register. + */ + public function addSubscriber(EventSubscriberInterface $subscriber): void + { + $this->calls[] = ['addSubscriber', $subscriber]; + + parent::addSubscriber($subscriber); + } + + /** + * Records the listener, then removes it. + * + * @param (callable(): mixed)|object $listener Callable or object whose listeners are removed. + */ + public function removeListener($listener): void + { + $this->calls[] = ['removeListener', $listener]; + + parent::removeListener($listener); + } +} diff --git a/tests/Support/StrictTestInterceptor.php b/tests/Support/StrictTestInterceptor.php new file mode 100644 index 0000000..fdf4720 --- /dev/null +++ b/tests/Support/StrictTestInterceptor.php @@ -0,0 +1,76 @@ +status === Status::Passed && $errors !== []) { + return $result + ->with(status: Status::Failed) + ->withFailure(new RuntimeException(implode("\n", $errors))); + } + + if ($result->status === Status::Risky) { + return $result + ->with(status: Status::Failed) + ->withFailure(new RuntimeException('Test performed no assertion.')); + } + + return $result; + } +} diff --git a/tests/Support/StrictTestPlugin.php b/tests/Support/StrictTestPlugin.php new file mode 100644 index 0000000..77c9799 --- /dev/null +++ b/tests/Support/StrictTestPlugin.php @@ -0,0 +1,26 @@ +get(InterceptorCollector::class)->addInterceptor(new StrictTestInterceptor()); + } +} diff --git a/tests/Support/TempDirectoryTrait.php b/tests/Support/TempDirectoryTrait.php index 85ecce3..f8ebed9 100644 --- a/tests/Support/TempDirectoryTrait.php +++ b/tests/Support/TempDirectoryTrait.php @@ -9,12 +9,20 @@ use RecursiveIteratorIterator; use RuntimeException; use SplFileInfo; +use Testo\Core\Exception\SkipTest; +use Testo\Lifecycle\{AfterTest, BeforeTest}; +use function chmod; +use function dirname; +use function function_exists; use function is_dir; use function is_link; use function mkdir; +use function posix_geteuid; +use function realpath; use function rmdir; use function sprintf; +use function symlink; use function sys_get_temp_dir; use function uniqid; use function unlink; @@ -22,6 +30,9 @@ /** * Provides a temporary directory that is created before each test and removed after. * + * Testo runs {@see self::setUpTempDirectory()} and {@see self::tearDownTempDirectory()} through their lifecycle + * attributes. + * * Pure-PHP recursive cleanup: walks the tree leaf-first, unlinks files and symlinks, then `rmdir`s directories. * * On Windows `rmdir` handles directory symlinks cleanly when their target has already been removed; plain file symlinks @@ -32,16 +43,37 @@ trait TempDirectoryTrait /** * Path to the temporary directory for the current test. */ - private string $tempDir = ''; + protected string $tempDir = ''; /** - * Recursively creates `$path` if it does not exist, failing the current test with a descriptive message when the + * Creates a symbolic link at `$link` whose target is in a directory that does not exist, so writes through the + * link fail, skipping the current test on Windows, where creating symbolic links needs extra privileges. + * + * Call it from the test body: a skip thrown from a Testo hook aborts the test instead. + * + * @param string $link Absolute path of the link to create. + */ + protected function createDanglingLink(string $link): void + { + if (DIRECTORY_SEPARATOR === '\\') { + throw new SkipTest('Creating symbolic links needs extra privileges on Windows.'); + } + + $this->ensureTestDirectory(dirname($link)); + + symlink("{$this->tempDir}/missing-directory/target", $link); + } + + /** + * Recursively creates `$path` if it does not exist, failing the current test with a descriptive exception when the * directory cannot be created. * * Intended for test seed helpers that materialize nested fixture paths and would otherwise swallow a silent `mkdir` * failure behind a less informative downstream I/O warning. * * @param string $path Absolute path of the directory to ensure. + * + * @throws RuntimeException if the directory cannot be created. */ protected function ensureTestDirectory(string $path): void { @@ -50,17 +82,40 @@ protected function ensureTestDirectory(string $path): void } if (mkdir($path, 0o777, recursive: true) === false && !is_dir($path)) { - self::fail(sprintf('Failed to create test directory "%s".', $path)); + throw new RuntimeException(sprintf('Failed to create test directory "%s".', $path)); } } + /** + * Sets the permission bits of the file at `$path`, skipping the current test on Windows and as root, where + * permission bits do not deny access. + * + * Call it from the test body: a skip thrown from a Testo hook aborts the test instead. + * + * @param string $path Absolute path of the file whose permissions are restricted. + * @param int $mode Permission bits to set, such as `0o000` (no access) or `0o444` (read-only). + */ + protected function restrictFileAccess(string $path, int $mode): void + { + if (DIRECTORY_SEPARATOR === '\\' || (function_exists('posix_geteuid') && posix_geteuid() === 0)) { + throw new SkipTest('Permission bits do not deny access on Windows or as root.'); + } + + chmod($path, $mode); + } + /** * Creates a unique temporary directory for the current test. * * The directory is created in the system's temp directory and is automatically removed after the test completes. * - * @throws RuntimeException if the temporary directory cannot be created. + * The canonical path is kept, so it matches paths that the code under test resolves with `realpath()`: Windows + * expands 8.3 short names (such as `RUNNER~1`) and uses its native separator, and macOS resolves `/var` to + * `/private/var`. + * + * @throws RuntimeException if the temporary directory cannot be created or resolved. */ + #[BeforeTest] protected function setUpTempDirectory(): void { $path = sys_get_temp_dir() . '/scaffold-test-' . uniqid('', true); @@ -69,7 +124,13 @@ protected function setUpTempDirectory(): void throw new RuntimeException(sprintf('Could not create temp directory "%s".', $path)); } - $this->tempDir = $path; + $real = realpath($path); + + if ($real === false) { + throw new RuntimeException(sprintf('Could not resolve temp directory "%s".', $path)); + } + + $this->tempDir = $real; } /** @@ -77,6 +138,7 @@ protected function setUpTempDirectory(): void * * Uses a pure-PHP implementation to ensure consistent behavior across platforms, especially regarding symlinks. */ + #[AfterTest] protected function tearDownTempDirectory(): void { if ($this->tempDir === '' || !is_dir($this->tempDir)) { diff --git a/tests/Support/bootstrap.php b/tests/Support/bootstrap.php deleted file mode 100644 index 49ce66e..0000000 --- a/tests/Support/bootstrap.php +++ /dev/null @@ -1,7 +0,0 @@ - 'string $directory, int $permissions = 0777, bool $recursive = false, $context = null', - 'arguments' => '$directory, $permissions, $recursive, $context', -]; -$stubs['file_put_contents'] = [ - 'signatureArguments' => 'string $filename, mixed $data, int $flags = 0, $context = null', - 'arguments' => '$filename, $data, $flags, $context', -]; -$stubs['file_get_contents'] = [ - 'signatureArguments' => 'string $filename, bool $use_include_path = false, $context = null, int $offset = 0, ?int $length = null', - 'arguments' => '$filename, $use_include_path, $context, $offset, $length', -]; -$stubs['rename'] = [ - 'signatureArguments' => 'string $from, string $to, $context = null', - 'arguments' => '$from, $to, $context', -]; -$stubs['copy'] = [ - 'signatureArguments' => 'string $from, string $to, $context = null', - 'arguments' => '$from, $to, $context', -]; - -return $stubs;