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 @@
-
+
@@ -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
+[](https://codecov.io/github/php-forge/scaffold)
[](https://github.com/php-forge/scaffold/actions/workflows/static.yml)
[](https://github.com/php-forge/scaffold/actions/workflows/quality.yml)
[](https://github.styleci.io/repos/1212894073?branch=main)
+## Built with AI
+
+[](https://claude.com/claude-code)
+[](https://openai.com/codex)
+[](https://www.coderabbit.ai)
+
## Our social networks
[](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