diff --git a/composer.json b/composer.json index da3f7e9b35..257e1e2532 100644 --- a/composer.json +++ b/composer.json @@ -16,7 +16,7 @@ "nette/neon": "^4.0", "nette/schema": "^1.4 || ^2.0", "nette/utils": "^4.1", - "phpsyntax/phpsyntax": "^1.0", + "phpsyntax/phpsyntax": "^1.0.1", "phpstan/phpdoc-parser": "^2.4", "composer/semver": "^3.4" }, @@ -50,7 +50,7 @@ }, "extra": { "branch-alias": { - "dev-master": "1.4-dev" + "dev-master": "1.5-dev" } } } diff --git a/docs/dresscode.annotated.neon b/docs/dresscode.annotated.neon index e38f3ba499..456ed457e8 100644 --- a/docs/dresscode.annotated.neon +++ b/docs/dresscode.annotated.neon @@ -582,3 +582,6 @@ upgrading: # what a newer PHP writes or retired forbiddenMembers: {} # a member that may not be used attributeForAnnotation: {} # an attribute written for an annotation; a namespace mask with `\*` attributeForMember: {} # an attribute written for a member the class declares by convention + unseen: # what an upgrade cannot see, reported where it stands + classNameString: reported # the string `'Acme\Old'` naming a class the maps rename or forbid. Also: keep + dynamicAccess: reported # `$object->$method()`, `new $class`, `call_user_func($callback)`. Also: keep diff --git a/docs/internals.md b/docs/internals.md index a46c57fdeb..a3a27c475c 100644 --- a/docs/internals.md +++ b/docs/internals.md @@ -25,7 +25,7 @@ Public: Internal: -- `Engine\*`, `Interop\*`, `Config\*`, `Measuring\*`, `Console\*`: the engine, the translation of foreign configurations, the rest of the configuration, the measuring of `init` and the console +- `Engine\*`, `Interop\*`, `Config\*`, `Measuring\*`, `Upgrade\*`, `Console\*`: the engine, the translation of foreign configurations, the rest of the configuration, the measuring of `init`, the estimate, the plan and the run of `upgrade` and the console - `Reporter`, `Reporters\*`: the formats of the output, whose contract is the output itself, and the interface they implement next to them; they print the `Engine\RunResult` of a run - `Rules\NodeHelpers`, `Rules\ListLayout`, `Rules\Compiler`, `Rules\NativeType`, `Rules\Classes\PropertyWrites`, `Rules\Classes\MemberModifiers`, `Rules\Functions\ForwardingClosure`, `Rules\Namespaces\NameReferences`, `Rules\Namespaces\QualificationPolicy`, `Rules\PhpDoc\AnnotationReplacement`, `Rules\PhpDoc\PhpdocTypeNotationVisitor`, `Rules\Whitespace\BlankLineClaims`, `Rules\Whitespace\Padding`: what the rules share among themselves or a rule does in a class of its own - `Rules\Upgrading\AnnotationArguments`, `Rules\Upgrading\CallableLiteral`, `Rules\Upgrading\CallTemplate`, `Rules\Upgrading\ClassReplacement`, `Rules\Upgrading\MagicCall`, `Rules\Upgrading\MemberTarget`, `Rules\Upgrading\AttributeTarget`, `Rules\Upgrading\Rewrite`, `Rules\Upgrading\AttributeForMemberEntry`, `Rules\Upgrading\AnnotationMap`, `Rules\Upgrading\enums.php`: the helpers of the rules fed by maps that are not the grammar of the maps @@ -189,7 +189,7 @@ A violation also carries the span of what it is about, `Violation::$offset` and `--lines` narrows what a run reports to those lines of the file as read (`Engine\LineRanges`, over the result of the file before the reporter and the summary see it): a violation is listed where its original lines reach into a range or where it has none, the rest is counted in `FileResult::$unlisted` and decides no exit code. The rules, the suppressions and the cache see the whole file, so a fix still fixes all of it. It takes one file, the `agent` format and no `--strict-rules`. -`--before ` gives the text the file had before the edit, and then what the file did not follow is its own style rather than the edit's mistake: the decisions that text violates, found by processing it first (`CheckCommand::findBrokenDecisions()`), are left as the file writes them (`ReportPolicy::$leftAsWritten`: `report()` answers false and the pass loop holds it like a refused fix), and every other decision is fixed in the whole file, because a violation of a decision the file kept is one the edit made, wherever it stands: an import whose last use it removed, the lines it put into a new block. The listing follows (`LineRanges` with the decisions left): a violation of a kept decision is listed wherever it is, one of a decision left only where it waits for a judgement, a risky fix or none, on the lines of `--lines`, and the agent is told the decisions left whose violations have a plain fix, which are the style of the file to write in. A file whose old text breaks a decision anywhere thus has it left everywhere, which keeps the file consistent: an edit of a file indented by spaces stays indented by spaces. +`--before ` gives the text the file had before the edit, and then what the file did not follow is its own style rather than the edit's mistake: the decisions that text violates, found by processing it first (`Console\RunExecutor::findBrokenDecisions()`), are left as the file writes them (`ReportPolicy::$leftAsWritten`: `report()` answers false and the pass loop holds it like a refused fix), and every other decision is fixed in the whole file, because a violation of a decision the file kept is one the edit made, wherever it stands: an import whose last use it removed, the lines it put into a new block. The listing follows (`LineRanges` with the decisions left): a violation of a kept decision is listed wherever it is, one of a decision left only where it waits for a judgement, a risky fix or none, on the lines of `--lines`, and the agent is told the decisions left whose violations have a plain fix, which are the style of the file to write in. A file whose old text breaks a decision anywhere thus has it left everywhere, which keeps the file consistent: an edit of a file indented by spaces stays indented by spaces. ### Baseline @@ -213,19 +213,21 @@ The violations reported are those of the first round, whose positions belong to `FileFinder::findFiles()`, which a run holds as `Runner::$files` and `RunnerFactory::createFileFinder()` gives without building a run, finds the files (patterns with a slash are anchored to the root, without one they match a segment at any depth, both also match directories on the way, and `**/` is no directory or any number of them, as in gitignore, a pattern that is no valid glob being refused when the configuration is read; a file named on the command line is taken as it is, and only `--skip-excluded`, which a hook or an editor naming every file it touches passes, lets the excluded paths leave it out like a found one, and the configured `paths` leave out what they do not hold; the excluded paths are those of the configuration and its plugins over `Config::DefaultExcludePaths`, and a `.gitignore` is not read, what it ignores, a build or a cache, being left out by `excludePaths` where the defaults miss it) and `Runner::run()` takes that list, reads and writes the files and hands results to a `Reporter`. The caller expands the paths so that it knows the scope before the run starts. A path named on the command line is relative to the working directory, and `FileFinder::narrowPaths()` narrows a named directory that holds some of the configured `paths` to those, so that `fix .` in the root never reaches beyond them, while a path outside them is taken as named, unless `--skip-excluded` says the caller names every file it touches. -The format is the whole contract of the output, never a switch modifying another one: `console` unless `--format` says otherwise, `github` when `GITHUB_ACTIONS` says the run is a step of a workflow, `json` and `checkstyle` for tools (the JSON document says its `version`, the `mode` and the `root` of the run, its keys are camelCase and the values from the code stand as they are, the `severity` of a violation being `error` or `warning` and its `risk` `typeUnknown`, `nameUncertain` or `behaviorChanges`, the backing values of `Severity` and `Risk`, the span of a violation as `offset` and `length` and where it ends as `endLine` and `endColumn`, null where it has none, a key removed, renamed or meaning another thing being a new version and a key added none), `lines` for a hook of git and the linters of an editor, one line for every event in the shape a compiler writes (`path:line:column: severity: message [decision; risk=…]`, the column where the span starts when it starts on that line, the path relative to the working directory or absolute and with forward slashes, a message on one line, a clean or merely rewritten file printing nothing), `agent` for an AI agent that has just edited the files (`Reporters\AgentReporter`: sentences on stdout naming the file as the command line named it, what a fix wrote as the hunks of a fenced diff with their standard headers, the imports it removed by name from `FileResult::$removedImports`, and every violation left with what to do about it, the reason of a risky fix it did not make and the comment the configuration of the file accepts from `suppressionComments`, never `dresscode:ignore`; a clean file says nothing, a rewrite is claimed only where the file was written, the warnings of the configuration are left out by the command, and the whole message keeps to a budget of lines and bytes, a diff that does not fit giving way to a summary naming the decisions of the rules that changed the file, `FileResult::$mutatedRules`, and a listing that does not fit saying how many it left out). The header naming the configuration file and the scope belongs to the command (`Console\Commands\CheckCommand`) and is written, together with the warning that Xdebug makes the run many times slower, only for the console and github formats; the progress bar only for the console format on a terminal, where it is a status of the very console the report goes to, so that writing the report erases it. The console format lists twenty violations of a file and counts the rest by decision on one line, the formats for tools listing every one. A fix run lists every file it touched exactly once, with a `rewritten` note and under it what the fixed text still violates; which violation a fix removed cannot be told from the text, so the verdict counts what was found and what remains, and `--diff` shows what changed. +The format is the whole contract of the output, never a switch modifying another one: `console` unless `--format` says otherwise, `github` when `GITHUB_ACTIONS` says the run is a step of a workflow, `json` and `checkstyle` for tools (the JSON document says its `version`, the `mode` and the `root` of the run, its keys are camelCase and the values from the code stand as they are, the `severity` of a violation being `error` or `warning` and its `risk` `typeUnknown`, `nameUncertain` or `behaviorChanges`, the backing values of `Severity` and `Risk`, the span of a violation as `offset` and `length` and where it ends as `endLine` and `endColumn`, null where it has none, a key removed, renamed or meaning another thing being a new version and a key added none), `lines` for a hook of git and the linters of an editor, one line for every event in the shape a compiler writes (`path:line:column: severity: message [decision; risk=…]`, the column where the span starts when it starts on that line, the path relative to the working directory or absolute and with forward slashes, a message on one line, a clean or merely rewritten file printing nothing), `agent` for an AI agent that has just edited the files (`Reporters\AgentReporter`: sentences on stdout naming the file as the command line named it, what a fix wrote as the hunks of a fenced diff with their standard headers, the imports it removed by name from `FileResult::$removedImports`, and every violation left with what to do about it, the reason of a risky fix it did not make and the comment the configuration of the file accepts from `suppressionComments`, never `dresscode:ignore`; a clean file says nothing, a rewrite is claimed only where the file was written, the warnings of the configuration are left out by the command, and the whole message keeps to a budget of lines and bytes, a diff that does not fit giving way to a summary naming the decisions of the rules that changed the file, `FileResult::$mutatedRules`, and a listing that does not fit saying how many it left out). The header naming the configuration file and the scope belongs to the run of the command (`Console\RunExecutor`, which `check`, `fix`, `baseline` and `upgrade` share) and is written, together with the warning that Xdebug makes the run many times slower, only for the console and github formats; the progress bar only for the console format on a terminal, where it is a status of the very console the report goes to, so that writing the report erases it. The console format lists twenty violations of a file and counts the rest by decision on one line, the formats for tools listing every one. A fix run lists every file it touched exactly once, with a `rewritten` note and under it what the fixed text still violates; which violation a fix removed cannot be told from the text, so the verdict counts what was found and what remains, and `--diff` shows what changed. `fix --stdin` is the formatter of an editor, which reads the text and the exit code alone: the whole fixed text goes to stdout and nothing to stderr, with exit code 0 whatever the text still violates, an empty input being valid; a syntax error gives the text back as it came with one line on stderr and exit code 1, a failure the same with exit code 2, and a path `--skip-excluded` leaves out the text as it came without a word. It writes nothing to the disk and refuses the options of a report, `--format`, `--diff`, `--max-warnings` and `--ask-risky`, with the advice of `check --stdin`, which reports on the code in any format, and nothing at all of a path `--skip-excluded` leaves out; the warnings of the configuration are not printed. -A rule exception or a cycle fails that one file (nothing is written, the run goes on, exit code 2, also for a runtime error of the tool), and so does a file that cannot be read or written, and a file whose text on the disk is no longer the one processed when the fix is about to write it, so that what an editor saved meanwhile is never overwritten; a syntax error is exit code 1 like a violation, and so is a baseline refused, while a mistake of the command line or of the configuration, and a program run without a command, is exit code 3, which is no result of a run at all. The fix writes a file through a temporary one renamed over it, so that an interrupted run never leaves it cut short, and in place where no temporary file can be made beside it or renamed over it (a directory that is not writable, a file mounted on its own, on Windows a file another process holds). +A rule exception or a cycle fails that one file (nothing is written, the run goes on, exit code 2, also for a runtime error of the tool), and so does a file that cannot be read or written, and a file whose text on the disk is no longer the one processed when the fix is about to write it, so that what an editor saved meanwhile is never overwritten; a syntax error is exit code 1 like a violation, and so is a baseline refused, while a mistake of the command line or of the configuration, and a program run without a command, is exit code 3, which is no result of a run at all; an upgrade waiting at a step outside DressCode, for Composer or for a human, is exit code 4. The fix writes a file through a temporary one renamed over it, so that an interrupted run never leaves it cut short, and in place where no temporary file can be made beside it or renamed over it (a directory that is not writable, a file mounted on its own, on Windows a file another process holds). A `ResultCache` (one JSON file per project root in `cacheDir` or the system temp) remembers every content that came out clean under the effective configuration: the rules and the values of the decisions, the selection of `only`, style, PHP version, the same of every override resolved on its own, so that a preset only an override uses counts too, the installed version of each package of the project with the reference of the source it came from (`ProjectPackages::getIdentity()`), the same of each package of the running process, which is where the tool, its PHPStan and the extensions of it come from wherever they are not installed in the project, its root and the roots inside a phar left out (`RunnerFactory::getProcessIdentity()`), the times and sizes of the files of the rule, preset and analysis classes neither a package of the process nor a phar holds, which a rule of the project itself changes under the same version (a process without Composer knows no package, so every file outside a phar counts), and so of every PHP and NEON file of the source trees of DressCode and PhpSyntax, whose helpers and data the rules stand on, where they are a working tree rather than a package, and the text of the configuration file, hashed by `RunnerFactory::hashConfiguration()`. That text is all that describes a rule or an analysis a closure builds, so such a closure must build from nothing but what the text says, and a run with a closure and no file is not cached. A content is remembered by its path together with its text, because an override or a rule reading the path gives the same text in two files two verdicts; `Runner::run()` skips such a file with a `cached` result, its text read again when it is reported and processed after all where it is no longer the text the cache knew, and, after a fix whose text has nothing remaining, remembers the written content too, unless there is a baseline, whose entries no run has yet held against the fixed lines. With the types a result also depends on what other files of the project declare and on the `phpstan.neon` of the project, so the identity then holds the time and size of every file under the analysed paths, the configuration of PHPStan and `installed.json` (`RunnerFactory::fingerprintProject()`): a change anywhere throws the cache away, which is the price of a clean verdict that stays true after a pull or a rebase. What that configuration includes, its stubs and bootstrap files outside those paths, only the container of PHPStan knows, and a run served whole by the cache builds none, so the run that builds one records them with their stamps in the cache (`PhpStan::getConfigurationFiles()`, a worker sending them with its first result after it knows them, `ResultCache::recordDependencies()`), and the next run drops the cache where any of them changed; those of PHPStan itself and those in its temporary directory are left out. A file modified in the second before the run began or later, where a change in the same second would leave its time and size as they were, adds the hash of its text, as git does with the files it calls racy, which holds for the files of the rules too; a file restored with an older time and the same size is the one limit left. `--no-cache` serves no file from it but remembers what the run finds, forgetting a content it found not clean; `processCode()` (stdin) never uses it. -With `--jobs` above 1 (by default the processor count, capped at one worker per four files, because a worker costs about that much to start; an explicit `--jobs` is taken as given) the files not served by the cache go to a `WorkerPool`. Worker processes are started with the same command line plus a hidden `--worker
`, under the `php.ini` of the parent (`-c`, or `-n` where it loaded none) and with the settings the parent has beyond it, those of `-d` among them, which PHP tells no process, so the parent asks the same PHP for its settings and passes on the difference as `-d`, and connect to a TCP server on the loopback: `stream_select()` handles no pipes on Windows before PHP 8.5, and where it does, a message over a pipe costs there hundreds of times what it costs over the loopback, so the server stays whatever the minimum version. `Console\Application::run()` turns OPcache off on Windows, where the processes of a run share its memory and PHP with JIT crashes once they fill it. With the types, a worker fills the cache of PHPStan before it connects (`PhpStan::warmUp()`), and the pool starts the others only once the first has connected: workers started together would all write the same cold cache, which on Windows makes every write slow and fails the renames over a file another worker holds. A worker that has not connected within the connect timeout of the pool fails the run, which with the types bounds that warm-up. A worker receives one path at a time and answers with the `FileResult` as a line of JSON (`Engine\WorkerCodec`), the path both ways and the output base64-encoded, since neither need be UTF-8. The parent reads the connections without blocking and puts a line together from its parts, because waiting for the rest of one would stop it from hearing the other workers and from noticing a stuck one; it takes an answer only about the path it gave that worker, and a worker spending longer than the timeout of the pool on one file fails the run, since a rule has most likely looped. The listening socket is closed as soon as the last worker is in, because on Windows closing it later costs every run a wait, and it comes from ext/sockets where there is one, because closing one of the stream layer there waits half a second. +With `--jobs` above 1 (by default the processor count, capped at one worker per four files, because a worker costs about that much to start; an explicit `--jobs` is taken as given) the files not served by the cache go to a `WorkerPool`. Worker processes are started with the same command line plus a hidden `--worker
`, under the `php.ini` of the parent (`-c`, or `-n` where it loaded none) and with the settings the parent has beyond it, those of `-d` among them, which PHP tells no process, so the parent asks the same PHP for its settings and passes on the difference as `-d`, and connect to a TCP server on the loopback: `stream_select()` handles no pipes on Windows before PHP 8.5, and where it does, a message over a pipe costs there hundreds of times what it costs over the loopback, so the server stays whatever the minimum version. `Console\Application::run()` turns OPcache off on Windows, where the processes of a run share its memory and PHP with JIT crashes once they fill it. With the types, a worker fills the cache of PHPStan before it connects (`PhpStan::warmUp()`), and the pool starts the others only once the first has connected: workers started together would all write the same cold cache, which on Windows makes every write slow and fails the renames over a file another worker holds. A worker that has not connected within the connect timeout of the pool fails the run, which with the types bounds that warm-up. A worker receives one path at a time and answers with the `FileResult` and what it measured for `--profile` as a line of JSON (`Engine\WorkerCodec`), the path both ways and the output base64-encoded, since neither need be UTF-8. The parent reads the connections without blocking and puts a line together from its parts, because waiting for the rest of one would stop it from hearing the other workers and from noticing a stuck one; it takes an answer only about the path it gave that worker, and a worker spending longer than the timeout of the pool on one file fails the run, which a looping rule and an answer that cannot reach the parent cause alike, so the message points to `--jobs 1`, a run without workers. The listening socket is closed as soon as the last worker is in, because on Windows closing it later costs every run a wait, and it comes from ext/sockets where there is one, because closing one of the stream layer there waits half a second. A process working through files, the parent without workers and every worker, keeps the cycle collector of PHP off and collects between two files once the memory has doubled since what the last collection left, never above three quarters of `memory_limit` (`Engine\CycleCollector`). The collector PHP runs by itself scans again and again what stays alive, the tree being processed and above all the reflection of PHPStan, and frees little: with the types it took a third of the run. -A worker only processes and, when fixing, writes; the parent keeps the cache and the baseline, reads a file again when it hands it out, reports every file in the order of the input as soon as the files before it are done and keeps of its result what the run needs without the code and the output (`Engine\FileSummary`), so that only the files in progress and those waiting for an earlier one are held as text, and turns a worker that dies or exits with an error into a failure of the run. +A worker only processes and, when fixing, writes; the parent keeps the cache and the baseline, reads a file again when it hands it out, reports every file in the order of the input as soon as the files before it are done and keeps of its result what the run needs without the code and the output and with the violations only counted (`Engine\FileSummary`, `Engine\ViolationTally`), so that only the files in progress and those waiting for an earlier one are held whole, a run whose violations code consumes one by one taking them through `Reporters\CollectingReporter`, and turns a worker that dies or exits with an error into a failure of the run. + +The hidden option `--profile ` of `check`, `fix`, `baseline` and `upgrade today` writes where the time of the run went as JSON (`Engine\Profiler`): the phases of processing a file (parse, passes, print, each round counted, and the gaps the engine decides along the traversal, the claims of the rules included), the callbacks of every rule with the calls that changed the tree, the time of the closures of every gap rule's claims, the start of PHPStan, its derived containers and scopes, the collections of cycles, the fifty slowest files with the phases of each, the size and the time of every file, and the peak memory of every process. A worker hands over what it measured with every file, beside its result, and, once nothing is left, what it measured since in an answer to `finish`, which the pool waits for from every worker, one that started too late to get a file among them; the parent adds it up, so the counts do not depend on `--jobs`; the result cache is off, since a file it serves has nothing to measure. Off, the profiler costs a null check around each callback of a rule; on, it costs the clock read twice around each, so its times say where the time goes and the times of a run without it how much there is. ## Configuration @@ -239,7 +241,7 @@ The keys at the top are either reserved or sections (`Config\Catalogue::Reserved What the PHP notation passes as an object or a callable the NEON writes as an entity in three places only, a plugin in `use`, `skipWhen` and the factory of an analysis: `Class(args)` is a new object, `Class::method(args)` what the static method returns, `Class::method(...)` the method itself, and in a chain `Class(args)::method(args)` a link calls the method on what the link before it gave. An entity is evaluated when the file is read, one of `use` only once its class is known to be a plugin, so that a configuration of a repository someone merely checks cannot run other code by naming it. A rule of the project is named by its class in NEON; one built by a factory, a recipe evaluated at every build, is given by `dresscode.php`. In the decisions an entity stands only in the maps of the upgrading data, whose grammar takes one (`isMethod(POST)`). The schema keeps only the keys the file gave, so that an absent key keeps the default of the constructor, and it takes a single entry of `use` without a list (`use: nette`). -`Loader::find()` walks upwards and takes, in each directory, the local file before the `.dist` template; the two formats side by side are an ambiguity it refuses rather than resolves. A configuration file is the only thing laid over a project, and `--config` names it (its format follows its extension); a wrapper binary that wants a configuration to apply in a project without one hands `Console\Application` a `defaultConfig`, which the loader uses when it finds no file, and the workers get it because they are started with the same script. Without a file the root is the directory of the nearest `composer.json`, else the working directory, as for the target version, so that a run from a subdirectory shares the cache, the relative paths and the patterns of a `defaultConfig` with a run from the root. The command line is no key of a file: it is a profile laid over everything the file says, `--use` naming a preset or a plugin as `use` of a file does, `--set path=value` a decision (the value is NEON, decoded as the value in a file) and `--fix-risky=` what it accepts; `--only` is a parameter of `RunnerFactory::resolve()` and `--strict-rules` one of `RunnerFactory::createRunner()`. +`Loader::find()` walks upwards and takes, in each directory, the local file before the `.dist` template; the two formats side by side are an ambiguity it refuses rather than resolves. A configuration file is the only thing laid over a project, and `--config` names it (its format follows its extension); a wrapper binary that wants a configuration to apply in a project without one hands `Console\Application` a `defaultConfig` and its own `script`, the loader using the configuration when it finds no file, and the workers getting it because they are started with that script. Without a file the root is the directory of the nearest `composer.json`, else the working directory, as for the target version, so that a run from a subdirectory shares the cache, the relative paths and the patterns of a `defaultConfig` with a run from the root. The command line is no key of a file: it is a profile laid over everything the file says, `--use` naming a preset or a plugin as `use` of a file does, `--set path=value` a decision (the value is NEON, decoded as the value in a file) and `--fix-risky=` what it accepts; `--only` is a parameter of `RunnerFactory::resolve()` and `--strict-rules` one of `RunnerFactory::createRunner()`. ### The catalogue @@ -255,7 +257,7 @@ A plugin stands in `use` of the configuration beside the presets, by class or as ### What the packages bring -A package installed with the project speaks without being named: `Config\PackageDiscovery` reads `vendor/composer/installed.json` of the nearest `composer.json`, the root package included, and takes from every package what its `composer.json` says under `extra.dresscode`: `plugin`, a class loaded where `use` of the configuration names the package or the plugin, the root package needing no name, a plugin bringing code that runs in every check and therefore let in by the project as Composer lets in its own plugins, the others being a warning (a package of the vendor `dresscode` is named with the vendor or without it, as a preset of the core is, a package named so makes its name no preset, and a package and a preset of the same name are an error; a key of `extra.dresscode` that DressCode does not know, `PackageDiscovery::Keys` being the ones it does, is a warning of the run and a problem for `Testing\UpgradingTester`, the package possibly being newer than the tool), and `upgrading-dir`, the directory of the upgrading files, every NEON file in it, `upgrading/.neon` by convention (`PackageDiscovery::findUpgradingFiles()`). Such a file says what the versions of a library retired and what to write instead: `package` names the package whose versions the sections are of (the carrier itself, or the library a package of rules carries the file for), and every section `since ` holds the maps that version brought, the renames it made as `replacedClasses` and `replacedMembers`, a map of a rule of a plugin by the path of its decision, and a rule of the plugin the package ships itself turned on by the path of its requirement and a word (`acme.statusEnum: required` from the version that made the rewrite right), which a section above the lowest version leaves off without reporting anything. A map the project writes under `upgrading.api` itself turns its rule on, and `upgrading.packages: yes` lays the maps and the requirements of every file under it; a file names no intent, because the same entry is an offer of a newer form when a version brings it and a retirement once a later one drops the old, which the section `since ` already says. The sections the lowest version the code must work with reaches are merged in the order of their versions whatever order the file writes them in (newest first, as a guide to upgrading is written), a later one having the last word on an entry, every one where any version does, none where the versions have no lower bound, a package the project does not require among them, none for a package the project does not have, and a section above the lowest version says nothing, though the constraint allows a version it holds for, because the code must still work with the lowest one, where its fix would break the code, as the tests with the lowest dependencies show; an entry whose fix is right before the version that retired what it replaces says from which one, `{write: …, from: '8.0'}`, and is rewritten wherever the lowest version reaches that one, the map getting the entry without it, and the versions of the sections holding what is not rewritten stay with the data (`UpgradingData::$unreached`). The file is read and checked by `Config\UpgradingFile::fromFile()` and laid out for a constraint by `selectFor()`; the data keep the words of the file, and the version that retired an entry of a forbidden map (`UpgradingData::$retirements`) ends its sentence only where the data are laid (`UpgradingData::buildDecisions()`, ``Function `acme_old()` is deprecated: use `acme_new()`, since acme/lib 4.0``), so that `Testing\UpgradingTester` checks the sentence its author wrote; the key is spelled `since 3.10` because NEON reads a bare `3.10` as the number 3.1. A value is handed over as NEON reads it, so what it reads as an entity (`isPaid()`) is for the domain of the map to take. A member is spelled the way PHP reads it, `Class::name` for a constant or a method, whichever the code reaches, `Class::name(...$args)` for a method alone where a constant of that name exists too (parentheses make a key of replacedMembers a method whatever they hold, while replacedCalls reads them as the shape of the arguments, empty ones as none, and a placeholder with a type in front of it, `array $options` or `list $values`, as one only for an argument the types say is of it; the template unpacking such an argument, `...$options`, is risky where its keys are not seen, it being neither an array literal nor a list), `Class::$name` for a property and `Class::$name::get` or `Class::$name::set` for one of its two uses, a read (`isset()` among them) or a write (any assignment, `unset()`), as the hooks of PHP divide them, which is how `replacedCalls` gives the expression of each and `forbiddenMembers` forbids a write alone, and the replacement is the name alone for the same class, `Class::name` for another, or `\function` for the global function a method becomes. What a version took back, a later section withdraws with the value `keep` in place of the replacement, and so does any layer of the project, in the map of `replacedClasses` and of `replacedFunctions` as well; the entry never reaches the rule (`Upgrading\MemberMapGrammar`, the grammar such maps share, which also takes a value NEON reads as an entity, `isMethod(POST)`, and reads its arguments the way NEON gives them: a placeholder, a number, `Class::NAME` and a nested call as written, any other string as a string, quoted or not; what that cannot say is a string holding the whole code). +A package installed with the project speaks without being named: `Config\PackageDiscovery` reads `vendor/composer/installed.json` of the nearest `composer.json`, the root package included, and takes from every package what its `composer.json` says under `extra.dresscode`: `plugin`, a class loaded where `use` of the configuration names the package or the plugin, the root package needing no name, a plugin bringing code that runs in every check and therefore let in by the project as Composer lets in its own plugins, the others being a warning (a package of the vendor `dresscode` is named with the vendor or without it, as a preset of the core is, a package named so makes its name no preset, and a package and a preset of the same name are an error; a key of `extra.dresscode` that DressCode does not know, `PackageDiscovery::Keys` being the ones it does, is a warning of the run and a problem for `Testing\UpgradingTester`, the package possibly being newer than the tool), and `upgrading-dir`, the directory of the upgrading files, every NEON file in it, `upgrading/.neon` by convention (`PackageDiscovery::findUpgradingFiles()`). Such a file says what the versions of a library retired and what to write instead: `package` names the package whose versions the sections are of (the carrier itself, or the library a package of rules carries the file for), and every section `since ` holds the maps that version brought, the renames it made as `replacedClasses` and `replacedMembers`, a map of a rule of a plugin by the path of its decision, and a rule of the plugin the package ships itself turned on by the path of its requirement and a word (`acme.statusEnum: required` from the version that made the rewrite right), which a section above the lowest version leaves off without reporting anything. A map the project writes under `upgrading.api` itself turns its rule on, and `upgrading.packages: yes` lays the maps and the requirements of every file under it; a file names no intent, because the same entry is an offer of a newer form when a version brings it and a retirement once a later one drops the old, which the section `since ` already says. The sections the lowest version the code must work with reaches are merged in the order of their versions whatever order the file writes them in (newest first, as a guide to upgrading is written), a later one having the last word on an entry, every one where any version does, none where the versions have no lower bound, a package the project does not require among them, none for a package the project does not have, and a section above the lowest version says nothing, though the constraint allows a version it holds for, because the code must still work with the lowest one, where its fix would break the code, as the tests with the lowest dependencies show; an entry whose fix is right before the version that retired what it replaces says from which one, `{write: …, from: '8.0'}`, and is rewritten wherever the lowest version reaches that one, the map getting the entry without it, and the versions of the sections holding what is not rewritten stay with the data (`UpgradingData::$unreached`). The file is read and checked by `Config\UpgradingFile::fromFile()` and laid out for a constraint by `selectFor()`; the data keep the words of the file, and the version that retired an entry of a forbidden map (`UpgradingData::$retirements`) ends its sentence only where the data are laid (`UpgradingData::buildDecisions()`, ``Function `acme_old()` is deprecated: use `acme_new()`, since acme/lib 4.0``), so that `Testing\UpgradingTester` checks the sentence its author wrote; the key is spelled `since 3.10` because NEON reads a bare `3.10` as the number 3.1. Each section is laid as a layer of its own, an entry reached by its `from` in a layer of the section with that version (`Layer::$library`, `$since`, `$from`), so that `dresscode config` says where a value came from (`application.neon of dresscode/upgrade-nette, since 3.2`) and a rule reporting an entry passes its section on (`Values::getEntryOrigin()`, `MemberMapEntry::$origin`, `RuleContext::report(source:)`) to `Violation::$source`, which the format `json` writes as `source`; every entry stands in one of those layers, so their order decides nothing `selectFor()` has not decided already. A value is handed over as NEON reads it, so what it reads as an entity (`isPaid()`) is for the domain of the map to take. A member is spelled the way PHP reads it, `Class::name` for a constant or a method, whichever the code reaches, `Class::name(...$args)` for a method alone where a constant of that name exists too (parentheses make a key of replacedMembers a method whatever they hold, while replacedCalls reads them as the shape of the arguments, empty ones as none, and a placeholder with a type in front of it, `array $options` or `list $values`, as one only for an argument the types say is of it; the template unpacking such an argument, `...$options`, is risky where its keys are not seen, it being neither an array literal nor a list), `Class::$name` for a property and `Class::$name::get` or `Class::$name::set` for one of its two uses, a read (`isset()` among them) or a write (any assignment, `unset()`), as the hooks of PHP divide them, which is how `replacedCalls` gives the expression of each and `forbiddenMembers` forbids a write alone, and the replacement is the name alone for the same class, `Class::name` for another, or `\function` for the global function a method becomes. What a version took back, a later section withdraws with the value `keep` in place of the replacement, and so does any layer of the project, in the map of `replacedClasses` and of `replacedFunctions` as well; the entry never reaches the rule (`Upgrading\MemberMapGrammar`, the grammar such maps share, which also takes a value NEON reads as an entity, `isMethod(POST)`, and reads its arguments the way NEON gives them: a placeholder, a number, `Class::NAME` and a nested call as written, any other string as a string, quoted or not; what that cannot say is a string holding the whole code). Such a file sets maps, the requirements of the rules of the plugin of its own package and, under `namespaces` as the configuration writes them, what the namespaces of the package declare for the files a project writes into them, and nothing else: no package may decide how the code of the project is written, so a requirement of the core or of another plugin is a `ConfigurationException` (`PluginRegistry::findPackageSection()`). `ConfigResolver` lays them under every layer of the project, where `upgrading.packages` is `yes`; a map this DressCode does not know is a warning, because the package may be newer than the tool. PHP is a library like any other: what its versions retired is `src/Rules/Upgrading/php.neon` in the same grammar, the data of the platform package `php` (`PackageDiscovery::readPhpData()`), cut by the target of PHP as a package is by its constraint and laid where the requirement `upgrading.php.deprecatedApi` is `forbidden`, which the standard `nette` says without the data of the libraries, and what they say is reported under that requirement, not under the map (`Values::getEntryDecision()`, `MemberMapEntry::$decision`), so that `only`, `severity` and a suppression name it as any other; a fix right before the version that deprecated the function says so with `from`, `curl_close()` doing nothing since PHP 8.0 though deprecated in 8.5, and the values of arguments PHP deprecated, which no map can name, are `NoDeprecatedPhpArgumentsRule` under `upgrading.php.deprecatedArgument`. The result cache needs nothing new, the values a rule ends up with being in its identity, and so are the versions of the installed packages. @@ -289,7 +291,7 @@ The excluded paths only ever add up, the default list, those of the plugins and `dresscode catalogue` prints the catalogue of the installed set and `--format json` gives it as data, versioned (`Catalogue::Version`): every decision with its kind, its domain as data, its description and notes, the rules declaring it with what each requires, the values of the five standards as a configuration writes them and the names of the other tools whose rules it covers. It is the interface an editor of the configuration is built on, and `composer reference` writes `docs/reference/decisions.md` from the same data. -The output of `init` and `migrate` gives every word one meaning and every count its unit: a *finding* is what a rule reports in the code, an *excluded file* a file the scope leaves out with the reason, and *unchecked* a decision written as `keep`. A *place* is where the code makes a decision, which init measures. +The output of `init`, `upgrade` and `migrate` gives every word one meaning and every count its unit: a *finding* is what a rule reports in the code, an *automatic change* a fix made without asking, a *manual task* a finding no fix makes, left to a person, an *accepted exception* a suppression with its reason, one without a reason not accepted yet, an *excluded file* a file the scope leaves out with the reason, an *unverified file* one a check could not process, and *unchecked* a decision written as `keep`. A *place* is where the code makes a decision, which init measures, and a *topic* the unit of an upgrade, as its plan file names it. ### The target version of PHP @@ -297,7 +299,7 @@ The versions of PHP the rules target are a property of the checked project, neve The version a rule asks about travels as a plain string compared with `version_compare()`, never with the string operators, under which 8.9 outranks 8.10, and always in the short form `Config\Versions::shortenVersion()` gives, without the zeros a normalized one pads with, because `version_compare()` takes `8.1` for older than `8.1.0`. NEON reads a bare number as a version whose minor is a single digit, which every PHP ever released has had, so `8` and `8.0` both mean 8.0, and `php` in `targets` may carry a patch version, so no rule takes the string apart by position. The running interpreter is never the answer, so that the same file gets the same verdict from any directory under any PHP; only `Lexer` asks about the runtime, to emulate the tokens its own build does not know. -What PHP itself declares is the same kind of question, and a rule asks `Analyses\PhpSymbols` about it rather than `function_exists()` or reflection, which would answer with the extensions and the version of the machine: the catalog holds every version from 8.0 on, so what depends on the version, which versions declare a function at all, is compared with the target, and what PHP retired is in its upgrading data, `src/Rules/Upgrading/php.neon`. The parameters of those functions are a catalog of their own, `Analyses\PhpSignatures`, because they are two thirds the size of the rest and the command line compiles what it loads on every run, so only a rule that asks about them pays for it; it answers with `Parameter`, whose `canReplace()` says whether an argument written for one parameter may stand at another and whose `default` is known where every version from 8.0 on declares the same scalar, and it knows nothing of the extensions its source cannot see, where a rule then has no answer rather than a wrong one. A rule whose construct exists only from some version on says so with `requires: ['php' => '>=8.4']` in its `#[RuleInfo]`, a Composer constraint written as the `require` of `composer.json` writes it, all of it read by `composer/semver` (`Config\Versions`) and never by hand, and a range, a single version being refused because it would turn the rule off for every other release; an upper bound says a rule writes what a later version took away. It is metadata and never a directory, so that a rule lives with its topic and the reference can index the catalogue by the version a rule needs, and `ConfigResolver` leaves it out below that version: silently when a preset wrote its decisions, with a warning when the project wrote them. A rule that needs the version more finely than "run me or not" asks `RuleContext::$phpVersion` instead, and never about anything PHP 8.0 already had. The version in `requires` and the one read from `RuleContext::$phpVersion` say since when the fix is right, never since when the code it replaces is a problem: the target is the oldest version the code runs on, not the newest, so the upgrading data of PHP remove `curl_close()` only where every version of the target has made it a no-op, while a rule about a deprecation whose replacement older versions know too (`NoNullArrayKeysRule`, `NoSleepAndWakeupRule`, `RedundantArgumentsRule`) asks no version at all, the code meeting the deprecation wherever it runs on a later one, and neither does `OptimizedCallNotationRule` writing the arguments of an optimized call, an argument written by position being right everywhere and optimized wherever the code runs on 8.4 or later. A fix naming a class of PHP needs the version that declares it, though older ones parse the name and ignore an attribute they do not know: `OverrideAttributeRequiredRule`, `SensitiveParameterRequiredRule` and `DeprecatedAttributeForAnnotationRule` require the version of their attribute, code naming a class the target does not declare being no fix for that target. A package in `requires` is the same question asked of `Config\ProjectPackages`, which answers from the `composer.json` of the project and the `installed.json` beside it, never from the Composer of the running process: for a package the project requires itself the versions are those its constraint allows, because code written for a newer one breaks wherever the constraint lets an older one in, so a constraint without a lower bound allows every version, for a package that only comes with another, which the project promises nothing about, it is every version too, the installed one never answering, the alias of a development branch the project requires standing for the newest of its line, a package an installed one replaces with its own version, a part of a monorepo installed as the whole, is had in the version of the one replacing it, and any version does for the project itself and for a branch without an alias. The packages in `targets` of the configuration (`targets: {acme/mailer: '3.3'}`) say the version of an installed package outright and come before all of that (`ProjectPackages::withTargets()`), so that code is fixed for a version while the one before it is still installed and its members still have a declaration to read; the version is quoted, because NEON reads a bare `3.10` as the number 3.1. The resolver leaves a rule whose package the project does not have, or has in a version its requirement does not allow, out as it does a rule too new for the target, and the sections `since` of a package's deprecations are cut by the lowest of those versions. A rule that makes no sense without the types of the code says so with `typesRequired`, and the resolver leaves it out where the configuration sets no `typeAnalysis` (a fact of the project, which a preset may not state): silently when a preset or the data of a package wrote its decisions, so that a preset may write them whatever the project has, and as a `ConfigurationException` when the configuration or the command line wrote them, because the project then asked for what it cannot get and a run without the rule would lie. The registry builds `Analyses\Types` only where the configuration asked for the types, so `getAnalysis()` of them throws elsewhere. A rule that would only do better with them asks `RuleContext::findAnalysis()`, which answers `null` where the run has none (`ReplacedClassesRule` then writes a class without asking whether the project has it), or does without them altogether, and says in its docblock what it then cannot see, in one shape: `Without the types, is not told from .` Its correctness never rests on them: without the types the rule breaks nothing, what it cannot tell apart being risky or left alone, and the types only narrow that. Such a rule answers in three states (`Tristate`): for certain yes, the fix is safe; for certain no, the rule says nothing, never offering a fix it knows is wrong; maybe, the fix is risky with `Risk::TypeUnknown`. The declarations in sight give the answer first (a parameter, a property, a method of `$this`, whose types a child may not turn into another), and the types narrow what they leave as maybe, through a question `Types` already answers (`isSubtype()` in `StaticForMethodWithoutThisRule`, `findParameters()` in `PipeForNestedCallsRule`). A question of `Types` about a fact whose no a caller may act on answers in `Tristate` too (`isOfType()`, `isSubtype()`, `isInterface()`, `isFinalClass()`, `isAttributeClass()`, `isStaticMethod()`, `isPlainProperty()`, `isComparedAlike()`), maybe for a class nothing declares and for one whose hierarchy is not seen whole, a parent, an interface or a trait of it or of an ancestor being one nothing declares, and for an expression of type `never`, which stands where the code never runs and which PHPStan takes for a subtype of every type; a question asking whether something may be done answers `bool`, `true` only where it certainly may (`canReplace()`, `matchesParentSignature()`). `hasMember()` answers `bool` although it asks about a fact, a class nothing declares having no member: what the maps of members ask with it is whether the code still reaches a declaration, and a member a library removed together with its class is as undeclared as one removed from the class alone. +What PHP itself declares is the same kind of question, and a rule asks `Analyses\PhpSymbols` about it rather than `function_exists()` or reflection, which would answer with the extensions and the version of the machine: the catalog holds every version from 8.0 on, so what depends on the version, which versions declare a function at all, is compared with the target, and what PHP retired is in its upgrading data, `src/Rules/Upgrading/php.neon`. The parameters of those functions are a catalog of their own, `Analyses\PhpSignatures`, because they are two thirds the size of the rest and the command line compiles what it loads on every run, so only a rule that asks about them pays for it; it answers with `Parameter`, whose `canReplace()` says whether an argument written for one parameter may stand at another and whose `default` is known where every version from 8.0 on declares the same scalar, and it knows nothing of the extensions its source cannot see, where a rule then has no answer rather than a wrong one. A rule whose construct exists only from some version on says so with `requires: ['php' => '>=8.4']` in its `#[RuleInfo]`, a Composer constraint written as the `require` of `composer.json` writes it, all of it read by `composer/semver` (`Config\Versions`) and never by hand, and a range, a single version being refused because it would turn the rule off for every other release; an upper bound says a rule writes what a later version took away. It is metadata and never a directory, so that a rule lives with its topic and the reference can index the catalogue by the version a rule needs, and `ConfigResolver` leaves it out below that version: silently when a preset wrote its decisions, with a warning when the project wrote them. A rule that needs the version more finely than "run me or not" asks `RuleContext::$phpVersion` instead, and never about anything PHP 8.0 already had. The version in `requires` and the one read from `RuleContext::$phpVersion` say since when the fix is right, never since when the code it replaces is a problem: the target is the oldest version the code runs on, not the newest, so the upgrading data of PHP remove `curl_close()` only where every version of the target has made it a no-op, while a rule about a deprecation whose replacement older versions know too (`NoNullArrayKeysRule`, `NoSleepAndWakeupRule`, `RedundantArgumentsRule`) asks no version at all, the code meeting the deprecation wherever it runs on a later one, and neither does `OptimizedCallNotationRule` writing the arguments of an optimized call, an argument written by position being right everywhere and optimized wherever the code runs on 8.4 or later. A fix naming a class of PHP needs the version that declares it, though older ones parse the name and ignore an attribute they do not know: `OverrideAttributeRequiredRule`, `SensitiveParameterRequiredRule` and `DeprecatedAttributeForAnnotationRule` require the version of their attribute, code naming a class the target does not declare being no fix for that target. A package in `requires` is the same question asked of `Config\ProjectPackages`, which answers from the `composer.json` of the project and the `installed.json` beside it, never from the Composer of the running process: for a package the project requires itself the versions are those its constraint allows, because code written for a newer one breaks wherever the constraint lets an older one in, so a constraint without a lower bound allows every version, for a package that only comes with another, which the project promises nothing about, it is every version too, the installed one never answering, the alias of a development branch the project requires standing for the newest of its line, a package an installed one replaces with its own version, a part of a monorepo installed as the whole, is had in the version of the one replacing it, and any version does for the project itself and for a branch without an alias. The packages in `targets` of the configuration (`targets: {acme/mailer: '3.3'}`) say the version of an installed package outright and come before all of that (`ProjectPackages::withTargets()`), so that code is fixed for a version while the one before it is still installed and its members still have a declaration to read; the version is quoted, because NEON reads a bare `3.10` as the number 3.1. The targets of a command line, PHP among them, lie over those of the configuration before the upgrading data are cut (`RunnerFactory::mergeTargets()`), so that a run for versions the project has not moved to yet sees the sections of those versions as reached. The resolver leaves a rule whose package the project does not have, or has in a version its requirement does not allow, out as it does a rule too new for the target, and the sections `since` of a package's deprecations are cut by the lowest of those versions. A rule that makes no sense without the types of the code says so with `typesRequired`, and the resolver leaves it out where the configuration sets no `typeAnalysis` (a fact of the project, which a preset may not state): silently when a preset or the data of a package wrote its decisions, so that a preset may write them whatever the project has, and as a `ConfigurationException` when the configuration or the command line wrote them, because the project then asked for what it cannot get and a run without the rule would lie. The registry builds `Analyses\Types` only where the configuration asked for the types, so `getAnalysis()` of them throws elsewhere. A rule that would only do better with them asks `RuleContext::findAnalysis()`, which answers `null` where the run has none (`ReplacedClassesRule` then writes a class without asking whether the project has it), or does without them altogether, and says in its docblock what it then cannot see, in one shape: `Without the types, is not told from .` Its correctness never rests on them: without the types the rule breaks nothing, what it cannot tell apart being risky or left alone, and the types only narrow that. Such a rule answers in three states (`Tristate`): for certain yes, the fix is safe; for certain no, the rule says nothing, never offering a fix it knows is wrong; maybe, the fix is risky with `Risk::TypeUnknown`. The declarations in sight give the answer first (a parameter, a property, a method of `$this`, whose types a child may not turn into another), and the types narrow what they leave as maybe, through a question `Types` already answers (`isSubtype()` in `StaticForMethodWithoutThisRule`, `findParameters()` in `PipeForNestedCallsRule`). A question of `Types` about a fact whose no a caller may act on answers in `Tristate` too (`isOfType()`, `isSubtype()`, `isInterface()`, `isFinalClass()`, `isAttributeClass()`, `isStaticMethod()`, `isPlainProperty()`, `isComparedAlike()`), maybe for a class nothing declares and for one whose hierarchy is not seen whole, a parent, an interface or a trait of it or of an ancestor being one nothing declares, and for an expression of type `never`, which stands where the code never runs and which PHPStan takes for a subtype of every type; a question asking whether something may be done answers `bool`, `true` only where it certainly may (`canReplace()`, `matchesParentSignature()`). `hasMember()` answers `bool` although it asks about a fact, a class nothing declares having no member: what the maps of members ask with it is whether the code still reaches a declaration, and a member a library removed together with its class is as undeclared as one removed from the class alone. ### The namespaces of the project @@ -329,7 +331,17 @@ The file is written by `Config\Draft`, as `dresscode migrate config` writes its What is the user's to decide init does not decide for them, it asks (`Measuring\Questions`, each a `Question` with its `Answer`s and a place of the code it is about, which a terminal shows with what a fix makes of it, the file fixed in the process under the value and narrowed to the decision, `Proposal::previewFix()`, unless the fix changes only blank lines, indentation or the spaces ending a line, which a diff of lines does not show): first a close call of standards the formatter did not decide, whose answer measures again against the other standard, then, after the check over the whole scope, at most five questions of decisions, the costliest first: a value the budget left unchecked, a value of the code the rules of the formatter contradict, and names no rule renames that share a prefix or a suffix, read from the code the rule reports, which the baseline lists as the recommended answer and `naming.except` may let pass, now and later; the values the budget left unchecked beyond the five are one question more, listing each with what its fix costs, one answer checking them all, so that no decision is left unchecked without a word. Every question's recommended answer, the first, never rewrites code the measuring kept, and Enter takes it; an answer that keeps the value of the code writes it as the user's, which the budget never leaves unchecked, and an answer giving the value of the standard writes nothing, nor does the report list it among the values written, the standard saying it already (`Proposal::findWrittenValues()`). The configuration is checked again with the answers where they changed it, and what that check leaves over the budget is the next round of questions, asked whatever their number, as they follow from the answers. Whether to take the standard as it is is no question: the line `Measured` says how many files of the sample it would rewrite, mostly for one decision the code holds to everywhere, such as where a standard that moved writes `declare(strict_types=1)`. Without a terminal, with `--yes` and with `--format json` init asks nothing and takes the recommended answers, so the file is the one Enter gives, and prints each question as the line of `dresscode.neon` or the command that answers it otherwise; the JSON document (`InitPrinter::toArray()`) says its `version` and the `root`, the scope, the sample, the standard with the files a fix changes under each, every value with its comment and origin, the regions, what the check over the whole scope says, those lines as `instructions`, the files a rule failed in, the configuration and the file it was `written` to, over a configuration that exists what has moved as `shifts` (`Proposal::findShifts()`), and nothing else is written to the output. The rules of the formatter are those its configuration translates to; a configuration of PHP CS Fixer is PHP, which translating runs, so init translates it only where `--formatter` named it, `--yes` agrees or, as in `migrate config`, the user agrees in a terminal (`CommandContext::chooseFormatterConfig()`, `confirmReadingRules()`). The end of the report says whether those rules were compared with the code or not read at all, never carried over either way, and that `dresscode migrate config` translates them instead of measuring the code, as the summary of `migrate config` names `init` for the other way. `init --set` gives a decision a value whatever was measured (`Proposal::answer()`), written with "your answer" unless the standard gives it and never left unchecked by the budget, as is an answer. With `--dry-run` init prints the configuration after the report and writes nothing, `--jobs` limits the processors its probes share, `1` running them in-process, and `--formatter` names the configuration of the formatter to take where the evidence chose another. Over a configuration that exists init compares the code with it, the standard and the decisions it gives, over the files it checks (`Scope::fromConfig()`), those an override gives decisions of their own left out and said, a comparison left with no file ending with exit code 2, the presets it names resolved with its plugins, which a probe names by their class and runs with in this process where the configuration is of PHP, which may declare them; it asks nothing and takes no answer, as it writes nothing, `--set` being refused, a file that cannot be read stopping it with why before anything is measured, and a local file chosen before a `.dist` template as the loader chooses it; measures against the standard that file names and prints every decision it would write otherwise with the files a fix under the value of the file would rewrite, and every one the file sets apart from the standard while the code holds to the standard, which no departure from the standard shows (`InitPrinter::printShifts()`), so that running it again after an upgrade of DressCode or a while of work says what has moved; init over its own file says nothing has. -The output says each phase as it comes, a status line while it runs with a spinner and the probes done, the spinner turning on through the one long probe of the check of the whole scope: the project and what is left out of it, the version of PHP, the standard and what the code departs from it in, the values taken from the code, what a fix of the whole scope changes and what it leaves, and the commands to run next. A line says the fact first and in gray what it rests on or what to do about it, so that the eye reads the facts down the lines; what the configuration or the command line writes is code, a decision with its value, a preset, a file, a command and the values a measurement counts, in the comments of the file too, and the values listed line up their comments as the file does. A line wider than a terminal breaks at spaces, the lines it adds indented to the values of the labels (`Markup::wrapLines()`), since the terminal would break it under the labels; a log or a pipe gets it whole, and the configuration `--dry-run` prints stays as the file writes it. The printer of init returns its text drawn, every piece once (`Markup::formatLine()`, the label, the text, what it rests on and the rest), and the command writes it as it is, so that no drawing meets code a drawing before it made. A probe running longer than half an hour ends init with that, its process ended with what it started, as every command DressCode runs is (`Engine\ProcessRunner`, its output into files, as a pipe on Windows is read only blocking). +The output says each phase as it comes, a status line while it runs with a spinner and the probes done, the spinner turning on through the one long probe of the check of the whole scope: the project and what is left out of it, the version of PHP, the standard and what the code departs from it in, the values taken from the code, what a fix of the whole scope changes and what it leaves, and the commands to run next. A line says the fact first and in gray what it rests on or what to do about it, so that the eye reads the facts down the lines; what the configuration or the command line writes is code, a decision with its value, a preset, a file, a command and the values a measurement counts, in the comments of the file too, and the values listed line up their comments as the file does. A line wider than a terminal breaks at spaces, the lines it adds indented to the values of the labels (`Markup::wrapLines()`), since the terminal would break it under the labels; a log or a pipe gets it whole, and the configuration `--dry-run` prints stays as the file writes it. A printer, of init as of `upgrade`, returns its text drawn, every piece once (`Markup::formatLine()`, the label, the text, what it rests on and the rest), and the command writes it as it is, so that no drawing meets code a drawing before it made. A probe running longer than half an hour ends init with that, its process ended with what it started, as every command DressCode runs is (`Engine\ProcessRunner`, its output into files, as a pipe on Windows is read only blocking). + +### upgrade + +`dresscode upgrade today` is `fix` for a project that only moves to a newer PHP or newer libraries, which it says by raising the lower bounds of its constraints: the set `deprecations` (with `--modernize` also `modernizations`) is laid over the presets the configuration uses and beneath its own decisions and overrides (`ConfigResolver::$laid`), so that what the project keeps stays kept in the upgrade too, and the command line lays the plugins of the packages of upgrading data, which no `use` has to name, and `typeAnalysis: phpstan` over it all, a run asking for the types refusing to go without PHPStan beside DressCode (`RunnerFactory::resolve()`), and the versions are those the constraints of the project allow, as for any run, PHP among them (`RunnerFactory::readProjectPackages()`). The preface says which packages are installed newer than the lowest version allowed, whose declarations then say nothing of what that one deprecates, advising `composer update --prefer-lowest`, and which packages of upgrading data are not required with a lower bound, so that neither their data nor their declarations say anything (`ProjectPackages::findNewerInstalled()`, `isUnbounded()`). A project without a configuration file is the scope `init` would write, as for every command of an upgrade (`Upgrade\Project::fromConfig()`), with no style. A project with one keeps its scope, target, types, `fixRisky`, baseline and maps, and of its style only the decisions its code keeps: a check without the types and without the sets runs first over the code as it is, every decision it finds violated anywhere is left out whatever its severity, and the run is narrowed by `only` to the decisions left, the sets and the packages whose data reach the project, for the maps of their plugins no set covers (`Upgrade\Project::measureSatisfiedRequirements()`), which a worker gets through `--only` instead of checking again; `--only` of the command line narrows the run instead, and `--fix-risky`, `--ask-risky` and `--max-warnings` work as with `fix`, and the names are resolved for certain from what the namespaces of the scope declare (`Upgrade\Project::resolveNames()`). A file a generator wrote is left out, which the preface counts (`Upgrade\UpgradeFiles`). One run makes no fixed point over the files: where it rewrote a file, it advises running it again. The upgrading data of a library come from a package that says which libraries it is about under `extra.dresscode.packages`, as `dresscode/upgrade-nette` says `nette/`; discovery also finds one installed beside DressCode rather than in the project, a package of the type `dresscode-plugin` with upgrading files. DressCode knows no such package itself: what Packagist offers, for now of the vendor `dresscode` alone until a package of another vendor can be trusted, is asked once a day and remembered in the cache directory (`DataPackageCatalogue`), and `UpgradingTester::collectPackageProblems()` refuses a list that is not exactly the packages the upgrading files are about. A project requiring one of those libraries itself, in `require` or `require-dev`, a library coming with another one not counting, gets the package installed first, `composer require` into the installation of DressCode, or `require --dev` into the project where its lock holds DressCode: in a terminal writing for a human after asking, otherwise only with `--yes`, the run being refused with the command to run where neither holds (`Upgrade\DataPackageInstallation`); Composer is `Upgrade\Composer`, what it writes kept out of the output, and the command then starts again in a new process, whose autoloader knows the installed packages and the plugins they bring (`dresscode/upgrade-nette` brings one), or where it runs embedded in another program says to run it again, with exit code 4. + +An upgrade is about an `Upgrade\Project`, the configuration, the root, the configuration file and the command line, which lays one layer over the configuration for every run of an upgrade (`Project::createLayer()`). A run of a plan crosses three boundaries a test replaces to fail where it wants, given to `PlanRunner` by its constructor: the version control (`Upgrade\VersionControl`, `Git`), the packages (`PackageManager`, `Composer`) and the tests (`TestRunner`, `ProcessTestRunner`); the files and the state of a run stay real. What an upgrade to some versions costs is measured by `Upgrade\Estimator`, which changes no file: one check over the scope of the configuration (`Upgrade\UpgradeCheck`, which every check of an upgrade is) with the sets `deprecations`, `modernizations` and `cleanup` laid as `upgrade today` lays them, the packages of upgrading data that reach the project, the decisions `upgrading.unseen.*` and the targets, laid by the command line before the data are cut (`RunnerFactory::mergeTargets()`), and where the configuration says nothing of the names `nameResolution: certain` with what the namespaces of the scope declare (`Measuring\NamespaceDeclarations`), without which nearly every fix of a call of a function would wait as risky; the files the autoload of `composer.json` loads one by one declare too, wherever they lie, as they do for `init`, and a file that cannot be read, or that the autoload names and is not there, makes the names as uncertain as one that does not parse. Every violation is a place of a topic (`Upgrade\Topic`): the library of its entry of upgrading data (`Violation::$source`), else its decision, which are the names `--only` takes. Its phase (`Upgrade\Phase`) is the bridge, a fix made on the versions the project allows today, where the lowest of them reaches the version `from` or the section of the entry says, and for a place of no data where its decision runs for the project without the targets, which a second resolution tells; the jump otherwise. The text names it by the constraint its fixes are right on (`works on ^3.2`, `needs ^4.0`, `Topic::$constraint`): that of today in the bridge and the one the target raises it to in the jump, of the library of the topic, or of the one target where the topic is a decision of no library, the words `works today` and `after the raise` standing where neither is known. What the run can do about it (`Upgrade\Fixability`) is read off the violation: automatic, waiting for the types or for the names, or manual. A topic belongs to the first set whose decisions it is of, the data to `deprecations`. What the upgrade does not see is counted apart (`Upgrade\BlindSpots`): the places `Rules\Upgrading\UnseenReferencesRule` reports, a string naming a class the maps rename or forbid and a member, a class or a function reached by a name the code computes, the files of the scope no rule reads that an upgrade may change too (a template, a configuration) by their extension, and the files whose head says a generator wrote them, which the check leaves out. Where the project has a `composer.lock`, Composer is asked offline what of it refuses each target (`Upgrade\Composer`, `composer why-not --locked`, its lines parsed, the project itself left out), an answer it does not give within a minute or a failure being an unknown with its reason, never a failed run; the command is the script `COMPOSER_BINARY` names, run by the PHP of DressCode as Composer sets it for its scripts, or `composer` on the path, and an output that is no answer of `why-not`, which exits with 1 as a Composer that failed does, is an unknown too, and one that does not end in time is ended with its children. Unless the run is offline, Composer is asked too what raising the constraints to the targets as the plan raises them would move (`composer require --dry-run`, which needs the network, `Upgrade\Moves`, an unknown the same way), and the text lists the packages it moves across a major version, or a minor one below 1.0 (`Move::isMajor()`), the JSON document every one, each marked where the upgrading data do not reach the minor version it moves to (`Move::isKnown()`), `(no data)` where they stop below its major version, the hop a project makes with no help of DressCode, and `(data up to 4.1)` where they reach into it. Every failure of Composer is a `ComposerException` saying why, its last line or the time it ran out of, and naming the log in the temporary directory that keeps the command, its exit and all it wrote, which the questions of the estimate turn into an unknown and the raise of a run into a step left waiting. A package of upgrading data about a library the project requires, which neither the project nor DressCode has, is named with those libraries (`PackageDiscovery::findMissingDataPackages()`) and never installed. All of it is one `Upgrade\Estimate`, which `Console\EstimatePrinter` writes as text or as a JSON document of its own `version`, as `Console\PlanPrinter` writes the plan and `Console\RunOutcomePrinter` a run of it, as JSON in a document of its own with the plan it ran, the warnings of the run going to standard error. + +The command `upgrade` has its commands, and alone it lists them. `dresscode upgrade estimate [ []]` writes the estimate: for the package and the version named, for PHP up to the version named or the newest its upgrading data know, and without a target for what `Estimator::proposeTargets()` proposes, PHP and every library whose data know a version newer than the project allows. A project without a configuration is measured over the scope `init` would write, `--paths` narrows it, the types are those `--types` or `--no-types` says, the latter over a configuration asking for them too (`RunnerFactory` `withoutTypes`, which every run of the upgrade takes from its layer, the run of the project as it is today among them), else the configuration, else what the user answers in a terminal, a run outside one or writing a format other than `console` going without them, as the command asks nothing then (`UpgradeCommand::mayAsk()`), `--paths`, `--offline` and `--jobs` belong to the commands that measure, `estimate`, `plan` and `run` with a target, and `--offline` takes the catalogue of Packagist as the cache remembers it, however old. The options of a fix belong to `upgrade today` alone, so that the estimate never changes a file by accident. With `--jobs` the check runs in workers as `check` does, each repeating it from what the parent wrote into a file of the cache directory (`UpgradeCheck::write()`, with the scope of a project without a configuration, `UpgradeCheck::$scope`), which `--check-file` names, since the layer of the estimate holds what no option of the command line says. + +`upgrade plan` orders the estimate into the steps of an upgrade, written after the estimate, so that a plan never says less of what the upgrade cannot see or is not sure of (its JSON document holds the estimate under `estimate`) (`Upgrade\PlanBuilder`, `Upgrade\Plan`, each `Upgrade\Step` a `FixStep`, a `ComposerStep`, an `UpdateStep` or a `ManualStep`, the steps of Composer a `DependencyStep`): for each target something of the lock refuses, or Composer could not tell what does, a step for a human with the `composer why-not` to run; the fix of the topics of `deprecations` in the bridge; the raise of the constraints of `composer.json`, each in the shape the project writes it and with its upper bounds (`Upgrade\Constraints`): a part of `||` the target is past dropped and the lower bound of the others raised (`^8.4` for `^8.1`, `>=8.4` for `>=8.1`, `>=8.4 <8.5` for `>=8.1 <8.5`), and where the target is past every part, the last raised the same way (`~8.4.0` for `~8.1.0`), one with an upper bound of its own as a caret, which the title of the step says, left out where the lowest version allowed already reaches the target; the fix of the topics of `deprecations` in the jump; the fix of `cleanup`; and the fix of `modernizations`, which the plan leaves out until the user takes it in. A step is a recipe, never its result: a fix names its topics as `--only` takes them, and whatever it fixes is measured anew when the run comes to it, so the plan saved by `upgrade plan --save` into `dresscode-upgrade.neon` (`Upgrade\PlanFile`), with the version of its shape, the versions of DressCode and of the upgrading data it was made with, the commands of the tests, the paths `--paths` narrowed the estimate to, which its fixes, `upgrade tasks` and the suppressions it lists keep to, and what the estimate could not see under `estimate`, the files it could not process and the packages of upgrading data it lacked, which a run of the plan warns of, is a file the team reviews and edits, a step left out with `skip: true`; it is read strictly, a key it does not know, a value of another type, a name that is no package and a constraint Composer does not read refused with the path of the key, so that a typo never changes a run in silence. A plan of no step is saved as no file, so that a plan read is never empty. `upgrade run` with a target saves the plan and runs it, refusing to replace a saved one, which `upgrade plan --save` replaces; without a target it runs the saved one as it is, refusing the options that make a plan. Both need the configuration file, whose style the fixes keep (`Upgrade\PlanRunner`, which tells where it stopped by `Upgrade\RunStop`): each topic is fixed by a run over the project as it is, the sets laid beneath the configuration as `upgrade today` lays them, narrowed to the topic and the decisions the code keeps and without the targets, so that a topic of the bridge writes only what the versions allowed today know, and one of the jump, once Composer raised the constraints, what the new ones do. Whether a step is done is read from the code and the lock alone, a fix left with nothing to fix changing nothing, a manual step passing once `composer why-not --locked` says nothing of the lock refuses its target, the run waiting at it otherwise with what refuses it, or why Composer could not tell, a project without a lock among the reasons, and exit code 4, a step that is free left out with `skip: true`, and a step of Composer passing where `composer.json` requires every package of it with a lower bound reaching its constraint, its branches compared by version, and for one that updates where the version installed and the one of the lock are ones the step allows, and for PHP the `config.platform.php` the project sets, which a step raising PHP raises with it, a step of its own raising the platform alone where `composer.json` requires the target already and running `composer update --lock` after it (`ComposerStep::isDoneIn()`, `composer config platform.php`), so a run goes on from a working tree a team committed, squashed or rebased; at a step of Composer whose constraints are not raised yet it shows what `composer require -W --dry-run` would change and, once the user agrees (`$approve` of the run, `Console\Commands\RaiseApproval`, in a terminal after asking or with `--yes`, Composer not even asked without either), runs through the packages of the run (`PackageManager`) `composer require -W --prefer-lowest --minimal-changes` and goes on with the jump, the dry run being of copies of `composer.json` and the lock beside them, with the platform of PHP a step raises with it, so that it resolves what the raise will, a raise of the platform alone among it: the packages raised are at the lowest versions their constraints allow, which the code is written for and whose `@deprecated` the rewrites may read, the rest changed as little as the update needs, what that downgrades against the lock said apart before the user agrees, and the plan of an application ends with a step of Composer of its own updating every package to the newest version the constraints allow (`Upgrade\UpdateStep`, the kind `update` of the plan file), tested as every step and done once `composer update --dry-run` changes nothing; otherwise it stops with the `composer require` to run and exit code 4, and where Composer fails, with what it failed with (`RunOutcome::$composerFailure`). What the fixes of a run tell the user, an analysis that went without or names not resolved for certain, goes into its outcome as its warnings, in the text and in the JSON alike. A run of the whole plan goes on after every raise in a new process, which loads anew what the raise installed, the plugins, the libraries and the upgrading data among it, for the fixes, the tests and the check at the end alike (`RunStop::Raised`), and a raise no tests ran after yet is the one the journal keeps, so that a run started anew tests it too: the run hands over what it got to as data in a file a variable of the environment names (`RunOutcome::toArray()`), the new process goes on after the raise and alone says how far the whole run got, and a process started so hands back where it stopped at the next raise instead of starting one itself, its starter going on once for every step of Composer of the plan (`CommandContext::rerun()`, the program the one of the package, `WorkerPool::locateProgram()`); an embedded run, whose command line is not its own, stops after the raise with exit code 4. A library, a project of the `type` `library`, or of none, which Composer reads as `library`, without a lock of its own, which one its git ignores is not, keeps the versions it allows: its plan is the bridge and the constraints widened to the targets (`^3.2 || ^4.0` for `^3.2`), a step of Composer without `update` that requires them with `--no-update` (`ProjectPackages::isLibrary()`); one whose `type` says library while it has a lock of its own is asked about in a terminal and planned as Enter answers outside one, a library where the `type` is written and the application the lock makes it where none is, and `--library` or `--no-library` decides it either way, the line `Mode` saying which and why; it is decided before the estimate of a plan, which for a library asks Composer nothing of what the update moves, as widening installs nothing. What a fix leaves for a human, a violation it has no fix for or a risky one it refused, is a task (`Upgrade\Task`), listed by the last fix of its topic (`Upgrade\TopicReporter`), a risky one with what its fix waits for and how to allow it; after the step a raise leads to the run waits while the step leaves any, with exit code 1, a plan is done only once no task is left, its end waiting the same way, once no comment puts a place off without a reason, as `upgrade tasks` reads them, and once the set `deprecations` finds nothing more in the whole scope, which the plan checks at its end, not only the topics its estimate found, a library installed by a raise showing what it deprecates only then (`RunStop::Remaining`, exit code 1, with the files `upgrade today` fixes), `--step` names a step the plan runs or is refused, and a task is done once the code no longer has it or a `dresscode:ignore` (best with ` -- ` and the reason) or the baseline confirms it. `upgrade tasks` lists the tasks of the saved plan as the code stands, each with its line and the line above and below it as code, as the run of a plan lists those it leaves, the fixes run without writing, with those the check of the whole scope at the end of a run finds and no topic does under `deprecations`, and the comments `dresscode:ignore` about an upgrade that give no reason after ` -- `, which only put a task off, and the files the fixes cannot process (`PlanRunner::findTasks()`, `Upgrade\Postponement`, which reads the comments alone), with exit code 1 where a task or such a comment is left and 2 where a file is; a raise of the plan the project has not made yet hides the tasks of the steps after it, the code being read against the versions it requires today and a task needing the target being one its lowest versions break, so the last line and `due` of the JSON name the step the rest waits for (`Plan::findDueRaise()`). A fix runs without writing and the run writes what it changes (`Upgrade\TopicReporter`), each file kept as it was before the step before it is first written (`Upgrade\Snapshots`), in the directory of the git repository of the project, which clearing the cache does not take, or in the cache directory with a warning where git finds none, a file changed since the fix read it left as it is, and going back leaves a file changed since the step wrote it as it is too, keeping its text before the step; a file a fix cannot process, one that does not parse or a rule fails on, stops the run after its step with exit code 2 (`RunStop::Unprocessed`, `RunOutcome::getExitCode()` mapping every stop), and the estimate names such files, whose places it does not count. A run that finds the snapshots a step left unfinished, interrupted or gone back over a file changed since, runs nothing (`RunStop::Interrupted`, exit code 1): it lists the files the step may have rewritten, none where the snapshots cannot be read, which `upgrade abort` puts back as they were before the step, a file changed since left as it is, or `upgrade run --discard` drops the snapshots and goes on from the code as it is; `upgrade plan --save` refuses to forget them the same way, unless given `--discard`. Where `--test-command` (with `{junit}` for the JUnit file it writes) gives the tests, they run once before the first step and after every step, the quicker `--quick-test-command` where given except after the step a raise leads to and after the last one, and the whole suite after a raise no fix follows, whose dependencies then stay raised where the tests fail, `composer.json` and the lock being kept as they were before the first raise until a step after it is done (`Upgrade\ComposerJournal`), so that `upgrade abort` puts back those the raise changed and nobody since and runs `composer install`, which the run says wherever it stops with them changed, the journal staying while a file is left or the install failed, so that the next `upgrade abort` goes on from there, and `upgrade abort --dry-run` says what it would put back and leave, changing nothing; `upgrade status` runs no fix and says where the saved plan stands, a step of Composer done or due by the constraints, a manual step by what the lock refuses, a fix and a step to the newest versions left to `upgrade run`, and what a run keeps, the steps it did not finish, the raise it journals, the step it left uncommitted and when the tests ran before the first step (`Upgrade\PlanStatus`), always with exit code 0: a step after which a test fails that passed before, or after which the tests write no results, goes back byte for byte and the run ends with exit code 1 (`Upgrade\TestResults`, a test known by its `classname` and `name` with the root left out, a class and a method for PHPUnit, a file for Nette Tester): each passed, skipped, failed or thrown (`TestStatus`), the worst of them where one is repeated under its identity: a test that passed before and does not pass now, or is gone, fails, said how it ended; a command running out of time, writing no JUnit report or one of no test gives no results, and one ending with another exit code than 0, or than the 1 and 2 PHPUnit and Nette Tester end with for tests that did not pass, crashed, each of them told why, which fails the step, and before the first one stops the run before it changes anything (`RunStop::Tests` without a step, exit code 2, the run being incomplete), each command has a baseline of its own, which the run says it compared with, when it ran and how many of its tests did not pass then, so that a run with no new failure is not read as one whose tests pass, and a command without `{junit}` is refused when the plan is made and when the file of the plan is read. With `--commit` every topic becomes a commit of its own, with the files it changed as the topic left them and the trailer `DressCode-Upgrade-Step`, once the tests of its step passed and it processed every file, made from those texts through an index of its own, so that the working tree is never written for a commit and the hooks of the repository run as for any other; a file changed after its step wrote it, by the tests or by a hand, leaves the step uncommitted in the working tree, as the commit would hold a text the tests did not pass over, and where git refuses a commit the run stops with what is left uncommitted and which topics of the step it committed before (`RunStop::Commit`, exit code 2), its outcome kept as any other; a step leaving files it could not process stays uncommitted, kept as such with the snapshots and the results of the tests before the first step (`Upgrade\RunState`), and the run that processes them commits it whole, refusing where the plan edited since says something else under its number unless `--discard` forgets it, those files and the ones the step wrote being no changes of the working tree of its own, and a raise the run makes a commit of `composer.json` and the lock where git does not ignore them, so that the next run finds no changes of its own (`Upgrade\Git`); since a commit takes the files whole, it is refused before anything changes where the tracked files have changes of their own, the saved plan aside, or where git finds no repository tracking the project. What a run keeps is written whole through a temporary file of its own, a snapshot before its index and the index before the file of the project, two runs never work in one project at once, a run and a plan being saved holding the lock of the project, and it is forgotten when the plan is done or a new one is saved. The JSON documents of `estimate`, `plan`, `run`, `tasks` and `status` say their `version` and the `root` of the project, and those about a saved plan (`plan --save`, `run`, `tasks`, `status`) its `planIdentity` too, a hash of the text of `dresscode-upgrade.neon` (`PlanFile::identify()`) by which a tool tells which plan a document is about; an agent reads them, the workflows having no format `agent`. ## Writing a rule @@ -363,7 +375,7 @@ Everything in such a message that is code stands in backticks, as in Markdown: a `Testing\RuleTester` runs a rule over `*.code` fixtures (`.expected` output beside them, `.violations` as `line: message` with the risk of a risky one on an indented line below it, `risky ` with `: ` where the rule gives one, the values of its decisions in a `// {"json"}` comment, a key without its section taking the one section of the rule, over those of a `values.neon` beside the fixtures, a run that allows risky fixes in a `// risky` one, the code and the fixed code run under the CLI of PHP in a `// run` one, which must print the same and exit alike, the targeted version in a `// php 8.4` one, the types turned off in a `// types off` one, the widest line in a `// lineLength 80` one (120 without it; `check()` takes a whole `Style` instead, whose line ending stays that of the code) and what the namespaces declare outside the fixture in `// namespacedFunctions`, `// namespacedConstants` and `// nameResolution certain`, all in the comments that open the fixture; without a version the rule is tested at the version of PHP it requires, else at `Config::DefaultPhpVersion`, never at the version of the interpreter running the tests) and, given `analyses:` in the shape of `Config::$analyses`, registers those of a plugin for the rule, then checks the contract: parent invariant, idempotence over the output, comments preserved unless `modifiesComments`, `dresscode:ignoreFile` honored, no silent mutation. -`Testing\UpgradingTester` is for a package that ships upgrading files: `collectProblems($file, $root, $packageRules)` reads a file the way a run would, in the project whose vendor holds the library, the rules the package ships itself known besides those of DressCode, and gives back sentences. A key under `extra.dresscode` of the nearest `composer.json` at or above the file that `PackageDiscovery` does not read is a problem too (a run only warns of it, the package may be newer than the tool). Every section, reached or not, has to be what the grammars of its maps accept, and what the sections come to at the installed version has to replace, in `replacedClasses` and `replacedMembers` and by a static method in `replacedFunctions`, by classes, members and methods that exist, asked of the loaded code (a function of a library is declared by a file loaded with its first use, so it is not looked up); the other maps are held to their grammar alone. A replacement the file replaces in its turn (`REALPATH`, then `Realpath`, then `RealPath`) is followed to its end, the way the passes of a run follow it, and one that leads back to where it started is a problem; an entry withdrawn with `keep` is thereby not checked, and one whose withdrawal was forgotten shows as a replacement that does not exist. What is replaced is not looked up, a library having usually removed it. The sentence of a `forbidden…` map is read as the end of the message it completes: in lower case unless it begins with a name, with its code in backticks, with no period, double quote or "should", and at most 160 characters, the backticks not counted; an entry of a `forbidden…` map that gives none (a project may leave it out) is a problem in the data of a package. `runSample($code, $root, $decisions)` is the other half: code written for the old API as the decisions given fix and report it, every section the installed version reaches applying, whatever the constraint of the project allows, the types taken from the PHPStan of the project, which reads the code from `temp/` of the root, and no result cache; it gives the `FileResult`, so that a package tests its data without reaching for the `@internal` factory of the run. +`Testing\UpgradingTester` is for a package that ships upgrading files: `collectProblems($file, $root, $packageRules)` reads a file the way a run would, in the project whose vendor holds the library, the rules the package ships itself known besides those of DressCode, and gives back sentences. A key under `extra.dresscode` of the nearest `composer.json` at or above the file that `PackageDiscovery` does not read is a problem too (a run only warns of it, the package may be newer than the tool). `collectPackageProblems($root)` holds `extra.dresscode.packages` of the package to exactly the packages its upgrading files are about, by which `upgrade` offers it to a project lacking it. Every section, reached or not, has to be what the grammars of its maps accept, and what the sections come to at the installed version has to replace, in `replacedClasses` and `replacedMembers` and by a static method in `replacedFunctions`, by classes, members and methods that exist, asked of the loaded code (a function of a library is declared by a file loaded with its first use, so it is not looked up); the other maps are held to their grammar alone. A replacement the file replaces in its turn (`REALPATH`, then `Realpath`, then `RealPath`) is followed to its end, the way the passes of a run follow it, and one that leads back to where it started is a problem; an entry withdrawn with `keep` is thereby not checked, and one whose withdrawal was forgotten shows as a replacement that does not exist. What is replaced is not looked up, a library having usually removed it. The sentence of a `forbidden…` map is read as the end of the message it completes: in lower case unless it begins with a name, with its code in backticks, with no period, double quote or "should", and at most 160 characters, the backticks not counted; an entry of a `forbidden…` map that gives none (a project may leave it out) is a problem in the data of a package. `runSample($code, $root, $decisions)` is the other half: code written for the old API as the decisions given fix and report it, every section the installed version reaches applying, whatever the constraint of the project allows, the types taken from the PHPStan of the project, which reads the code from `temp/` of the root, and no result cache; it gives the `FileResult`, so that a package tests its data without reaching for the `@internal` factory of the run. The fixtures of every rule run again under each standard with the sets beside it (`robustness.phpt`), which no fixture of one rule tries: the run must not fail, write code that does not parse or fail to settle, whatever the other rules make of the code. What no fixture catches, the runs over the corpus do: the whitespace fuzz damages the whitespace of a fixed file and requires the fixer to come back to it, and `name-meaning.phpt` runs the rules that write names and imports over the corpus and requires every name outside the imports to resolve to what it resolved to before, because an import moved into a statement writing its items differently, or dropped while something still uses it, leaves code that parses and round-trips and says nothing else. diff --git a/docs/reference/api.md b/docs/reference/api.md index c8cb2034d2..6f29ddf502 100644 --- a/docs/reference/api.md +++ b/docs/reference/api.md @@ -280,7 +280,7 @@ final readonly class Config extends DressCode\Profile final class Catalogue public const Version = 4 public const CoreSections = ['file', 'indentation', 'braces', 'blankLines', 'multiline', 'spacing', 'naming', 'casing', 'qualification', 'imports', 'classes', 'functions', 'types', 'controlFlow', 'expressions', 'literals', 'comments', 'phpdoc', 'hygiene', 'mistakes', 'upgrading'] - public const Lexicon = ['required' => 'always there', 'forbidden' => 'never there', 'optional' => null, 'none' => null, 'sameLine' => null, 'nextLine' => null, 'above' => null, 'lineStart' => null, 'lineEnd' => null, 'perLine' => null, 'fill' => null, 'apart' => null, 'attached' => null, 'closingApart' => null, 'aligned' => null, 'collapsed' => null, 'expanded' => null, 'first' => null, 'last' => null, 'lastStatementSetApart' => null, 'spaces' => null, 'tabs' => null, 'bare' => null, 'imported' => null, 'backslashed' => null, 'self' => null, 'declared' => null, 'lowercase' => null, 'uppercase' => null, 'canonical' => null, 'alphabetical' => null, 'short' => null, 'long' => null, 'separated' => null, 'combined' => null, 'grouped' => null, 'joined' => null, 'PascalCase' => null, 'camelCase' => null, 'snake_case' => null, 'UPPER_CASE' => null, 'Pascal_Snake_Case' => null, 'constant' => null, 'property' => null, 'traitUse' => null] + public const Lexicon = ['required' => 'always there', 'forbidden' => 'never there', 'optional' => null, 'none' => null, 'sameLine' => null, 'nextLine' => null, 'above' => null, 'lineStart' => null, 'lineEnd' => null, 'perLine' => null, 'fill' => null, 'apart' => null, 'attached' => null, 'closingApart' => null, 'aligned' => null, 'collapsed' => null, 'expanded' => null, 'first' => null, 'last' => null, 'lastStatementSetApart' => null, 'spaces' => null, 'tabs' => null, 'bare' => null, 'imported' => null, 'backslashed' => null, 'self' => null, 'declared' => null, 'lowercase' => null, 'uppercase' => null, 'canonical' => null, 'alphabetical' => null, 'short' => null, 'long' => null, 'separated' => null, 'combined' => null, 'grouped' => null, 'joined' => null, 'PascalCase' => null, 'camelCase' => null, 'snake_case' => null, 'UPPER_CASE' => null, 'Pascal_Snake_Case' => null, 'constant' => null, 'property' => null, 'traitUse' => null, 'reported' => 'reported where it stands'] public const ProjectSection = 'project' public static function fromRules(list> $rules): DressCode\Config\Catalogue public function find(string $path): ?DressCode\Decision @@ -302,7 +302,11 @@ final readonly class Layer public readonly ?string $name public readonly ?string $package public readonly ?string $decision - public function __construct(DressCode\Config\LayerKind $kind, ?string $name = null, ?string $package = null, ?string $decision = null) + public readonly ?string $library + public readonly ?string $since + public readonly ?string $from + public function __construct(DressCode\Config\LayerKind $kind, ?string $name = null, ?string $package = null, ?string $decision = null, ?string $library = null, ?string $since = null, ?string $from = null) + public function withSection(string $library, string $since, ?string $from): DressCode\Config\Layer public function describe(): string public function formatReference(): string public function isProject(): bool @@ -332,7 +336,7 @@ final class ConfigurationException extends Exception implements Stringable, Thro ```php final readonly class Application - public const Version = '1.4.0' + public const Version = '1.5-dev' public function __construct(?resource $stdout = null, ?resource $stderr = null, ?resource $stdin = null, ?string $cwd = null, ?string $script = null, ?DressCode\Config $defaultConfig = null, ?bool $xdebug = null, ?bool $interactive = null) public function run(list $argv): int ``` @@ -673,7 +677,7 @@ final class RuleContext public readonly string $path public readonly DressCode\Style $style public readonly string $phpVersion - public function report(PhpSyntax\Node|PhpSyntax\Token $at, string $message, ?string $decision = null, ?PhpSyntax\Trivia $trivia = null, int $lineInTrivia = 0, ?DressCode\Risk $risk = null, ?PhpSyntax\Token $follows = null, bool $byLine = false, bool $fixable = true, ?string $because = null): bool + public function report(PhpSyntax\Node|PhpSyntax\Token $at, string $message, ?string $decision = null, ?PhpSyntax\Trivia $trivia = null, int $lineInTrivia = 0, ?DressCode\Risk $risk = null, ?PhpSyntax\Token $follows = null, bool $byLine = false, bool $fixable = true, ?string $because = null, ?DressCode\Config\Layer $source = null): bool public function isSilenced(PhpSyntax\Node|PhpSyntax\Token $at, ?string $decision = null, ?PhpSyntax\Trivia $trivia = null, int $lineInTrivia = 0): bool /** @template T of object */ public function getAnalysis(class-string $class): T @@ -778,6 +782,7 @@ final class TestFailure extends Exception implements Stringable, Throwable ```php final class UpgradingTester public static function collectProblems(string $file, string $root, list> $packageRules = []): list + public static function collectPackageProblems(string $root): list public static function runSample(string $code, string $root, array $decisions = [], string $name = 'sample'): DressCode\FileResult ``` @@ -862,6 +867,7 @@ final readonly class MemberMapEntry public readonly DressCode\Upgrading\MemberPattern $pattern public readonly T $value public readonly string $decision + public readonly ?DressCode\Config\Layer $origin ``` ## `DressCode\Upgrading\MemberMapGrammar` @@ -966,8 +972,8 @@ final readonly class Values public function find(string $path): ?DressCode\Value public function readMap(string $path): array public function findWithdrawnNames(string $path): list - public function findPackageEntries(string $path): array public function getEntryDecision(string $path, string $key): string + public function getEntryOrigin(string $path, string $key): ?DressCode\Config\Layer public function isKept(string $path): bool public function isSelected(string $path): bool ``` @@ -990,7 +996,8 @@ final readonly class Violation public readonly ?int $offset public readonly ?int $length public readonly ?array{int, int} $originalLines - public function __construct(string $decision, string $message, int $line, ?int $column, DressCode\Severity $severity, string $fingerprint, bool $fixable = true, ?DressCode\Risk $risk = null, bool $refused = false, ?string $because = null, ?string $derivedFrom = null, ?int $offset = null, ?int $length = null, ?array{int, int} $originalLines = null) + public readonly ?DressCode\Config\Layer $source + public function __construct(string $decision, string $message, int $line, ?int $column, DressCode\Severity $severity, string $fingerprint, bool $fixable = true, ?DressCode\Risk $risk = null, bool $refused = false, ?string $because = null, ?string $derivedFrom = null, ?int $offset = null, ?int $length = null, ?array{int, int} $originalLines = null, ?DressCode\Config\Layer $source = null) public function findSpanStart(string $text): ?array{int, int} public function findSpanEnd(string $text): ?array{int, int} public static function formatCode(string $code): string @@ -1206,6 +1213,7 @@ final readonly class Violation - `DressCode\Rules\Upgrading\ReplacedFunctionCallsRule` - `DressCode\Rules\Upgrading\ReplacedFunctionsRule` - `DressCode\Rules\Upgrading\ReplacedMembersRule` +- `DressCode\Rules\Upgrading\UnseenReferencesRule` - `DressCode\Rules\Variables\NoGlobalStatementsRule` - `DressCode\Rules\Variables\NoRepeatedAssignmentsRule` - `DressCode\Rules\Variables\NoSeparateIssetsRule` diff --git a/docs/reference/decisions.md b/docs/reference/decisions.md index 8bc51c1656..1ed929a1fa 100644 --- a/docs/reference/decisions.md +++ b/docs/reference/decisions.md @@ -1,6 +1,6 @@ # Decisions -Generated by `composer reference` from the catalogue; do not edit. 445 decisions in 22 sections. +Generated by `composer reference` from the catalogue; do not edit. 447 decisions in 22 sections. A decision writing a construct of a newer PHP takes effect where every version of the target has it, the target being the oldest version the code runs on; one about a deprecation reports and fixes whatever the target, the code meeting the deprecation wherever it runs on the version that made it. @@ -47,7 +47,7 @@ meeting the deprecation wherever it runs on the version that made it. **mistakes** (24): [consecutivePhpdocs](#mistakesconsecutivephpdocs), [continueInSwitch](#mistakescontinueinswitch), [countOfUncountable](#mistakescountofuncountable), [debugOutput](#mistakesdebugoutput), [debugOutputFunctions](#mistakesdebugoutputfunctions), [errorSuppression](#mistakeserrorsuppression), [exceptionWhereThrowableBelongs](#mistakesexceptionwherethrowablebelongs), [finalParent](#mistakesfinalparent), [globalStatement](#mistakesglobalstatement), [invisibleCharacter](#mistakesinvisiblecharacter), [looseNumberComparison](#mistakesloosenumbercomparison), [neverReturnType.anonymousFunction](#mistakesneverreturntypeanonymousfunction), [neverReturnType.function](#mistakesneverreturntypefunction), [neverReturnType.method](#mistakesneverreturntypemethod), [readonlyProperty](#mistakesreadonlyproperty), [repeatedAssignment](#mistakesrepeatedassignment), [staticSetState](#mistakesstaticsetstate), [strictArgument](#mistakesstrictargument), [thisOutsideObject](#mistakesthisoutsideobject), [trailingWhitespaceInString](#mistakestrailingwhitespaceinstring), [unimplementedAbstractMethod](#mistakesunimplementedabstractmethod), [unreachableCatch](#mistakesunreachablecatch), [__debugInfoReturningNull](#mistakes__debuginforeturningnull), [__serialize](#mistakes__serialize) -**upgrading** (56): [api.attributeForAnnotation](#upgradingapiattributeforannotation), [api.attributeForMember](#upgradingapiattributeformember), [api.forbiddenClasses](#upgradingapiforbiddenclasses), [api.forbiddenConstants](#upgradingapiforbiddenconstants), [api.forbiddenFunctions](#upgradingapiforbiddenfunctions), [api.forbiddenMembers](#upgradingapiforbiddenmembers), [api.replacedCalls](#upgradingapireplacedcalls), [api.replacedClasses](#upgradingapireplacedclasses), [api.replacedFunctions](#upgradingapireplacedfunctions), [api.replacedMembers](#upgradingapireplacedmembers), [classes.Override](#upgradingclassesoverride), [classes.SensitiveParameter](#upgradingclassessensitiveparameter), [classes.SensitiveParameterNames](#upgradingclassessensitiveparameternames), [classes.Stringable](#upgradingclassesstringable), [declarations.deprecatedClass](#upgradingdeclarationsdeprecatedclass), [declarations.deprecatedFunction](#upgradingdeclarationsdeprecatedfunction), [declarations.deprecatedMember](#upgradingdeclarationsdeprecatedmember), [functions.arrayFirstLast](#upgradingfunctionsarrayfirstlast), [functions.arraySearchFunctions](#upgradingfunctionsarraysearchfunctions), [functions.array_is_list](#upgradingfunctionsarray_is_list), [functions.clamp](#upgradingfunctionsclamp), [functions.get_debug_type](#upgradingfunctionsget_debug_type), [functions.json_validate](#upgradingfunctionsjson_validate), [functions.roundingMode](#upgradingfunctionsroundingmode), [functions.substringFunctions](#upgradingfunctionssubstringfunctions), [packages](#upgradingpackages), [php.backticks](#upgradingphpbackticks), [php.caseSemicolon](#upgradingphpcasesemicolon), [php.constructorReturnValue](#upgradingphpconstructorreturnvalue), [php.csvEscapeArgument](#upgradingphpcsvescapeargument), [php.deprecatedApi](#upgradingphpdeprecatedapi), [php.deprecatedArgument](#upgradingphpdeprecatedargument), [php.dollarBraceInterpolation](#upgradingphpdollarbraceinterpolation), [php.dynamicProperty](#upgradingphpdynamicproperty), [php.floatArrayKey](#upgradingphpfloatarraykey), [php.implicitNullable](#upgradingphpimplicitnullable), [php.nullArgument](#upgradingphpnullargument), [php.nullArrayKey](#upgradingphpnullarraykey), [php.reservedNames](#upgradingphpreservednames), [php.returnInFinally](#upgradingphpreturninfinally), [php.sleepAndWakeup](#upgradingphpsleepandwakeup), [phpdoc.deprecated](#upgradingphpdocdeprecated), [phpdoc.readonly](#upgradingphpdocreadonly), [syntax.cloneWith](#upgradingsyntaxclonewith), [syntax.dynamicClassConstant](#upgradingsyntaxdynamicclassconstant), [syntax.firstClassCallables](#upgradingsyntaxfirstclasscallables), [syntax.match](#upgradingsyntaxmatch), [syntax.newInInitializer](#upgradingsyntaxnewininitializer), [syntax.nullsafe](#upgradingsyntaxnullsafe), [syntax.octalPrefix](#upgradingsyntaxoctalprefix), [syntax.pipe](#upgradingsyntaxpipe), [syntax.pipeMinCalls](#upgradingsyntaxpipemincalls), [syntax.promotedProperties](#upgradingsyntaxpromotedproperties), [syntax.readonlyClasses](#upgradingsyntaxreadonlyclasses), [syntax.spreadForArrayMerge](#upgradingsyntaxspreadforarraymerge), [syntax.throwExpression](#upgradingsyntaxthrowexpression) +**upgrading** (58): [api.attributeForAnnotation](#upgradingapiattributeforannotation), [api.attributeForMember](#upgradingapiattributeformember), [api.forbiddenClasses](#upgradingapiforbiddenclasses), [api.forbiddenConstants](#upgradingapiforbiddenconstants), [api.forbiddenFunctions](#upgradingapiforbiddenfunctions), [api.forbiddenMembers](#upgradingapiforbiddenmembers), [api.replacedCalls](#upgradingapireplacedcalls), [api.replacedClasses](#upgradingapireplacedclasses), [api.replacedFunctions](#upgradingapireplacedfunctions), [api.replacedMembers](#upgradingapireplacedmembers), [classes.Override](#upgradingclassesoverride), [classes.SensitiveParameter](#upgradingclassessensitiveparameter), [classes.SensitiveParameterNames](#upgradingclassessensitiveparameternames), [classes.Stringable](#upgradingclassesstringable), [declarations.deprecatedClass](#upgradingdeclarationsdeprecatedclass), [declarations.deprecatedFunction](#upgradingdeclarationsdeprecatedfunction), [declarations.deprecatedMember](#upgradingdeclarationsdeprecatedmember), [functions.arrayFirstLast](#upgradingfunctionsarrayfirstlast), [functions.arraySearchFunctions](#upgradingfunctionsarraysearchfunctions), [functions.array_is_list](#upgradingfunctionsarray_is_list), [functions.clamp](#upgradingfunctionsclamp), [functions.get_debug_type](#upgradingfunctionsget_debug_type), [functions.json_validate](#upgradingfunctionsjson_validate), [functions.roundingMode](#upgradingfunctionsroundingmode), [functions.substringFunctions](#upgradingfunctionssubstringfunctions), [packages](#upgradingpackages), [php.backticks](#upgradingphpbackticks), [php.caseSemicolon](#upgradingphpcasesemicolon), [php.constructorReturnValue](#upgradingphpconstructorreturnvalue), [php.csvEscapeArgument](#upgradingphpcsvescapeargument), [php.deprecatedApi](#upgradingphpdeprecatedapi), [php.deprecatedArgument](#upgradingphpdeprecatedargument), [php.dollarBraceInterpolation](#upgradingphpdollarbraceinterpolation), [php.dynamicProperty](#upgradingphpdynamicproperty), [php.floatArrayKey](#upgradingphpfloatarraykey), [php.implicitNullable](#upgradingphpimplicitnullable), [php.nullArgument](#upgradingphpnullargument), [php.nullArrayKey](#upgradingphpnullarraykey), [php.reservedNames](#upgradingphpreservednames), [php.returnInFinally](#upgradingphpreturninfinally), [php.sleepAndWakeup](#upgradingphpsleepandwakeup), [phpdoc.deprecated](#upgradingphpdocdeprecated), [phpdoc.readonly](#upgradingphpdocreadonly), [syntax.cloneWith](#upgradingsyntaxclonewith), [syntax.dynamicClassConstant](#upgradingsyntaxdynamicclassconstant), [syntax.firstClassCallables](#upgradingsyntaxfirstclasscallables), [syntax.match](#upgradingsyntaxmatch), [syntax.newInInitializer](#upgradingsyntaxnewininitializer), [syntax.nullsafe](#upgradingsyntaxnullsafe), [syntax.octalPrefix](#upgradingsyntaxoctalprefix), [syntax.pipe](#upgradingsyntaxpipe), [syntax.pipeMinCalls](#upgradingsyntaxpipemincalls), [syntax.promotedProperties](#upgradingsyntaxpromotedproperties), [syntax.readonlyClasses](#upgradingsyntaxreadonlyclasses), [syntax.spreadForArrayMerge](#upgradingsyntaxspreadforarraymerge), [syntax.throwExpression](#upgradingsyntaxthrowexpression), [unseen.classNameString](#upgradingunseenclassnamestring), [unseen.dynamicAccess](#upgradingunseendynamicaccess) **namespaces** (2): [constants](#namespacesconstants), [functions](#namespacesfunctions) @@ -4120,6 +4120,7 @@ A class that may not be used, with what to do instead (`Acme\Legacy\Db: "use the - The standards: perCs `keep`, psr12 `keep`, nette `keep`, symfony `keep`, laravel `keep` - Rule `DressCode\Rules\Upgrading\ForbiddenSymbolsRule`, stage Structure - Read by rule `DressCode\Rules\Upgrading\NoDeprecatedClassesRule`, which this decision does not turn on +- Read by rule `DressCode\Rules\Upgrading\UnseenReferencesRule`, which this decision does not turn on ### upgrading.api.forbiddenConstants @@ -4176,6 +4177,7 @@ A class written instead of another one, both fully qualified (`Acme\Old\Mailer: - The standards: perCs `keep`, psr12 `keep`, nette `keep`, symfony `keep`, laravel `keep` - Rule `DressCode\Rules\Upgrading\ReplacedClassesRule`, stage Structure - Read by rule `DressCode\Rules\Upgrading\NoDeprecatedClassesRule`, which this decision does not turn on +- Read by rule `DressCode\Rules\Upgrading\UnseenReferencesRule`, which this decision does not turn on - Modifies comments - May have risky fixes, made once the decision is named in `fixRisky` or with `--fix-risky` @@ -4707,6 +4709,24 @@ A class whose every property is readonly. - Needs PHP >=8.0 - May have risky fixes, made once the decision is named in `fixRisky` or with `--fix-risky` +### upgrading.unseen.classNameString + +A string holding the name of a class `replacedClasses` or `forbiddenClasses` names, which no rename of the class reaches. + +- By default `keep` +- Takes: `reported` (reported where it stands: the string `'Acme\Old'` naming a class the maps rename or forbid); `keep` +- The standards: perCs `keep`, psr12 `keep`, nette `keep`, symfony `keep`, laravel `keep` +- Rule `DressCode\Rules\Upgrading\UnseenReferencesRule`, stage Structure + +### upgrading.unseen.dynamicAccess + +A member, a class or a function reached by a name the code computes, which no map of upgrading data matches. + +- By default `keep` +- Takes: `reported` (reported where it stands: `$object->$method()`, `new $class`, `call_user_func($callback)`); `keep` +- The standards: perCs `keep`, psr12 `keep`, nette `keep`, symfony `keep`, laravel `keep` +- Rule `DressCode\Rules\Upgrading\UnseenReferencesRule`, stage Structure + ## namespaces ### namespaces.constants diff --git a/readme.md b/readme.md index 8348c42e89..564cbe967a 100644 --- a/readme.md +++ b/readme.md @@ -429,9 +429,10 @@ None of this is a search and replace: an annotation became an attribute along wi of a parameter moved behind `??` and a flag became a named argument. And DressCode knows that `$form` is a form and `$this` a presenter, because it asks PHPStan about the types. -The set `deprecations` lets the data of the installed packages in, and naming the package in `use` brings -its rules too. Most rewrites ask PHPStan about the [types](#types-from-phpstan); without them only classes, -functions and annotations are fixed: +`vendor/bin/dresscode upgrade today` makes the upgrade with no configuration: it takes the installed +packages with their data and their rules, asks PHPStan about the [types](#types-from-phpstan) and leaves +the style of the code as it is. To have every check watch for the old API too, name the package in `use` +next to the set `deprecations`; without the types only classes, functions and annotations are fixed: ```neon typeAnalysis: phpstan diff --git a/src/Analyses/IndentationPlan.php b/src/Analyses/IndentationPlan.php index 113e51de18..68fcbeae77 100644 --- a/src/Analyses/IndentationPlan.php +++ b/src/Analyses/IndentationPlan.php @@ -155,11 +155,15 @@ private function place(Token $token): void $indentation = $base . $style->getIndentation($level); $this->lines[$line] = $indentation; // a comment above a closing bracket belongs to the content before it, unless the bracket is followed - // by the next branch of a non-empty structure, which the comment then introduces; a comment above + // by the next branch of a non-empty structure, which the comment then introduces, or the comment is + // written at the level of the content and so ends the branch the bracket closes; a comment above // a later case belongs to the statements of the previous one $commentIndentation = match (true) { $role === LayoutRole::Closer && self::continuesStructure($token) && self::hasCommentsAtTwoLevels($token, $indentation) => null, - $role === LayoutRole::Closer && !(self::continuesStructure($token) && !$token->getPrevious()?->is('{')), + $role === LayoutRole::Closer && ( + !(self::continuesStructure($token) && !$token->getPrevious()?->is('{')) + || self::hasCommentsOnlyAt($token, $indentation . $style->indent) + ), $role === LayoutRole::Case && !self::isFirstItem($child, $token) => $indentation . $style->indent, default => $indentation, @@ -211,19 +215,7 @@ private static function findChainStart(?Node $node): ?Node */ public static function getMinimumLevel(Token $first): int { - return !$first->startsLine() || Indentation::opensStatement($first) || self::opensMatchArm($first) ? 1 : 0; - } - - - private static function opensMatchArm(Token $token): bool - { - for ($node = $token->parent; $node !== null && $node->getFirstToken() === $token; $node = $node->parent) { - if ($node instanceof Nodes\MatchArmNode) { - return true; - } - } - - return false; + return !$first->startsLine() || Indentation::opensStatement($first) || Indentation::opensMatchArm($first) ? 1 : 0; } @@ -241,6 +233,26 @@ private static function continuesStructure(Token $token): bool * is given, heading the branch it continues the structure with, and one deeper, belonging to the branch it closes. */ private static function hasCommentsAtTwoLevels(Token $token, string $indentation): bool + { + $levels = self::getCommentLevels($token); + $last = array_pop($levels); + return $last === $indentation && array_any($levels, fn(string $level) => strlen($level) > strlen($last)); + } + + + /** Whether there are comments on lines of their own above the token and every one stands at the indentation as written. */ + private static function hasCommentsOnlyAt(Token $token, string $indentation): bool + { + $levels = self::getCommentLevels($token); + return $levels !== [] && array_all($levels, fn(string $level) => $level === $indentation); + } + + + /** + * The indentations of the comments on lines of their own above the token, as written. + * @return list + */ + private static function getCommentLevels(Token $token): array { $levels = []; $trailing = $token->getPrevious()->trailingTrivia ?? []; @@ -260,8 +272,7 @@ private static function hasCommentsAtTwoLevels(Token $token, string $indentation } } - $last = array_pop($levels); - return $last === $indentation && array_any($levels, fn(string $level) => strlen($level) > strlen($last)); + return $levels; } diff --git a/src/Analyses/PhpStan.php b/src/Analyses/PhpStan.php index a237a705a8..b7dab56361 100644 --- a/src/Analyses/PhpStan.php +++ b/src/Analyses/PhpStan.php @@ -10,7 +10,7 @@ use Composer\Autoload\ClassLoader; use Composer\InstalledVersions; use DressCode\Config\ComposerJson; -use DressCode\Engine\Helpers; +use DressCode\Engine\{Helpers, Profiler}; use DressCode\Violation; use Nette\Utils\FileSystem; use PhpParser\{Node, NodeFinder}; @@ -90,6 +90,7 @@ public function __construct( string $tempDir, /** the version of PHP the code is written for, which PHPStan parses it as where the running PHP is older */ private readonly ?string $phpVersion = null, + private readonly ?Profiler $profiler = null, /** * @var list the directories of the packages installed in a newer version than the oldest one the project * supports, or supported from no particular version, whose declarations may say what that one does not @@ -289,6 +290,7 @@ public function resolveScopes(string $path, string $code, array $ast, callable $ $resolver = $container->getByType(NodeScopeResolver::class); $resolver->setAnalysedFiles([$path]); $scope = $container->getByType(ScopeFactory::class)->create(ScopeContext::create($path)); + $start = $this->profiler ? hrtime(as_number: true) : 0; $inCallback = false; // a warning of PHPStan is the first sign of its failure on the file, and printed it would spoil the output; one it // silences is not, a rename into its cache another process has just written being one @@ -312,6 +314,8 @@ public function resolveScopes(string $path, string $code, array $ast, callable $ } finally { restore_error_handler(); } + + $this->profiler?->addPhase('phpstan: scopes', hrtime(as_number: true) - $start); } @@ -586,6 +590,7 @@ private function getContainer(): Container if (ini_get('opcache.file_cache_only')) { ini_set('opcache.enable', '0'); } + $start = $this->profiler ? hrtime(as_number: true) : 0; $configs = [ ...array_merge(...array_map(fn(PhpStanExtension $extension) => $extension->includes, $this->extensions)), ...array_filter([$config]), @@ -609,6 +614,10 @@ private function getContainer(): Container ); } + $this->profiler?->addPhase( + $this->replacement === null ? 'phpstan: container' : 'phpstan: derived container build', + hrtime(as_number: true) - $start, + ); $this->configurationFiles ??= $this->collectConfigurationFiles($container); return $this->container = $container; } diff --git a/src/Config/Catalogue.php b/src/Config/Catalogue.php index c55d73c18e..9f5f8289ba 100644 --- a/src/Config/Catalogue.php +++ b/src/Config/Catalogue.php @@ -56,7 +56,7 @@ final class Catalogue 'canonical' => null, 'alphabetical' => null, 'short' => null, 'long' => null, 'separated' => null, 'combined' => null, 'grouped' => null, 'joined' => null, 'PascalCase' => null, 'camelCase' => null, 'snake_case' => null, 'UPPER_CASE' => null, 'Pascal_Snake_Case' => null, - 'constant' => null, 'property' => null, 'traitUse' => null, + 'constant' => null, 'property' => null, 'traitUse' => null, 'reported' => 'reported where it stands', ]; /** diff --git a/src/Config/ComposerJson.php b/src/Config/ComposerJson.php index 785dba26f6..c91afabcc5 100644 --- a/src/Config/ComposerJson.php +++ b/src/Config/ComposerJson.php @@ -59,7 +59,7 @@ public static function detectPhpTarget(?string $composerFile): ?string $constraint = is_string($constraint) && Versions::isConstraint($constraint) ? $constraint : null; $platform = $data['config']['platform']['php'] ?? null; if (is_string($platform) && Versions::isVersion($platform)) { - return $constraint === null ? ">=$platform" : Versions::raiseLowerBound($constraint, $platform); + return $constraint === null ? ">=$platform" : Versions::restrictFrom($constraint, $platform); } return $constraint !== null && Versions::findLowestVersion($constraint) !== null ? $constraint : null; diff --git a/src/Config/ConfigResolver.php b/src/Config/ConfigResolver.php index fd5ddcb200..d56862372d 100644 --- a/src/Config/ConfigResolver.php +++ b/src/Config/ConfigResolver.php @@ -51,6 +51,11 @@ public function __construct( private readonly string $root = '.', /** @var list the packages whose plugins the project does not let in, so the maps of their rules are unknown */ private readonly array $pluginsSkipped = [], + /** + * @var list presets laid over those the configuration uses and beneath its own decisions and its overrides, + * so that the project keeps the last word, as `upgrade today` lays its sets + */ + private readonly array $laid = [], ) { $this->rulesOfOverrides = new \WeakMap; } @@ -231,7 +236,7 @@ public function resolve( lineLength: self::resolveLineLength($values->get('file.lineLength')), tabWidth: $values->get('indentation.tabWidth')->getCountRange()[0], typeAnalysis: $this->typesAvailable ? $typeAnalysis : null, - packageTargets: array_diff_key($config->targets, ['php' => true]), + packageTargets: array_diff_key(RunnerFactory::mergeTargets($config, $commandLine), ['php' => true]), plugins: array_map( fn(string|Plugin $plugin) => is_string($plugin) ? $plugin : $plugin::class, [...$config->plugins, ...$commandLine instanceof Config ? $commandLine->plugins : []], @@ -295,7 +300,7 @@ private function collectPackageMaps(array $decisions, ?array $narrowed): array $layers = []; foreach ($this->upgradingData as $package) { $requirement = $package->layer->decision; - $layer = $package->buildDecisions(function (string $map) use ($package, $requirement, $narrowed, $named, $covered): ?string { + $built = $package->buildDecisions(function (string $map) use ($package, $requirement, $narrowed, $named, $covered): ?string { $path = $this->findDataPath($map); if ($path === null && !in_array($package->layer->package, $this->pluginsSkipped, true)) { // the plugin skipped says so $this->warnings[$package->layer->describe() . " $map"] = "Map `$map`, which " @@ -323,8 +328,8 @@ private function collectPackageMaps(array $decisions, ?array $narrowed): array $laid = $requirement === null ? ($decisions[self::PackagesDecision] ?? null)?->value->getFlag() : ($decisions[$requirement] ?? null)?->value->isKept() === false; - if ($layer !== [] && $laid) { - $layers[] = [$package->layer, $layer]; + if ($laid) { + array_push($layers, ...$built); } } @@ -642,6 +647,10 @@ private function collectLayers(array $profiles): array $layers = $visited = $repeated = []; foreach ($profiles as [$layer, $profile]) { $this->collectUsed($profile, $layer, $layers, $visited, $repeated); + if ($layer->kind === LayerKind::Configuration && $this->laid !== []) { + $this->collectUsed(new Profile(use: $this->laid), new Layer(LayerKind::Caller), $layers, $visited, $repeated); + } + $layers[] = [$layer, $profile]; } @@ -707,9 +716,12 @@ private function collectUsed(Profile $profile, Layer $source, array &$layers, ar private function warnRepeated(array $repeated): void { foreach ($repeated as [$layer, $laidBy, $namedBy]) { - // what a preset uses is not the project's to change, and the command line reaches what an override does not + // what a preset or the caller lays is not the project's to change, and the command line reaches what an override + // does not if ( $namedBy->kind !== LayerKind::Preset + && $namedBy->kind !== LayerKind::Caller + && $laidBy->kind !== LayerKind::Caller && !($laidBy->kind === LayerKind::Override && $namedBy->kind === LayerKind::CommandLine) ) { $this->warnings['repeated ' . $layer->describe() . ' ' . $namedBy->describe()] = ucfirst($namedBy->formatReference()) @@ -748,7 +760,7 @@ private function resolveOnly(array $names): array * section named like a preset is written `section.*`, the bare name being refused as both. * @throws ConfigurationException */ - private function expandName(string $name): ExpandedName + public function expandName(string $name): ExpandedName { $package = $this->findDataPackage($name); if ($package !== null) { @@ -757,6 +769,10 @@ private function expandName(string $name): ExpandedName if ($data->layer->package === $package || $data->package === $package) { $keys = [...array_keys($data->maps), ...array_keys($data->requirements)]; array_push($paths, ...array_filter(array_map($this->findDataPath(...), $keys))); + // the data of PHP are reported under the requirement laying them + if ($data->layer->decision !== null) { + $paths[] = $data->layer->decision; + } } } diff --git a/src/Config/CorePlugin.php b/src/Config/CorePlugin.php index 22f325bb9c..7293523213 100644 --- a/src/Config/CorePlugin.php +++ b/src/Config/CorePlugin.php @@ -260,6 +260,8 @@ public function getManifest(): PluginManifest Rules\Upgrading\NoDeprecatedMembersRule::class, Rules\Upgrading\NoDeprecatedFunctionsRule::class, Rules\Upgrading\NoDeprecatedPhpArgumentsRule::class, + // what the rewrites leave of a string naming a class, and what none of them could see + Rules\Upgrading\UnseenReferencesRule::class, Rules\Variables\NoGlobalStatementsRule::class, Rules\Variables\NoRepeatedAssignmentsRule::class, Rules\Variables\NoSeparateIssetsRule::class, diff --git a/src/Config/DataPackageCatalogue.php b/src/Config/DataPackageCatalogue.php new file mode 100644 index 0000000000..1aeaabdd89 --- /dev/null +++ b/src/Config/DataPackageCatalogue.php @@ -0,0 +1,89 @@ +> package => the libraries it is about, a whole vendor written `vendor/`; + * empty where Packagist cannot be reached and nothing is remembered + */ + public static function load(string $cacheDir, bool $offline = false): array + { + $file = "$cacheDir/data-packages.json"; + $cached = is_file($file) ? json_decode((string) file_get_contents($file), associative: true) : null; + $cached = is_array($cached) ? $cached : null; + if ($offline || ($cached !== null && filemtime($file) > time() - self::MaxAge)) { + return $cached ?? []; + } + + $fetched = self::fetch(); + try { + FileSystem::write($file, json_encode($fetched ?? $cached ?? [], JSON_THROW_ON_ERROR)); + if ($fetched === null) { + touch($file, time() - self::MaxAge + self::FailureAge); + } + } catch (\Throwable) { // a cache that cannot be written only means asking again + } + + return $fetched ?? $cached ?? []; + } + + + /** @return ?array> null where Packagist does not answer */ + private static function fetch(): ?array + { + $names = self::request(self::ListUrl)['packageNames'] ?? null; + if (!is_array($names)) { + return null; + } + + $res = []; + foreach (array_filter($names, is_string(...)) as $name) { + // the newest release, or the development version of a package with none + $metadata = self::request(sprintf(self::MetadataUrl, $name))['packages'][$name][0] + ?? self::request(sprintf(self::MetadataUrl, "$name~dev"))['packages'][$name][0] + ?? null; + $libraries = $metadata['extra']['dresscode']['packages'] ?? null; + if (is_array($libraries) && array_all($libraries, fn($library) => is_string($library))) { + $res[$name] = array_values($libraries); + } + } + + return $res; + } + + + /** @return ?array */ + private static function request(string $url): ?array + { + $context = stream_context_create(['http' => ['timeout' => 5, 'user_agent' => 'DressCode']]); + $json = @file_get_contents($url, context: $context); // @ a failure is no answer + $data = $json === false ? null : json_decode($json, associative: true); + return is_array($data) ? $data : null; + } +} diff --git a/src/Config/Layer.php b/src/Config/Layer.php index fd55afe0e5..9fe172d5f6 100644 --- a/src/Config/Layer.php +++ b/src/Config/Layer.php @@ -21,12 +21,34 @@ public function __construct( public ?string $package = null, /** the requirement that lays the upgrading file and what it says is reported under, null for the flag `upgrading.packages` */ public ?string $decision = null, + /** the package whose versions the section of an upgrading file is of, `php` for PHP itself */ + public ?string $library = null, + /** the version of the section of an upgrading file */ + public ?string $since = null, + /** the version the fixes of the entries of the section are right from, where it is older than the section */ + public ?string $from = null, ) { } - /** The layer as a value is said by it: `the configuration`, `dresscode/nette`, `upgrading.neon of acme/mailer`. */ + /** The layer of one section of the upgrading file this layer is, with the version its entries are right from. */ + public function withSection(string $library, string $since, ?string $from): self + { + return new self($this->kind, $this->name, $this->package, $this->decision, $library, $since, $from); + } + + + /** + * The layer as a value is said by it: `the configuration`, `dresscode/nette`, `upgrading.neon of acme/mailer`, + * `application.neon of dresscode/upgrade-nette, since 3.2`. + */ public function describe(): string + { + return $this->describeSource() . ($this->since === null ? '' : ", since $this->since"); + } + + + private function describeSource(): string { return match ($this->kind) { LayerKind::Configuration => 'the configuration', diff --git a/src/Config/PackageDiscovery.php b/src/Config/PackageDiscovery.php index 7e5328fb21..a5a053469d 100644 --- a/src/Config/PackageDiscovery.php +++ b/src/Config/PackageDiscovery.php @@ -18,16 +18,20 @@ * the directory `extra.dresscode.upgrading-dir` names, read for the versions of their package the code must work with * (`UpgradingFile::selectFor()`), with those of PHP for its target (`readPhpData()`), and the plugin under * `extra.dresscode.plugin`, which the project lets in by naming the package or the plugin in `use`, as Composer lets in - * its own plugins. The root package takes part too, and a file about the root itself applies whole. Such a file never - * turns a rule on itself; its maps, and the requirements of the rules of the plugin of its package, are laid under those - * of the project where the project says `upgrading.packages: yes`, those of PHP where it says + * its own plugins. The root package takes part too, and a file about the root itself applies whole, and so do the + * packages of upgrading data installed beside DressCode, which `upgrade today` installs for a project lacking them. Such a + * file never turns a rule on itself; its maps, and the requirements of the rules of the plugin of its package, are + * laid under those of the project where the project says `upgrading.packages: yes`, those of PHP where it says * `upgrading.php.deprecatedApi: forbidden`. * @internal */ final readonly class PackageDiscovery { /** the keys of `extra.dresscode` a package may use */ - public const Keys = ['upgrading-dir', 'plugin']; + public const Keys = ['upgrading-dir', 'packages', 'plugin']; + + /** the type of the packages that bring DressCode upgrading data or a plugin */ + public const PackageType = 'dresscode-plugin'; /** the platform package of Composer the upgrading data of PHP are about, which DressCode ships itself */ public const Php = 'php'; @@ -63,10 +67,14 @@ private function __construct( } - /** @throws ConfigurationException for a file a package ships that cannot be read */ - public static function discover(ProjectPackages $project): self + /** + * @param ?array $installation the packages of upgrading data installed beside DressCode => where + * they lie, by default those of the running process + * @throws ConfigurationException for a file a package ships that cannot be read + */ + public static function discover(ProjectPackages $project, ?array $installation = null): self { - // the root package first, then the installed ones as Composer lists them + // the root package first, then the installed ones as Composer lists them, then the data beside DressCode $packages = $project->rootPath === null ? [] : [[$project->rootName ?? 'the root package', $project->rootPath, $project->rootExtra['dresscode'] ?? null]]; @@ -74,6 +82,12 @@ public static function discover(ProjectPackages $project): self $packages[] = [$name, $package['path'], $package['extra']['dresscode'] ?? null]; } + foreach ($installation ?? self::findInstalledDataPackages() as $name => $path) { + if (!$project->has($name)) { + $packages[] = [$name, $path, ComposerJson::read("$path/composer.json")['extra']['dresscode'] ?? null]; + } + } + $upgradingData = $plugins = $warnings = []; foreach ($packages as [$name, $path, $extra]) { if (!is_array($extra)) { @@ -135,6 +149,65 @@ public static function readPhpData(ProjectPackages $project): ?UpgradingData } + /** + * The packages shipping upgrading files, with the data of each. + * @return array> + */ + public function getDataPackages(): array + { + $res = []; + foreach ($this->upgradingData as $data) { + if ($data->layer->name !== null && $data->layer->package !== null) { + $res[$data->layer->package][] = $data; + } + } + + return $res; + } + + + /** + * The plugins of the packages shipping upgrading files, which an upgrade lets in without `use` naming them. + * @return list> + */ + public function findDataPlugins(): array + { + return array_values(array_intersect_key($this->plugins, $this->getDataPackages())); + } + + + /** + * The packages shipping upgrading files whose data reach the project, with a map or a requirement for the versions + * the code must work with, which no set covers. + * @return list + */ + public function findReachingPackages(): array + { + return array_keys(array_filter( + $this->getDataPackages(), + fn(array $files) => array_any($files, fn(UpgradingData $data) => $data->maps !== [] || $data->requirements !== []), + )); + } + + + /** + * The newest version the upgrading data of each library know of, PHP among them. + * @return array library => version + */ + public function findKnownVersions(): array + { + $versions = []; + foreach ($this->upgradingData as $data) { + if ($data->newest !== null && version_compare($data->newest, $versions[$data->package] ?? '0', '>')) { + $versions[$data->package] = $data->newest; + } + } + + ksort($versions); + return $versions; + } + + /** * The upgrading files of a package, relative to where it lies: every NEON file of the directory * `extra.dresscode.upgrading-dir` names, in the order of their names. @@ -158,6 +231,61 @@ public static function findUpgradingFiles(string $path, array $extra, string $pa } + /** + * The packages of upgrading data about a library the project requires itself, which neither the project nor the + * installation of DressCode holds. + * @param array> $catalogue package => the libraries it says it is about (`DataPackageCatalogue`) + * @param ?array $installation as `discover()` takes it + * @return list + */ + public static function findMissingDataPackages(ProjectPackages $project, array $catalogue, ?array $installation = null): array + { + $installation ??= self::findInstalledDataPackages(); + $missing = []; + foreach ($catalogue as $package => $libraries) { + if ($project->has($package) || isset($installation[$package])) { + continue; + } + + if (array_any(array_keys($project->required), fn(string $name) => self::isAbout($libraries, $name))) { + $missing[] = $package; + } + } + + return $missing; + } + + + /** + * Whether the library is one of those `extra.dresscode.packages` lists, a whole vendor written `vendor/`. + * @param list $libraries + */ + public static function isAbout(array $libraries, string $library): bool + { + return array_any($libraries, fn(string $name) => str_ends_with($name, '/') ? str_starts_with($library, $name) : $library === $name); + } + + + /** + * The packages of upgrading data installed beside DressCode, as Composer says of the running process. + * @return array package => where it lies + */ + public static function findInstalledDataPackages(): array + { + $found = []; + $packages = class_exists(InstalledVersions::class) ? InstalledVersions::getInstalledPackagesByType(self::PackageType) : []; + foreach (array_unique($packages) as $package) { + $path = InstalledVersions::getInstallPath($package); + $extra = $path === null ? null : (ComposerJson::read("$path/composer.json")['extra']['dresscode'] ?? null); + if (isset($extra['upgrading-dir'])) { + $found[$package] = Helpers::canonicalizePath(realpath($path) ?: $path); + } + } + + return $found; + } + + /** * The directory of the `composer.json` DressCode is installed by, globally, beside a project or as the project; * null for a phar and for a process Composer did not load. diff --git a/src/Config/ProjectPackages.php b/src/Config/ProjectPackages.php index 71ec83d5f7..2e181bbd22 100644 --- a/src/Config/ProjectPackages.php +++ b/src/Config/ProjectPackages.php @@ -9,7 +9,8 @@ use Composer\Semver\VersionParser; use DressCode\Analyses\PhpStanExtension; -use DressCode\Engine\Helpers; +use DressCode\Engine\{Helpers, ProcessRunner}; +use DressCode\Tristate; use Nette\Utils\FileSystem; use function is_array, is_string; @@ -37,7 +38,7 @@ public function __construct( /** @var array what the composer.json of the root package says under extra */ public array $rootExtra = [], /** @var array package the project requires itself => its constraint */ - private array $required = [], + public array $required = [], /** * @var array, prettyVersion?: string}> * installed package => the version it stands for (null for any), the source it came from, where it lies, its extra @@ -50,6 +51,8 @@ public function __construct( private array $replaced = [], /** the versions of PHP the code must work with, null where nobody said them */ private ?string $php = null, + /** the version of PHP `config.platform.php` sets, which Composer resolves the packages for; null for none */ + public ?string $platformPhp = null, ) { } @@ -106,6 +109,7 @@ public static function read(string $root): self $required, $installed, replaced: array_diff_key($replaced, $installed), + platformPhp: is_string($platform = $composer['config']['platform']['php'] ?? null) ? $platform : null, ); } @@ -118,7 +122,8 @@ public static function read(string $root): self public function withTargets(array $versions): self { return new self( - $this->rootName, $this->rootPath, $this->rootExtra, $this->required, $this->installed, $versions, $this->replaced, $this->php, + $this->rootName, $this->rootPath, $this->rootExtra, $this->required, + $this->installed, $versions, $this->replaced, $this->php, $this->platformPhp, ); } @@ -138,6 +143,7 @@ public function withPhp(string $target): self $this->targets, $this->replaced, Versions::isVersion($target) ? ">=$target" : $target, + $this->platformPhp, ); } @@ -155,6 +161,48 @@ public function has(string $package): bool } + /** + * Whether the project is a library, which says so by its `type`, a project giving none being one as Composer reads + * it, and has no lock of its own; maybe for one with a lock, as an application has. + */ + public function isLibrary(): Tristate + { + return match (true) { + $this->findType() !== 'library' => Tristate::No, + $this->hasOwnLock() => Tristate::Maybe, + default => Tristate::Yes, + }; + } + + + /** The type of the project, `library` where its composer.json gives none, as Composer reads it. */ + public function findType(): string + { + $type = ComposerJson::read("$this->rootPath/composer.json")['type'] ?? null; + return is_string($type) ? $type : 'library'; + } + + + /** + * Whether the project keeps a `composer.lock` of its own: one its git ignores is what an install of a library leaves, + * unless git ignores `composer.json` with it, the project then lying in a directory another repository ignores. + */ + private function hasOwnLock(): bool + { + if ($this->rootPath === null || !is_file("$this->rootPath/composer.lock")) { + return false; + } + + [, $ignored] = ProcessRunner::run( + ['git', '-C', $this->rootPath, 'check-ignore', 'composer.lock', 'composer.json'], + $this->rootPath, + timeout: 60, + errors: false, + ); + return preg_split('~\R~', trim($ignored)) !== ['composer.lock']; + } + + /** * The versions the lock of the project holds, a branch without a version of its own among them as null; null for a * project without a lock. @@ -215,24 +263,36 @@ public function findVersion(string $package): ?string } + /** + * The installed packages newer than the oldest version the project supports, by as little as a patch, where a + * declaration may say what the oldest version does not, a deprecation and its replacement above all. + * @return array package => the version installed and the lowest one supported + */ + public function findNewerInstalled(): array + { + $newer = []; + foreach ($this->installed as $package => ['version' => $installed]) { + $lowest = $this->findVersion($package); + if ($installed !== null && $lowest !== null && version_compare($lowest, $installed, '<')) { + $newer[$package] = [$installed, $lowest]; + } + } + + return $newer; + } + + /** * The directories of the installed packages whose declarations need not hold for the oldest version the project - * supports: those installed newer than it, by as little as a patch, where a declaration may say what the oldest - * version does not, a deprecation and its replacement above all, and those the project supports from no particular - * version. + * supports: those `findNewerInstalled()` lists and those the project supports from no particular version. * @return list */ public function findPathsAheadOfSupport(): array { + $newer = $this->findNewerInstalled(); $paths = []; - foreach ($this->installed as $package => ['version' => $installed, 'path' => $path]) { - $constraint = $this->findConstraint($package); - $lowest = $constraint === null ? null : Versions::findLowestVersion($constraint); - if ( - $path !== null - && $constraint !== null - && ($lowest === null || ($installed !== null && version_compare($lowest, $installed, '<'))) - ) { + foreach ($this->installed as $package => ['path' => $path]) { + if ($path !== null && (isset($newer[$package]) || $this->isUnbounded($package))) { $paths[] = $path; } } @@ -241,6 +301,17 @@ public function findPathsAheadOfSupport(): array } + /** + * Whether the project supports the package from no particular version, not requiring it or requiring it without + * a lower bound. + */ + public function isUnbounded(string $package): bool + { + $constraint = $this->findConstraint($package); + return $constraint !== null && Versions::findLowestVersion($constraint) === null; + } + + /** * The extensions of PHPStan the project has, the packages naming configuration files in `extra.phpstan.includes`, each * with those files PHPStan includes by itself, which `phpstan/extension-installer` makes it do, none without that diff --git a/src/Config/ResolvedProject.php b/src/Config/ResolvedProject.php index 0dbfcb131b..72957afd17 100644 --- a/src/Config/ResolvedProject.php +++ b/src/Config/ResolvedProject.php @@ -45,10 +45,33 @@ public function __construct( private ConfigResolver $resolver, /** the versions the code is written for unless an override says another */ private string $target, + /** @var list presets laid over those of the configuration and beneath its decisions and overrides */ + public array $laid = [], ) { } + /** The project with one more thing the user should be told. */ + public function withWarning(string $warning, ?string $docs = null): self + { + return new self( + $this->config, + $this->root, + $this->resolvedConfig, + $this->phpVersionSource, + [...$this->warnings, $warning => $docs], + $this->upgradingData, + $this->pluginManifests, + $this->projectPackages, + $this->commandLine, + $this->only, + $this->resolver, + $this->target, + $this->laid, + ); + } + + /** Every decision the rules of the run declare, those of the plugins and of the project among them. */ public function getCatalogue(): Catalogue { @@ -56,6 +79,16 @@ public function getCatalogue(): Catalogue } + /** + * What a name of `only` stands for in the project: the decisions of a preset, a section, a package or a rule. + * @throws ConfigurationException + */ + public function expandName(string $name): ExpandedName + { + return $this->resolver->expandName($name); + } + + /** * What the configuration comes to for a file matching those overrides; the same resolution the run uses. * @param list $overrides diff --git a/src/Config/RunnerFactory.php b/src/Config/RunnerFactory.php index c78d616b31..6f1aa1b5f2 100644 --- a/src/Config/RunnerFactory.php +++ b/src/Config/RunnerFactory.php @@ -10,7 +10,7 @@ use Composer\InstalledVersions; use DressCode\{Analyses, Config, ConfigurationException, Override, Plugin, PluginManifest, Profile, Rule}; use DressCode\Engine\{ - Baseline, FileFinder, FileProcessor, FileProcessors, Helpers, PhpFileProcessor, ReportPolicy, ResultCache, Runner, TypeAnalysisStatus, + Baseline, FileFinder, FileProcessor, FileProcessors, Helpers, PhpFileProcessor, Profiler, ReportPolicy, ResultCache, Runner, TypeAnalysisStatus, }; use Nette\Utils\Finder; use PhpSyntax\Node; @@ -29,6 +29,8 @@ public function __construct( public PluginRegistry $registry = new PluginRegistry, /** whether `phpstan/phpstan` is installed beside DressCode; null asks Composer */ private ?bool $phpstanInstalled = null, + /** the run goes without the types of the code even where the configuration asks for them, as `--no-types` says */ + private bool $withoutTypes = false, ) { } @@ -38,14 +40,27 @@ public function __construct( * override included. * @param ?Profile $commandLine laid over the configuration and its overrides, as --use is * @param ?list $only decisions, sections, presets and classes of rules the run is narrowed to + * @param list $laid presets laid over those of the configuration and beneath its decisions and overrides * @throws ConfigurationException */ - public function resolve(Config $config, string $root, ?Profile $commandLine = null, ?array $only = null): ResolvedProject + public function resolve( + Config $config, + string $root, + ?Profile $commandLine = null, + ?array $only = null, + array $laid = [], + ): ResolvedProject { - [$target, $source] = $this->getPhpTarget($config, $root); - $project = $this->readProjectPackages($config, $root, $target); + [$target, $source] = $this->getPhpTarget($config, $root, $commandLine); + $project = $this->readProjectPackages($config, $root, $target, $commandLine); $packages = PackageDiscovery::discover($project); - [$packagePlugins, $skipped, $unnamed] = $this->admitPackagePlugins($packages->plugins, $config, $commandLine, $project->rootName); + [$packagePlugins, $skipped, $unnamed] = $this->admitPackagePlugins( + $packages->plugins, + array_keys($packages->getDataPackages()), + $config, + $commandLine, + $project->rootName, + ); $visited = []; $plugins = [ ...$this->loadPlugins($packagePlugins, $visited), @@ -55,7 +70,7 @@ public function resolve(Config $config, string $root, ?Profile $commandLine = nu $this->registerProjectRules($config); // a command asking for the types has no run without them $commandTypes = $commandLine instanceof Config ? $commandLine->typeAnalysis : null; - $typesAvailable = ($commandTypes ?? $config->typeAnalysis) === null || $this->isPhpStanInstalled(); + $typesAvailable = !$this->withoutTypes && (($commandTypes ?? $config->typeAnalysis) === null || $this->isPhpStanInstalled()); if ($commandTypes !== null && !$typesAvailable) { throw new ConfigurationException( 'The command needs the types of the code, but `phpstan/phpstan` is not installed beside DressCode.', @@ -63,19 +78,19 @@ public function resolve(Config $config, string $root, ?Profile $commandLine = nu ); } - $resolver = new ConfigResolver($this->registry, $packages->upgradingData, $project, $typesAvailable, $root, $skipped); + $resolver = new ConfigResolver($this->registry, $packages->upgradingData, $project, $typesAvailable, $root, $skipped, $laid); $resolved = $resolver->resolve($config, $target, [], $commandLine, $only); $missing = array_map( fn(string $package) => $package === $project->rootName - ? "The configuration names package `$package` in `targets`, but that is the project itself, whose code is any version of it; skipped." - : "The configuration names package `$package` in `targets`, but it is not installed; skipped.", + ? "Package `$package` is named in `targets`, but that is the project itself, whose code is any version of it; skipped." + : "Package `$package` is named in `targets`, but it is not installed; skipped.", array_filter( - array_keys(array_diff_key($config->targets, [PackageDiscovery::Php => true])), + array_keys(array_diff_key(self::mergeTargets($config, $commandLine), [PackageDiscovery::Php => true])), fn(string $package) => !$project->has($package) || $package === $project->rootName, ), ); $warnings = array_fill_keys([...$packages->warnings, ...$unnamed, ...$missing, ...$resolver->getWarnings()], null); - if (!$typesAvailable) { + if (!$typesAvailable && !$this->withoutTypes) { $warnings['The configuration sets `typeAnalysis: phpstan`, but `phpstan/phpstan` is not installed beside DressCode, so the run goes without the types of the code.'] = 'types#enable'; } @@ -92,6 +107,7 @@ public function resolve(Config $config, string $root, ?Profile $commandLine = nu $only, $resolver, $target, + $laid, ); } @@ -115,6 +131,7 @@ public function createRunner( ?string $configFile = null, bool $fixRisky = false, bool $baseline = true, + ?Profiler $profiler = null, bool $refreshCache = false, array $leftAsWritten = [], ): Runner @@ -136,6 +153,7 @@ public function createRunner( self::resolveAnalysedPaths($config, $root), self::resolveCacheDir($config, $root) . '/phpstan', $phpVersion, + $profiler, $resolution->projectPackages->findPathsAheadOfSupport(), self::findForeignPaths($root), $resolution->projectPackages->findPhpStanExtensions(), @@ -149,7 +167,7 @@ public function createRunner( $processors = new FileProcessors( array_map(fn(Override $override) => $override->paths, $config->overrides), function (array $overrides) use ( - $resolution, $registry, $analyses, $strict, $baselineFile, $fixRisky, $leftAsWritten, + $resolution, $registry, $analyses, $strict, $baselineFile, $fixRisky, $profiler, $leftAsWritten, ): FileProcessor { $variant = $resolution->resolveFor($overrides); $style = $variant->createStyle(); @@ -174,6 +192,7 @@ function (array $overrides) use ( leftAsWritten: array_fill_keys($leftAsWritten, true), strict: $strict, ), + profiler: $profiler, gates: $variant->getGates(), ); }, @@ -213,6 +232,7 @@ function (array $overrides) use ( $baselineFile, $resultCache, narrowed: (bool) $resolution->only, + profiler: $profiler, warmUp: isset($phpstan) ? $phpstan->warmUp(...) : null, findDependencies: isset($phpstan) ? $phpstan->getConfigurationFiles(...) : null, findWarnings: isset($phpstan) ? $phpstan->getWarnings(...) : null, @@ -256,9 +276,10 @@ private function isPhpStanInstalled(): bool * without it, or the plugin in `use`, its own package needing no name, the others skipped with a warning; a package * named makes its name no preset. * @param array> $plugins package => its plugin + * @param list $carriers the packages shipping upgrading data, which `upgrade` lets in by itself * @return array{list>, list, list} the plugins, the packages skipped, the warnings */ - private function admitPackagePlugins(array $plugins, Config $config, ?Profile $commandLine, ?string $rootName): array + private function admitPackagePlugins(array $plugins, array $carriers, Config $config, ?Profile $commandLine, ?string $rootName): array { $named = [ ...$config->use, @@ -272,6 +293,11 @@ private function admitPackagePlugins(array $plugins, Config $config, ?Profile $c if ($package === $rootName || array_any([$package, $short, $plugin], fn(string $name) => in_array($name, $named, true))) { $admitted[] = $plugin; $this->registry->registerPluginPackage($package, $plugin); + } elseif (in_array($package, $carriers, true)) { + $skipped[] = $package; + $warnings[] = "Package `$package` brings rules that run only where `use` names it" + . ($short === $package ? '' : ", as `$short`") + . ', and in `dresscode upgrade`; skipped, with what its upgrading files set for them.'; } else { $skipped[] = $package; $warnings[] = "Package `$package` brings the plugin `$plugin`, which loads only where `use` names the package or the plugin; skipped."; @@ -378,7 +404,7 @@ private static function resolveCacheFile(Config $config, string $root): string } - private static function resolveCacheDir(Config $config, string $root): string + public static function resolveCacheDir(Config $config, string $root): string { $root = Helpers::canonicalizePath($root); $dir = $config->cacheDir === null ? sys_get_temp_dir() . '/dresscode' : Helpers::toAbsolutePath($config->cacheDir, $root); @@ -613,14 +639,14 @@ private static function hasClosures(ResolvedConfig $resolved, array $analyses): /** - * The versions the code is written for unless an override says another, as a Composer constraint: the configured - * one, or those the nearest composer.json allows, or the default one. The running version is never the answer: it - * says nothing about the code being checked. + * The versions the code is written for unless an override says another, as a Composer constraint: the one the + * command line or the configuration says, or those the nearest composer.json allows, or the default one. The running + * version is never the answer: it says nothing about the code being checked. * @return array{string, PhpVersionSource} */ - public function getPhpTarget(Config $config, string $root): array + public function getPhpTarget(Config $config, string $root, ?Profile $commandLine = null): array { - $php = $config->targets['php'] ?? null; + $php = self::mergeTargets($config, $commandLine)[PackageDiscovery::Php] ?? null; $detected = $php === null ? ComposerJson::detectPhpTarget(ComposerJson::findFile($root)) : null; return match (true) { $php !== null => [$php, PhpVersionSource::Configuration], @@ -631,13 +657,29 @@ public function getPhpTarget(Config $config, string $root): array /** - * The packages of the project with the versions the configuration says, PHP among them by the target, which a caller - * that has it already gives. + * The packages of the project with the versions the command line and the configuration say, PHP among them by the + * target, which a caller that has it already gives. */ - public function readProjectPackages(Config $config, string $root, ?string $phpTarget = null): ProjectPackages + public function readProjectPackages( + Config $config, + string $root, + ?string $phpTarget = null, + ?Profile $commandLine = null, + ): ProjectPackages { return ProjectPackages::read($root) - ->withTargets(array_diff_key($config->targets, [PackageDiscovery::Php => true])) - ->withPhp($phpTarget ?? $this->getPhpTarget($config, $root)[0]); + ->withTargets(array_diff_key(self::mergeTargets($config, $commandLine), [PackageDiscovery::Php => true])) + ->withPhp($phpTarget ?? $this->getPhpTarget($config, $root, $commandLine)[0]); + } + + + /** + * The targets of the configuration with those of the command line over them, which an upgrade lays for the versions + * it moves the code to before the upgrading data are cut for them. + * @return array + */ + public static function mergeTargets(Config $config, ?Profile $commandLine): array + { + return [...$config->targets, ...$commandLine->targets ?? []]; } } diff --git a/src/Config/UpgradingData.php b/src/Config/UpgradingData.php index 9a7d6fd874..73fc2c1215 100644 --- a/src/Config/UpgradingData.php +++ b/src/Config/UpgradingData.php @@ -34,21 +34,29 @@ public function __construct( public array $unreached = [], /** @var array the requirements of the rules of the plugin of the package it turns on => their values */ public array $requirements = [], + /** + * @var array> map => the key of an entry => the version of the section + * it came with and the version `from` says its fix is right from + */ + public array $origins = [], + /** the newest version a section of the file is of, null for what DressCode knows of a package itself */ + public ?string $newest = null, ) { } /** - * The maps and the requirements as the decisions of a layer, each under the path the closure gives it and left out - * where it gives none, the sentence of a retired entry ending with the package and the version that retired it - * (`, since acme/lib 3.0`). + * The maps and the requirements as the decisions of layers, each under the path the closure gives it and left out + * where it gives none: the entries in the layer of the section they came with, the requirements in the layer of the + * file, the sentence of a retired entry ending with the package and the version that retired it + * (`, since acme/lib 3.0`). Every entry stands in one layer, so their order decides nothing. * @param \Closure(string): ?string $findPath the map or the requirement => the path of its decision - * @return array + * @return list}> */ public function buildDecisions(\Closure $findPath): array { $package = $this->package === PackageDiscovery::Php ? 'PHP' : $this->package; - $tree = []; + $layers = $trees = []; foreach ($this->maps as $map => $entries) { $path = $findPath($map); if ($path === null) { @@ -60,16 +68,26 @@ public function buildDecisions(\Closure $findPath): array $entries[$key] = (is_string($sentence) ? rtrim($sentence, '.') . ', ' : '') . "since $package $version"; } - $tree = Helpers::placeValue($tree, $path, $entries); + $bySection = []; + foreach ($entries as $key => $value) { + [$since, $from] = $this->origins[$map][$key] ?? [null, null]; + $layers["$since|$from"] ??= $since === null ? $this->layer : $this->layer->withSection($this->package, $since, $from); + $bySection["$since|$from"][$key] = $value; + } + + foreach ($bySection as $id => $section) { + $trees[$id] = Helpers::placeValue($trees[$id] ?? [], $path, $section); + } } foreach ($this->requirements as $requirement => $value) { $path = $findPath($requirement); if ($path !== null) { - $tree = Helpers::placeValue($tree, $path, $value); + $layers['|'] ??= $this->layer; + $trees['|'] = Helpers::placeValue($trees['|'] ?? [], $path, $value); } } - return $tree; + return array_map(fn(string|int $id) => [$layers[$id], $trees[$id]], array_keys($trees)); } } diff --git a/src/Config/UpgradingFile.php b/src/Config/UpgradingFile.php index c8726f63c0..cbed92cff6 100644 --- a/src/Config/UpgradingFile.php +++ b/src/Config/UpgradingFile.php @@ -137,12 +137,13 @@ public function getSections(): array * rewritten where the lowest version reaches its section, or the version `from` says its fix is right from, a later * section having the last word on it: every entry where any version does, none where there is no lower bound. A * section above the lowest version says nothing, the lowest version not taking its fix, and turns no requirement on. + * Every entry keeps the section and the version `from` it came with. */ public function selectFor(?string $constraint, Layer $layer): UpgradingData { $lowest = $constraint === null ? null : Versions::findLowestVersion($constraint); $reaches = fn(string $version) => $constraint === null || ($lowest !== null && version_compare($lowest, $version, '>=')); - $maps = $retirements = $unreached = []; + $maps = $retirements = $origins = $unreached = []; foreach ($this->sections as $since => $section) { $since = (string) $since; $pending = false; @@ -155,6 +156,7 @@ public function selectFor(?string $constraint, Layer $layer): UpgradingData } $maps[$map][$key] = self::removeFrom($value); + $origins[$map][$key] = [$since, $from]; unset($retirements[$map][$key]); if (in_array($map, self::ForbiddenMaps, true) && $value !== MemberMapGrammar::Keep) { $retirements[$map][$key] = $since; @@ -174,7 +176,31 @@ public function selectFor(?string $constraint, Layer $layer): UpgradingData } } - return new UpgradingData($layer, $this->package, $this->namespaces, $maps, $retirements, $unreached, $requirements); + return new UpgradingData( + $layer, + $this->package, + $this->namespaces, + $maps, + $retirements, + $unreached, + $requirements, + $origins, + $this->findNewestVersion(), + ); + } + + + /** The newest version a section is of, the sections being in order of their versions. */ + private function findNewestVersion(): ?string + { + $newest = null; + foreach ([array_key_last($this->sections), array_key_last($this->requirements)] as $version) { + if ($version !== null && ($newest === null || version_compare((string) $version, $newest, '>'))) { + $newest = (string) $version; + } + } + + return $newest; } diff --git a/src/Config/Versions.php b/src/Config/Versions.php index e3ef185fca..4bcd83aba1 100644 --- a/src/Config/Versions.php +++ b/src/Config/Versions.php @@ -56,12 +56,19 @@ public static function isConstraint(string $constraint): bool /** The versions the constraint allows from the version on, `^8.1 || ^9.0` from 8.3 being `^8.1, >=8.3 || ^9.0, >=8.3`. */ - public static function raiseLowerBound(string $constraint, string $version): string + public static function restrictFrom(string $constraint, string $version): string { - return implode(' || ', array_map( - fn(string $part) => "$part, >=$version", - preg_split('~\s*\|\|?\s*~', trim($constraint)) ?: [], - )); + return implode(' || ', array_map(fn(string $part) => "$part, >=$version", self::splitAlternatives($constraint))); + } + + + /** + * The alternatives of the constraint `||` separates, `^3.2` and `^4.0` of `^3.2 || ^4.0`. + * @return list + */ + public static function splitAlternatives(string $constraint): array + { + return preg_split('~\s*\|\|?\s*~', trim($constraint), flags: PREG_SPLIT_NO_EMPTY) ?: []; } diff --git a/src/Console/Application.php b/src/Console/Application.php index bb3038ab38..0e2c6246c3 100644 --- a/src/Console/Application.php +++ b/src/Console/Application.php @@ -8,6 +8,7 @@ namespace DressCode\Console; use DressCode\{Config, ConfigurationException, ConvergenceException, RuleException}; +use DressCode\Engine\WorkerPool; use Nette\CommandLine\{ColorDepth, Command, Console, HelpRenderer, Parser as CommandLineParser, Prompt, UsageException}; use Nette\Utils\FileSystem; use function extension_loaded; @@ -19,7 +20,7 @@ */ final readonly class Application { - public const Version = '1.4.0'; + public const Version = '1.5-dev'; private CommandContext $context; @@ -28,7 +29,8 @@ * @param ?resource $stdout * @param ?resource $stderr * @param ?resource $stdin - * @param ?string $script the script the workers are started with, the one the process was started with by default + * @param ?string $script the script the workers and a run started again are started with, the program of this + * package by default; a command of its own giving `$defaultConfig` names its own, which carries that configuration * @param ?Config $defaultConfig what applies when the project has no configuration file * @param ?bool $xdebug whether Xdebug is loaded; detected when the output is the process's own * @param ?bool $interactive whether the output and the input are a terminal a person answers at; detected from each @@ -53,7 +55,9 @@ public function __construct( out: $out, err: $err, workingDirectory: $cwd ?? (string) getcwd(), - scriptFile: $script ?? $_SERVER['argv'][0] ?? 'dresscode', + scriptFile: $script ?? ($defaultConfig === null + ? WorkerPool::locateProgram() + : throw new \InvalidArgumentException('A command of its own giving a default configuration names its script, `script: __FILE__`, which its workers start so that they have that configuration too.')), defaultConfig: $defaultConfig, xdebug: $xdebug ?? ($stdout === null && extension_loaded('xdebug')), prompt: new Prompt($out, $stdin ?? STDIN, inputTerminal: $interactive), @@ -63,8 +67,9 @@ public function __construct( /** * Runs the command line and returns the exit code: 0 clean and complete, 1 violations, syntax errors, a refused - * baseline or work a migration leaves for the user, 2 a file that failed or a command that could not look at - * everything it was to, 3 a mistake of the command line or of the configuration. + * baseline or work an upgrade or a migration leaves for the user, 2 a file that failed, a commit refused or a command + * that could not look at everything it was to, 3 a mistake of the command line or of the configuration, 4 an upgrade + * waiting for a step outside DressCode. * @param list $argv including the script name */ public function run(array $argv): int @@ -75,6 +80,7 @@ public function run(array $argv): int } [$context, $out, $err] = [$this->context, $this->context->out, $this->context->err]; + $context->seekOutputEnd(); try { $args = (new CommandLineParser)->parse($this->defineCommandLine(), array_slice($argv, 1)); if ($args->get('--no-color')) { @@ -138,9 +144,23 @@ private function defineCommandLine(): Command $program->addFlag('--help', 'Print this help', standalone: true); $program->addFlag('--version', 'Print the name and the version', standalone: true); + // in the order the help lists them $context = $this->context; - foreach ([ // in the order the help lists them - new Commands\CheckCommand($context), + $program->addCommandsFrom(new Commands\CheckCommand($context)); + $upgrade = $program->addCommand( + 'upgrade', + 'Estimate, plan and carry out an upgrade to newer PHP and libraries', + commandRequired: true, + ); + $upgrade->addCommandsFrom(new Commands\UpgradeCommand($context)); + $upgrade->addText(implode("\n", [ + 'Examples:', + ' dresscode upgrade estimate php 8.4 what an upgrade to PHP 8.4 changes', + ' dresscode upgrade plan nette/utils 4.0 --save a plan for nette/utils 4.0, saved for review', + ' dresscode upgrade run the plan carried out step by step', + ' dresscode upgrade today the code rewritten for the versions required now', + ])); + foreach ([ new Commands\ConfigCommand($context), new Commands\ExplainCommand($context), new Commands\CatalogueCommand($context), @@ -152,7 +172,7 @@ private function defineCommandLine(): Command $program->addCommand('migrate', 'Move over from PHP CS Fixer, PHP_CodeSniffer or Laravel Pint', commandRequired: true) ->addCommandsFrom(new Commands\MigrateCommand($context)); - $program->addText('Exit codes: `0` clean and complete, `1` violations, syntax errors, a refused baseline or manual tasks a migration leaves, `2` a file failed or a command could not look at everything it was to, `3` a mistake of the command line or of the configuration.'); + $program->addText('Exit codes: `0` clean and complete, `1` violations, syntax errors, a refused baseline or manual tasks an upgrade or a migration leaves, `2` a file failed, a commit was refused or a command could not look at everything it was to, `3` a mistake of the command line or of the configuration, `4` an upgrade waiting for a step outside DressCode.'); return $program; } } diff --git a/src/Console/CommandContext.php b/src/Console/CommandContext.php index 9334b4462d..a84f314f01 100644 --- a/src/Console/CommandContext.php +++ b/src/Console/CommandContext.php @@ -10,7 +10,7 @@ use DressCode\{Config, ConfigurationException, Plugin}; use DressCode\Config\{Loader, PhpVersionSource, ResolvedProject, RunnerFactory}; use DressCode\Console\Commands\ConfigOptions; -use DressCode\Engine\Helpers; +use DressCode\Engine\{Helpers, WorkerPool}; use DressCode\Interop\{FormatterConfig, FormatterSearch}; use Nette\CommandLine\{Console, ParseResult, Prompt, UsageException}; use Nette\Neon\Neon; @@ -26,6 +26,10 @@ */ final readonly class CommandContext { + /** marks a process of DressCode another one started again, which starts none itself */ + private const RerunVariable = 'DRESSCODE_RERUN'; + + public function __construct( /** @var resource */ public mixed $stdout, @@ -37,7 +41,7 @@ public function __construct( public Console $err, /** the directory the paths of the command line are relative to */ public string $workingDirectory, - /** the script the workers are started with */ + /** the script the workers and a run started again are started with */ public string $scriptFile, /** what applies when the project has no configuration file */ public ?Config $defaultConfig, @@ -49,6 +53,40 @@ public function __construct( } + /** + * Runs DressCode again in a new process with the arguments and the variables given, which loads anew what this one + * loaded before the packages changed, its input and output those of this process; null where it cannot, as this + * process is embedded, so that its command line is not its own, or was started again itself. + * @param list $arguments + * @param array $env + */ + public function rerun(array $arguments, array $env = []): ?int + { + if ($this->stdout !== STDOUT || getenv(self::RerunVariable) !== false) { + return null; + } + + $command = [...WorkerPool::buildPhpCommand() ?? [PHP_BINARY], $this->scriptFile, ...$arguments]; + $env = [...getenv(), ...$env, self::RerunVariable => '1']; + $process = proc_open($command, [STDIN, STDOUT, STDERR], $pipes, $this->workingDirectory, $env); + return $process === false ? null : proc_close($process); + } + + + /** + * A process started again writes after what the one that started it wrote, as a file of the output it inherits + * starts at its beginning on Windows. + */ + public function seekOutputEnd(): void + { + if (getenv(self::RerunVariable) !== false) { + foreach ([$this->stdout, $this->stderr] as $stream) { + @fseek($stream, 0, SEEK_END); // @ a terminal or a pipe has no end to seek + } + } + } + + /** * The project as the command line names it, resolved: the factory that resolved it, its resolution and the file * of the configuration. @@ -66,16 +104,17 @@ public function resolveProject(ParseResult $args, ConfigOptions $options, array /** * The configuration, the root directory, the file it came from, and the layer the command line lays over them. + * @param ?Config $default the configuration of a command that runs without a file * @return array{config: Config, root: string, file: ?string, commandLine: ?Config} * @throws UsageException */ - public function loadConfig(ParseResult $args, ConfigOptions $options): array + public function loadConfig(ParseResult $args, ConfigOptions $options, ?Config $default = null): array { [$config, $root, $file] = Loader::load( $options->config === null ? null : Helpers::toAbsolutePath($options->config, $this->workingDirectory), $this->workingDirectory, // without a configuration file the run has only what the command line uses - $this->defaultConfig ?? ($options->use ? new Config : null), + $this->defaultConfig ?? $default ?? ($options->use ? new Config : null), $options->root === null ? null : Helpers::toAbsolutePath($options->root, $this->workingDirectory), ); return ['config' => $config, 'root' => $root, 'file' => $file, 'commandLine' => $this->readCommandLine($args, $options)]; @@ -142,6 +181,7 @@ public function writeHeader(?string $configFile, ResolvedProject $resolution, ?s [...$config->plugins, ...$commandLine instanceof Config ? $commandLine->plugins : []], ), ...$config->use, + ...$resolution->laid, ...$commandLine->use ?? [], ]; $this->out->writeLine($configFile === null diff --git a/src/Console/Commands/CheckCommand.php b/src/Console/Commands/CheckCommand.php index c0cb7ee421..7da515e1d9 100644 --- a/src/Console/Commands/CheckCommand.php +++ b/src/Console/Commands/CheckCommand.php @@ -7,13 +7,8 @@ namespace DressCode\Console\Commands; -use DressCode\{Config, Reporter, Reporters}; -use DressCode\Config\{PluginRegistry, ResolvedProject}; -use DressCode\Console\{CommandContext, Markup, ProgressBar, RiskReview}; -use DressCode\Engine\{Baseline, FileSummary, Helpers, LineRanges, Runner, RunResult, Worker, WorkerPool}; -use Nette\CommandLine\{Attributes as Cli, Console, ParseResult, UsageException}; -use Nette\Utils\FileSystem; -use function count, in_array, is_string, sprintf, strlen; +use DressCode\Console\{CommandContext, RunExecutor}; +use Nette\CommandLine\{Attributes as Cli, ParseResult}; /** @@ -22,16 +17,19 @@ */ final readonly class CheckCommand { - public function __construct( - private CommandContext $context, - ) { + private RunExecutor $executor; + + + public function __construct(CommandContext $context) + { + $this->executor = new RunExecutor($context); } #[Cli\Command('Report the violations')] public function check(ParseResult $args, RunOptions $run, CheckOptions $check, ConfigOptions $configuration): int { - return $this->run($args, $configuration, $run, $check); + return $this->executor->run($args, $configuration, $run, $check); } @@ -45,548 +43,13 @@ public function fix( ConfigOptions $configuration, ): int { - return $this->run($args, $configuration, $run, $check, fix: true, askRisky: (bool) $askRisky); + return $this->executor->run($args, $configuration, $run, $check, fix: true, askRisky: (bool) $askRisky); } #[Cli\Command('Write the violations a fix leaves into the baseline file of the configuration, once a fix changes nothing')] public function baseline(ParseResult $args, RunOptions $run, ConfigOptions $configuration): int { - return $this->run($args, $configuration, $run, generate: true); - } - - - /** - * @param ?CheckOptions $check what check and fix take beyond the run, null for the baseline - * @param bool $generate the baseline command writes the configured baseline, it never reads it - */ - private function run( - ParseResult $args, - ConfigOptions $configuration, - RunOptions $run, - ?CheckOptions $check = null, - bool $fix = false, - bool $generate = false, - bool $askRisky = false, - ): int - { - // `fix --stdin` is the formatter of an editor, which reads the text and the exit code alone - $formatter = $fix && $check?->stdin !== null; - foreach ([ - '--format' => $run->format, - '--diff' => $check?->diff, - '--max-warnings' => $check?->maxWarnings, - '--ask-risky' => $askRisky ?: null, - '--lines' => $check?->lines ?: null, - '--before' => $check?->before, - ] as $option => $value) { - if ($formatter && $value !== null) { - throw new UsageException( - "`fix --stdin` writes the fixed code alone, so it takes no `$option`; `check --stdin` reports on the code in any format.", - $args->command, - ); - } - } - - [$factory, $resolution, $configFile] = $this->context->resolveProject($args, $configuration, $check->only ?? []); - [$config, $root] = [$resolution->config, $resolution->root]; - $fixRisky = in_array(true, $check->fixRisky ?? [], true); // a bare `--fix-risky`, the names given go to the configuration - if ($run->worker !== null) { // the parent keeps the cache; the baseline decides what is reported - $runner = $factory->createRunner( - $resolution, - strict: (bool) $run->strictRules, - cache: false, - fixRisky: $fixRisky, - baseline: !$generate, - ); - ($runner->warmUp)?->__invoke(); // before connecting, which is what starts the other workers - return Worker::run($run->worker, $runner, $fix); - } - - $options = [ - 'strict' => (bool) $run->strictRules, - // the counts of a file served from the cache are those the baseline left - 'cache' => !$generate, - 'configFile' => $configFile, - 'fixRisky' => $fixRisky, - 'baseline' => !$generate, - 'refreshCache' => (bool) $run->noCache, - ]; - $runner = $factory->createRunner($resolution, ...$options); - [$out, $err] = [$this->context->out, $this->context->err]; - $format = self::resolveFormat($run->format, detect: true); - // only the parent warns, a worker has returned above; an agent can do nothing about the configuration - foreach ($formatter || $format === 'agent' ? [] : $resolution->warnings as $warning => $docs) { - $err->writeLine(Markup::highlightCode($err, "Warning: $warning", 'yellow')); - if ($docs !== null) { - $err->writeLine(Markup::formatDocsLink($err, $docs)); - } - } - - $stdinPath = $check?->stdin; - $paths = array_values(array_unique(array_map($this->context->resolvePath(...), $run->paths))); - $maxWarnings = $check?->maxWarnings; - if ($askRisky && ($check?->fixRisky || is_string($stdinPath))) { - throw new UsageException( - '`--ask-risky` asks about the risky fixes one by one, so it goes with neither `--fix-risky` nor `--stdin`.', - $args->command, - ); - } elseif ($askRisky && ($format !== 'console' || !$this->context->prompt->isInteractive())) { - throw new UsageException( - '`--ask-risky` asks in an interactive terminal; without one, allow the risky fixes with `--fix-risky=`.', - $args->command, - ); - } - - $lines = $check?->lines ? new LineRanges($check->lines) : null; - $before = $check?->before; - if ($lines && $format !== 'agent') { - throw new UsageException('`--lines` narrows what the `agent` format reports, so it goes with no other format.', $args->command); - } elseif ($before !== null && ($format !== 'agent' || is_string($stdinPath))) { - throw new UsageException( - '`--before` tells the `agent` format what an edit of a file did, so it goes with no other format and no `--stdin`.', - $args->command, - ); - } elseif ($lines && $run->strictRules) { - throw new UsageException( - '`--lines` names the lines of the file as it was read, which `--strict-rules` reads again in every round.', - $args->command, - ); - } - - if (is_string($stdinPath)) { - if ($paths) { - throw new UsageException('Paths cannot be combined with `--stdin`.', $args->command); - } - - return $formatter - ? $this->runFormatter($runner, $stdinPath, (bool) $run->skipExcluded, $config->paths) - : $this->runStdin( - self::resolveFormat($run->format, detect: false), // the caller of stdin is an editor or a hook waiting for the format it asked for - (bool) $check->diff, - $runner, - $factory->registry, - $resolution, - $stdinPath, - $maxWarnings, - (bool) $run->skipExcluded, - $config->paths, - $lines, - ); - } - - $scope = $paths ? $runner->files->narrowPaths($paths, $config->paths) : $config->paths; - if (!$scope) { - throw new UsageException('No paths given and none configured.', $args->command); - } - - // the machine-readable formats must not be prefaced, and a generated baseline is not a report - $preface = !$generate && in_array($format, ['console', 'github'], true); - if ($preface) { - if ($this->context->xdebug) { - $err->writeLine('Warning: Xdebug is loaded and makes the run many times slower.', 'red'); - } - - $this->context->writeHeader($configFile, $resolution, Baseline::findFile($config, $root)); - $out->setStatus(Markup::formatLabel($out, $fix ? 'Fixing' : 'Checking') . 'looking for files…'); - } - - try { - $files = $runner->files->findFiles($scope, skipExcluded: (bool) $run->skipExcluded, configured: $config->paths); - } finally { - $out->clearStatus(); - } - - if ($preface) { - $this->writeScope(files: $files, paths: $scope, root: $root, fix: $fix, narrowed: $paths && $scope !== $paths); - } - - if (($lines || $before !== null) && count($files) > 1) { - throw new UsageException( - ($lines ? '`--lines` names the lines of one file' : '`--before` names the text of one file') - . ', but ' . count($files) . ' files are to be run.', - $args->command, - ); - } elseif ($before !== null && $files) { - $code = @file_get_contents($this->context->resolvePath($before)); // @ the failure is said below - if ($code === false) { - throw new UsageException("Cannot read file `$before`, which `--before` names.", $args->command); - } - - $left = $this->findBrokenDecisions($runner, $files[0], $code); - $runner = $factory->createRunner($resolution, ...$options, leftAsWritten: $left); - $lines = new LineRanges($check->lines, array_fill_keys($left, true)); - } - - // a worker costs about the processing of a few files to start, so by default one for every four files at most - $jobs = $run->jobs ?? max(1, min(WorkerPool::detectCpuCount(), intdiv(count($files), 4))); - $command = $jobs > 1 && $files ? $this->buildWorkerCommand($args, $configuration, $run, $check) : null; - $workers = $command - ? new WorkerPool($command, $jobs, $this->context->workingDirectory, warmFirst: $runner->warmUp !== null) - : null; - $progress = !$generate && $format === 'console' && count($files) > 1 && $out->isTerminal() - ? new ProgressBar($out, count($files)) - : null; - $onProgress = $progress === null ? null : $progress->advance(...); - - try { - if ($generate) { - return $this->generateBaseline($runner, $config, $root, $configFile, $files, $workers, $format); - } - - $reporter = $this->createReporter( - (bool) $check?->diff, - $out, - $this->context->stdout, - $root, - $format, - $factory->registry, - $runner, - $resolution, - $run->paths, - ); - $result = $runner->run($files, $fix, $reporter, $workers, $onProgress, $maxWarnings, $lines); - return $askRisky - ? $this->review($runner, $result, $files, $root, $maxWarnings, $factory->registry) - : $result->getExitCode(); - - } finally { - $progress?->clear(); // an error must not be written into the bar - } - } - - - /** - * The decisions the file as it was before an edit broke, which the run then leaves as the file writes them. - * @return list - */ - private function findBrokenDecisions(Runner $runner, string $file, string $code): array - { - if ($runner->isKnownClean($file, $code)) { // the text the previous fix of the file wrote, most often - return []; - } - - $decisions = array_column($runner->processCode($file, $code)->violations, 'decision'); - return array_values(array_unique($decisions)); - } - - - /** - * Reports on the code read from stdin as if it were the file at the path; nothing of a path the excluded ones leave - * out where the caller asks to skip it. - * @param list $configured - */ - private function runStdin( - string $format, - bool $diff, - Runner $runner, - PluginRegistry $registry, - ResolvedProject $resolution, - string $path, - ?int $maxWarnings, - bool $skipExcluded, - array $configured, - ?LineRanges $lines, - ): int - { - $reporter = $this->createReporter( - $diff, - $this->context->out, - $this->context->stdout, - $resolution->root, - $format, - $registry, - $runner, - $resolution, - [$path], - ); - $code = (string) stream_get_contents($this->context->stdin); - $absolute = $this->context->resolvePath($path); - $skipped = $skipExcluded && $runner->files->excludes($absolute, $configured); - $reporter->start($runner->createRunInfo(false, $skipped ? 0 : 1)); - $result = $skipped ? null : $runner->processPath($absolute, fix: false, code: $code); - $result = $result === null ? null : $lines?->select($result, fix: false) ?? $result; - if ($result) { - $reporter->reportFile($result); - } - - $run = new RunResult($result ? [FileSummary::of($result)] : [], fix: false, maxWarnings: $maxWarnings); - $reporter->finish($run); - return $run->getExitCode(); - } - - - /** - * Formats the code read from stdin as if it were the file at the path, for an editor: the whole fixed code goes to - * stdout with exit code 0, whatever it still violates; a syntax error or a failure leaves the code as it came, its - * one line on stderr, and so does a path the excluded ones leave out, without a word. - * @param list $configured - */ - private function runFormatter(Runner $runner, string $path, bool $skipExcluded, array $configured): int - { - $code = (string) stream_get_contents($this->context->stdin); - $path = $this->context->resolvePath($path); - $result = $skipExcluded && $runner->files->excludes($path, $configured) - ? null - : $runner->processPath($path, fix: false, code: $code); - [$output, $error, $exit] = match (true) { - $result?->syntaxError !== null => [$code, "$result->path:$result->syntaxErrorLine: Syntax error: $result->syntaxError", 1], - $result?->failure !== null => [$code, "$result->path: " . strtok($result->failure, "\n"), 2], - default => [$result->output ?? $code, null, 0], - }; - - if ($error !== null) { - fwrite($this->context->stderr, "$error\n"); - } - - return fwrite($this->context->stdout, $output) === strlen($output) ? $exit : 2; - } - - - /** - * Asks about the risky fixes the fix left and makes those accepted, then says how it ended; the exit code is that of - * the files as the review left them. - * @param list $files - */ - private function review(Runner $runner, RunResult $result, array $files, string $root, ?int $maxWarnings, PluginRegistry $registry): int - { - $out = $this->context->out; - if ($result->countRefused() === 0) { - $out->writeLine("\n" . $out->color($result->getExitCode() === 0 ? 'white/green' : 'white/red', 'REVIEWED no risky fixes to ask about')); - return $result->getExitCode(); - } - - $made = new RiskReview($runner, $out, $this->context->prompt, $root, $registry)->review($result); - $final = $runner->run($files, true, new Reporters\NullReporter, maxWarnings: $maxWarnings); - $left = $final->countRefused(); - $out->writeLine( - "\n" . $out->color( - $final->getExitCode() === 0 ? 'white/green' : 'white/red', - sprintf( - 'REVIEWED %s made, %s', - Helpers::formatCount($made, 'risky fix', 'risky fixes'), - $left ? "$left left" : 'none left', - ), - ), - ); - return $final->getExitCode(); - } - - - /** - * What the rules are applied to: the scope reaches wherever the configuration was found, - * not where the run was started. - * @param list $files relative to the root, or absolute when outside it - * @param list $paths they were found under these - * @param bool $narrowed a directory named on the command line was narrowed to the configured paths - */ - private function writeScope(array $files, array $paths, string $root, bool $fix, bool $narrowed): void - { - $out = $this->context->out; - $absolute = array_map(fn(string $file) => FileSystem::isAbsolute($file) ? $file : "$root/$file", $files); - $scope = count($files) === 1 - ? FileSystem::platformSlashes($absolute[0]) - : sprintf('%d files in %s', count($files), FileSystem::platformSlashes(self::findCommonDirectory($absolute) ?: $root)); - $out->write($files - ? Markup::formatLabel($out, $fix ? 'Fixing' : 'Checking') . $scope - . ($narrowed ? $out->color('gray', ', narrowed to the configured paths') : '') . "\n\n" - : $out->color('yellow', sprintf( - ($fix ? 'Nothing to fix' : 'Nothing to check') . ': no file in %s', - implode(', ', array_map(FileSystem::platformSlashes(...), $paths)), - )) . "\n"); - } - - - /** - * The directory all the files share; that is the scope the run really has. - * @param list $files - */ - private static function findCommonDirectory(array $files): string - { - $common = null; - foreach ($files as $file) { - $segments = explode('/', $file); - array_pop($segments); - if ($common === null) { - $common = $segments; - continue; - } - - $length = 0; - while (isset($common[$length], $segments[$length]) && $common[$length] === $segments[$length]) { - $length++; - } - - $common = array_slice($common, 0, $length); - } - - return implode('/', $common ?? []); - } - - - /** - * The command line of a worker: the same PHP, the same command and configuration; the paths come over the - * connection. Null where there is no PHP to start one with, and the run stays in the process. - * @param ?CheckOptions $check null for the baseline - * @return ?list - */ - private function buildWorkerCommand(ParseResult $args, ConfigOptions $configuration, RunOptions $run, ?CheckOptions $check): ?array - { - $php = WorkerPool::buildPhpCommand(); - if ($php === null) { - return null; - } - - $command = [ - ...$php, - $this->context->scriptFile, - (string) $args->command->name, - '--no-color', - ]; - foreach ([ - '--config' => (array) $configuration->config, - '--use' => $configuration->use, - '--set' => $configuration->set, - '--severity' => $configuration->severity, - '--root' => (array) $configuration->root, - '--only' => $check->only ?? [], - ] as $option => $values) { - foreach ($values as $value) { - $command[] = "$option=$value"; // a value starting with a dash would read as an option - } - } - - if ($run->strictRules) { - $command[] = '--strict-rules'; - } - - foreach ($check->fixRisky ?? [] as $value) { // what a worker may fix has to be what the parent was asked for - $command[] = is_string($value) ? "--fix-risky=$value" : '--fix-risky'; - } - - return $command; - } - - - /** - * Runs the check without the current baseline over code a fix leaves alone and writes what remains into the - * configured baseline file, or into the one of the default name the run finds by itself; code a fix would still - * change, or a file that fails or does not parse, is refused. - * @param list $files - */ - private function generateBaseline( - Runner $runner, - Config $config, - string $root, - ?string $configFile, - array $files, - ?WorkerPool $workers, - string $format, - ): int - { - $name = $config->baseline ?? Baseline::getDefaultName($configFile); - $file = Helpers::toAbsolutePath($name, $root); - $run = $runner->run($files, fix: false, reporter: new Reporters\NullReporter, workers: $workers); - $changed = $failed = []; - foreach ($run->files as $result) { - if ($result->failure !== null || $result->syntaxError !== null) { - $failed[] = $result->path; - } elseif ($result->changed) { - $changed[] = $result->path; - } - } - - if ($changed || $failed) { - $counts = array_filter([ - $changed ? 'a fix would change ' . Helpers::formatCount(count($changed), 'file') : null, - $failed ? Helpers::formatCount(count($failed), 'file') . ' failed' : null, - ]); - $paths = [...$changed, ...$failed]; - $this->context->writeError( - 'The baseline is generated over code a fix leaves alone: ' . implode(', ', $counts) . '. Run `fix` first.', - 'suppressing#baseline', - implode('', array_map(fn(string $path) => " $path\n", array_slice($paths, 0, 10))) - . (count($paths) > 10 ? ' and ' . (count($paths) - 10) . " more\n" : ''), - ); - return 1; - } - - $baseline = Baseline::fromResults($run->files); - $baseline->save($file); - $message = 'Baseline with ' . Helpers::formatCount($baseline->count(), 'violation') . " written to `$name`.\n"; - // every other format keeps its stream to itself - $format === 'console' ? $this->context->write($message) : $this->context->writeNote($message); - return 0; - } - - - /** - * @param resource $stream the same place as the console; a machine-readable format is no text of a console - * @param string $root the paths of the results are relative to it - * @param list $paths the paths as the command line gave them - */ - private function createReporter( - bool $diff, - Console $console, - $stream, - string $root, - string $format, - PluginRegistry $registry, - Runner $runner, - ResolvedProject $resolution, - array $paths, - ): Reporter - { - return match ($format) { - 'lines' => new Reporters\LinesReporter($stream, $root, Helpers::canonicalizePath($this->context->workingDirectory)), - 'agent' => new Reporters\AgentReporter( - $stream, - $root, - Helpers::canonicalizePath($this->context->workingDirectory), - givenPaths: array_combine( - array_map(fn(string $path) => Helpers::canonicalizePath($this->context->resolvePath($path)), $paths), - $paths, - ), - findSuppressionExamples: function (string $path) use ($runner, $resolution): array { - $config = $resolution->resolveFor($runner->findOverridesFor($path)); - $examples = []; - foreach ($config->suppressionComments as $pattern => $decisions) { - foreach (isset($config->suppressionExamples[$pattern]) ? $decisions : [] as $decision) { - $examples[$decision][] = $config->suppressionExamples[$pattern]; - } - } - - return $examples; - }, - ), - 'json' => new Reporters\JsonReporter($stream), - 'checkstyle' => new Reporters\CheckstyleReporter($stream), - 'github' => new Reporters\GithubReporter($stream, $root, self::findEnv('GITHUB_WORKSPACE')), - default => new Reporters\ConsoleReporter( - $console, - diff: $diff, - root: $root, - cwd: Helpers::canonicalizePath($this->context->workingDirectory), - findDecisionUrl: $registry->findUrl(...), - ), - }; - } - - - /** - * The format asked for, or the one the surroundings call for: annotations when the run is a step - * of a GitHub Actions workflow, where nobody reads the log. - * @param bool $detect let the surroundings decide when the command line does not - */ - private static function resolveFormat(?string $format, bool $detect): string - { - return $format ?? ($detect && self::findEnv('GITHUB_ACTIONS') === 'true' ? 'github' : 'console'); - } - - - private static function findEnv(string $name): ?string - { - $value = getenv($name); - return $value === false || $value === '' ? null : $value; + return $this->executor->run($args, $configuration, $run, generate: true); } } diff --git a/src/Console/Commands/ConfigOptions.php b/src/Console/Commands/ConfigOptions.php index 16595ffa2b..cd8c3ff83a 100644 --- a/src/Console/Commands/ConfigOptions.php +++ b/src/Console/Commands/ConfigOptions.php @@ -53,6 +53,30 @@ public function __construct( } + /** + * The options as the command line of another process of DressCode gives them, each value glued to its option, as + * one starting with a dash would read as an option of its own. + * @return list + */ + public function toArguments(): array + { + $arguments = []; + foreach ([ + '--config' => (array) $this->config, + '--use' => $this->use, + '--set' => $this->set, + '--severity' => $this->severity, + '--root' => (array) $this->root, + ] as $option => $values) { + foreach ($values as $value) { + $arguments[] = "$option=$value"; + } + } + + return $arguments; + } + + /** * The normalizer of `--use`, which names a preset or a plugin, not a decision. */ diff --git a/src/Console/Commands/DataPackageOffer.php b/src/Console/Commands/DataPackageOffer.php new file mode 100644 index 0000000000..eb74a6f7b5 --- /dev/null +++ b/src/Console/Commands/DataPackageOffer.php @@ -0,0 +1,77 @@ + $config, 'root' => $root] = $this->context->loadConfig($args, $configuration, new Config(paths: ['.'])); + $installation = DataPackageInstallation::find($root, RunnerFactory::resolveCacheDir($config, $root)); + if ($installation === null) { + return false; + } + + $names = implode(', ', array_map(fn(string $package) => "`$package`", $installation->packages)); + $reason = 'The libraries of the project have upgrading data in ' . $names . ', which DressCode does not have'; + if ($installation->directory === null) { + throw new ConfigurationException("$reason, and its installation is not one Composer can add to; install the package beside DressCode."); + } + + $command = $installation->formatCommand(); + if (!$yes) { + if (!$mayAsk) { + throw new ConfigurationException("$reason; install it with `$command`, or let `dresscode " . TodayUpgrade::Command . ' --yes` do it.'); + } + + $this->context->write("$reason.\n"); + $where = $installation->intoProject + ? 'into the project, which changes its `composer.json`' + : "beside DressCode in `$installation->directory`"; + if ($this->context->prompt->choose(Markup::highlightCode($this->context->out, "Install it $where?"), ['y', 'n'], 'y') !== 'y') { + return false; + } + } + + // the progress goes to standard error, so that the output of the run stays the one document a format asks for + $this->context->err->writeLine("Installing $names\u{2026}"); + try { + $installation->install(); + } catch (ComposerException $e) { + throw new ConfigurationException( + "Composer did not install the upgrading data with `$command`: {$e->getMessage()}", + previous: $e, + ); + } + + return true; + } +} diff --git a/src/Console/Commands/EstimateOptions.php b/src/Console/Commands/EstimateOptions.php new file mode 100644 index 0000000000..43a16e5c6c --- /dev/null +++ b/src/Console/Commands/EstimateOptions.php @@ -0,0 +1,50 @@ + */ + #[Cli\Option('Files or directories within the configured paths; all of them when omitted', valueName: 'path', repeatable: true)] + public array $paths = [], + #[Cli\Option( + 'Output format: `console`, or `json` for a tool or an AI agent, which never asks', + alias: '-f', + enum: ['console', 'json'], + )] + public ?string $format = null, + #[Cli\Flag( + 'Measure with the types of the code from PHPStan, without asking; `--no-types` without them', + negatable: true, + )] + public ?bool $types = null, + #[Cli\Flag('Measure without asking the network: what Packagist offers as remembered, what Composer knows from the lock')] + public ?bool $offline = null, + #[Cli\Option( + 'Number of worker processes; by default the number of processors, at most one per four files; `1` runs in-process', + valueName: 'n', + normalizer: [RunOptions::class, 'parsePositiveInt'], + )] + public ?int $jobs = null, + /** the address of the parent; a worker started by WorkerPool */ + #[Cli\Option(hidden: true)] + public ?string $worker = null, + /** the file the parent wrote the check a worker of the estimate repeats into */ + #[Cli\Option(hidden: true)] + public ?string $checkFile = null, + ) { + } +} diff --git a/src/Console/Commands/PlanOptions.php b/src/Console/Commands/PlanOptions.php new file mode 100644 index 0000000000..e39ca844a9 --- /dev/null +++ b/src/Console/Commands/PlanOptions.php @@ -0,0 +1,58 @@ +testCommand ?? $this->quickTestCommand ?? $this->library) !== null; + } + + + /** Why the options given do not go together, as the command line writes them; null where they do. */ + public function findMisuse(): ?string + { + $noReport = array_find( + [$this->testCommand, $this->quickTestCommand], + fn(?string $command) => $command !== null && !TestResults::hasJunitPlaceholder($command), + ); + return $noReport === null + ? null + : "A command of the tests writes its JUnit report where `{junit}` stands, and `$noReport` has none."; + } +} diff --git a/src/Console/Commands/PlanRunOptions.php b/src/Console/Commands/PlanRunOptions.php new file mode 100644 index 0000000000..e407fecc08 --- /dev/null +++ b/src/Console/Commands/PlanRunOptions.php @@ -0,0 +1,30 @@ + $changes the operations of Composer, as `- Upgrading nette/utils (v3.2.10 => v4.0.11)` */ + public function approve(DependencyStep $step, array $changes): bool + { + $console = $this->console; + $console->clearStatus(); + $console->writeLine( + Markup::formatLine( + $console, + 'Composer', + "$step->title, " . ($changes === [] ? 'which changes no installed package' : 'which changes:'), + ), + ); + foreach ($changes as $change) { + $console->writeLine(" $change"); + } + + // a raise installs the lowest versions it allows, which may be older than those the lock holds today + $downgrades = count(preg_grep('~^- Downgrading ~', $changes) ?: []); + if ($downgrades > 0) { + $console->writeLine(Markup::formatLine( + $console, + 'Downgrades', + Helpers::formatCount($downgrades, 'package') . ' the lock holds newer', + ', installed at the lowest versions the constraints allow, which the code is written for; the last step of the plan updates them', + )); + } + + $question = $step instanceof UpdateStep ? 'Update the packages?' : 'Change `composer.json` and update the packages?'; + if (!$this->yes && $this->context->prompt->choose(Markup::highlightCode($console, $question), ['y', 'n'], 'y') !== 'y') { + return false; + } + + $console->setStatus(Markup::formatLabel($console, 'Upgrading') . "Composer, $step->title\u{2026}"); + return true; + } +} diff --git a/src/Console/Commands/RunHandoff.php b/src/Console/Commands/RunHandoff.php new file mode 100644 index 0000000000..46ac819f0b --- /dev/null +++ b/src/Console/Commands/RunHandoff.php @@ -0,0 +1,91 @@ +file ?? throw new \LogicException('The user started the run, so there is no run to hand back to.'); + Helpers::replaceFile($file, json_encode($outcome->toArray(), JSON_THROW_ON_ERROR)); + } + + + /** + * Goes on after the raise in a new process as often as the plan has steps of Composer, each process handing back + * where it stopped at the next raise; null where this process starts none, as an embedded one. + * @param list $rerun the command line of the run + */ + public static function goOn(CommandContext $context, RunOutcome $outcome, Plan $plan, array $rerun): ?int + { + $file = sys_get_temp_dir() . '/dresscode-handoff-' . bin2hex(random_bytes(8)) . '.json'; + $raises = count(array_filter($plan->findSteps(), fn(Step $step) => $step instanceof DependencyStep)); + try { + while ($raises-- > 0) { + Helpers::replaceFile($file, json_encode($outcome->toArray(), JSON_THROW_ON_ERROR)); + $exit = $context->rerun($rerun, [self::Variable => $file]); + if ($exit === null || !is_file($file)) { // the run cannot go on here, or went on to its end + return $exit; + } + + $outcome = self::read($file); + } + } finally { + @unlink($file); // @ the last run took it + } + + throw new \LogicException('The plan raised more often than it has steps of Composer.'); + } + + + private static function read(string $file): RunOutcome + { + return RunOutcome::fromArray((array) json_decode(FileSystem::read($file), associative: true, flags: JSON_THROW_ON_ERROR)); + } +} diff --git a/src/Console/Commands/RunOptions.php b/src/Console/Commands/RunOptions.php index d6514be597..74b4e92c4e 100644 --- a/src/Console/Commands/RunOptions.php +++ b/src/Console/Commands/RunOptions.php @@ -41,6 +41,9 @@ enum: ['console', 'agent', 'lines', 'github', 'json', 'checkstyle'], /** the address of the parent; a worker started by WorkerPool */ #[Cli\Option(hidden: true)] public ?string $worker = null, + /** a file to write where the time of the run went, see Profiler */ + #[Cli\Option(hidden: true)] + public ?string $profile = null, ) { } diff --git a/src/Console/Commands/TodayOptions.php b/src/Console/Commands/TodayOptions.php new file mode 100644 index 0000000000..efa0baffaa --- /dev/null +++ b/src/Console/Commands/TodayOptions.php @@ -0,0 +1,82 @@ + */ + #[Cli\Option('Files or directories; the configured paths when omitted', valueName: 'path', repeatable: true)] + public array $paths = [], + #[Cli\Option('Output format, any `fix` writes', alias: '-f', enum: ['console', 'json', 'agent', 'lines', 'github', 'checkstyle'])] + public ?string $format = null, + #[Cli\Flag('Also write what newer PHP offers, the set `modernizations`')] + public ?bool $modernize = null, + #[Cli\Flag('Ask about every risky fix left, one at a time with its diff, and make those accepted; needs an interactive terminal')] + public ?bool $askRisky = null, + #[Cli\Flag('Install the upgrading data the libraries of the project need without asking, outside a terminal too')] + public ?bool $yes = null, + /** @var list */ + #[Cli\Option( + 'Also make the fixes that may change what the code does: all, or with `=name` those of a decision, rule, preset or package. They are reported either way', + valueName: 'name', + valueOptional: true, + repeatable: true, + )] + public array $fixRisky = [], + /** @var list */ + #[Cli\Option( + 'Run only these: a decision, section, rule or preset, or a package of upgrading data with the rules reading it', + valueName: 'name', + repeatable: true, + )] + public array $only = [], + #[Cli\Option( + 'Exit with `1` when more than `n` warnings are left, as in CI', + valueName: 'n', + normalizer: [CheckOptions::class, 'parseMaxWarnings'], + )] + public ?int $maxWarnings = null, + #[Cli\Option( + 'Number of worker processes; by default the number of processors, at most one per four files; `1` runs in-process', + valueName: 'n', + normalizer: [RunOptions::class, 'parsePositiveInt'], + )] + public ?int $jobs = null, + #[Cli\Flag('Process every file, even one whose content is known to be clean')] + public ?bool $noCache = null, + /** the address of the parent; a worker started by WorkerPool */ + #[Cli\Option(hidden: true)] + public ?string $worker = null, + /** a file to write where the time of the run went, see Profiler */ + #[Cli\Option(hidden: true)] + public ?string $profile = null, + ) { + } + + + /** The run over the files it makes. */ + public function toRunOptions(): RunOptions + { + return new RunOptions( + $this->paths, + $this->format, + noCache: $this->noCache, + jobs: $this->jobs, + worker: $this->worker, + profile: $this->profile, + ); + } +} diff --git a/src/Console/Commands/TodayUpgrade.php b/src/Console/Commands/TodayUpgrade.php new file mode 100644 index 0000000000..b34b0137e0 --- /dev/null +++ b/src/Console/Commands/TodayUpgrade.php @@ -0,0 +1,142 @@ + those of `--only`, which the parent gives a worker too */ + private array $only, + ) { + } + + + /** + * The project of the run: its configuration, or the scope `init` would write where it has none, with the sets of the + * upgrade laid over the presets it uses and beneath its own decisions and overrides, and the plugins of the packages + * of upgrading data with the types of the code and the names resolved for certain over it all, narrowed by `--only`, + * or where it has a configuration to the decisions its style keeps and to the packages whose data reach the project. + * @return array{RunnerFactory, ResolvedProject, ?string} + * @throws ConfigurationException + */ + public function resolve(ParseResult $args, ConfigOptions $configuration): array + { + ['config' => $config, 'root' => $root, 'file' => $file, 'commandLine' => $commandLine] + = $this->context->loadConfig($args, $configuration, new Config(paths: ['.'])); + $project = Project::fromConfig($config, $root, $file, $commandLine); + $config = $project->config; + $discovered = $project->discoverPackages(); + $sets = $this->modernize ? ['deprecations', 'modernizations'] : ['deprecations']; + $names = $project->resolveNames(); + $layer = $project->createLayer($discovered->findDataPlugins(), types: true, declarations: $names->declarations); + $only = $this->only; + if ($file !== null && !$only) { + $only = [...$project->measureSatisfiedRequirements(), ...$sets, ...$discovered->findReachingPackages()]; + } + + [$factory, $resolution] = new UpgradeCheck($layer, $only ?: null, $sets)->resolve($config, $root); + return [$factory, $names->warning === null ? $resolution : $resolution->withWarning($names->warning), $file]; + } + + + /** + * What a worker gets on its command line beyond that of `check`: the sets, and what the parent narrowed the run to, + * unless `--only` did, which goes over as it is. + * @return list + */ + public function getWorkerOptions(ResolvedProject $resolution): array + { + return [ + ...$this->modernize ? ['--modernize'] : [], + ...$this->only ? [] : array_map(fn(string $name) => "--only=$name", $resolution->only ?? []), + ]; + } + + + /** + * What the run upgrades by: the packages of upgrading data, those installed newer than the lowest version the + * project allows, whose declarations then say nothing of what that one deprecates, and those it allows in any version, + * whose data and declarations say nothing at all. + */ + public function writePreface(ResolvedProject $resolution): void + { + $out = $this->context->out; + $project = $resolution->projectPackages; + $packages = array_diff( + array_unique(array_map(fn(array $data) => $data[0]->package, $resolution->upgradingData)), + [PackageDiscovery::Php], + ); + $codes = fn(array $packages) => implode(', ', array_map(fn(string $package) => "`$package`", $packages)); + $out->writeLine( + Markup::formatLine($out, 'Upgrading', $codes($packages) ?: 'PHP alone, no installed library has upgrading data'), + ); + + $newer = []; + foreach ($project->findNewerInstalled() as $package => [$installed, $lowest]) { + $newer[] = "`$package` " . Versions::formatVersion($installed) . " installed, $lowest required"; + } + + if ($newer !== []) { + $out->writeLine(Markup::formatLine( + $out, + 'Lowest', + implode(', ', $newer), + '; `composer update --prefer-lowest` lets the upgrade see what the lowest versions deprecate', + )); + } + + $unbounded = array_filter($packages, $project->isUnbounded(...)); + if ($unbounded !== []) { + $out->writeLine(Markup::formatLine( + $out, + 'Unbounded', + $codes($unbounded), + ': not required with a lower bound, so neither the upgrading data nor the deprecations say anything', + )); + } + } + + + /** + * The files the run goes through, without those a generator wrote. + * @param list $files relative to the root, or absolute when outside it + * @return list + */ + public function leaveOutGenerated(array $files, string $root, bool $preface): array + { + $found = UpgradeFiles::fromScope($root, $files); + if ($preface && $found->generated !== []) { + $out = $this->context->out; + $out->writeLine(Markup::formatLine($out, 'Left out', Helpers::formatCount(count($found->generated), 'generated file'))); + } + + return $found->files; + } +} diff --git a/src/Console/Commands/UpgradeCommand.php b/src/Console/Commands/UpgradeCommand.php new file mode 100644 index 0000000000..c9a1814f22 --- /dev/null +++ b/src/Console/Commands/UpgradeCommand.php @@ -0,0 +1,748 @@ +executor = new RunExecutor($context); + } + + + #[Cli\Command('Estimate the changes of the code an upgrade to a newer PHP or library needs, changing nothing')] + public function estimate( + ParseResult $args, + #[Cli\Argument('`php` or a package; PHP and every library with upgrading data when omitted', optional: true)] + ?string $target, + #[Cli\Argument('The version to upgrade to; for PHP the newest its upgrading data know when omitted', optional: true)] + ?string $version, + EstimateOptions $options, + ConfigOptions $configuration, + ): int + { + if ($options->worker !== null && $options->checkFile !== null) { + return $this->runEstimateWorker($args, $options->worker, $options->checkFile, $configuration); + } + + $project = $this->loadProject($args, $configuration); + $console = $this->findConsole($options->format); + $types = $this->decideTypes($options->types, $this->mayAsk($options->format), $project->config); + $estimate = $this->measure($args, $project, $target, $version, $types, $options, $configuration, $console); + $printer = new EstimatePrinter($estimate); + if ($console === null) { + $this->writeJson($project, $printer->toArray()); + } else { + $command = implode(' ', array_filter(['dresscode upgrade plan', $target, $version], fn($word) => $word !== null)); + $console->write($printer->print($console) . ($estimate->topics === [] + ? '' + : "\n" . Markup::formatLine($console, 'Next', "`$command` orders this into steps you can run") . "\n")); + } + + return $estimate->isComplete() ? 0 : 2; + } + + + #[Cli\Command('Order the estimate into the steps of an upgrade, changing nothing; `--save` keeps the plan')] + public function plan( + ParseResult $args, + #[Cli\Argument('`php` or a package; PHP and every library with upgrading data when omitted', optional: true)] + ?string $target, + #[Cli\Argument('The version to upgrade to; for PHP the newest its upgrading data know when omitted', optional: true)] + ?string $version, + #[Cli\Flag('Save the plan into `dresscode-upgrade.neon`, which the team may edit and `upgrade run` carries out')] + ?bool $save, + #[Cli\Flag('Drop what a run interrupted in a step kept of its files, which saving the plan forgets')] + ?bool $discard, + EstimateOptions $options, + PlanOptions $planning, + ConfigOptions $configuration, + ): int + { + if (($misuse = $planning->findMisuse()) !== null) { + throw new UsageException($misuse, $args->command); + } + + $project = $this->loadProject($args, $configuration); + $console = $this->findConsole($options->format); + $types = $this->decideTypes($options->types, $this->mayAsk($options->format), $project->config); + [$estimate, $plan, $mode] = $this->makePlan( + $args, $project, $target, $version, $types, $options, $planning, $configuration, $console, + ); + // the plan comes after the estimate it orders, which says what it cannot see and what it is not sure of + $estimatePrinter = new EstimatePrinter($estimate); + $planPrinter = new PlanPrinter($plan, $mode); + $console?->write($estimatePrinter->print($console) . "\n" . $planPrinter->print($console)); + if ($save) { + $this->savePlan($args, $plan, $project, (bool) $discard, $console); + } + + if ($console === null) { + $this->writeJson($project, [...$planPrinter->toArray(), 'estimate' => $estimatePrinter->toArray()], saved: (bool) $save); + } + + if ($plan->steps !== []) { + $console?->writeLine(Markup::formatLine($console, 'Next', $save + ? '`dresscode upgrade run` carries out the plan saved, step by step' + : '`--save` keeps the plan in `' + . PlanFile::Name + . '` for the team to review, which `dresscode upgrade run` then carries out')); + } + + return $estimate->isComplete() ? 0 : 2; + } + + + #[Cli\Command('Carry out the saved plan, or make one for the target first; stops where Composer or you are needed')] + public function run( + ParseResult $args, + #[Cli\Argument('`php` or a package, to make a plan for; the saved plan when omitted', optional: true)] + ?string $target, + #[Cli\Argument('The version to upgrade to; for PHP the newest its upgrading data know when omitted', optional: true)] + ?string $version, + EstimateOptions $options, + PlanOptions $planning, + PlanRunOptions $running, + ConfigOptions $configuration, + ): int + { + if ($target === null && ($planning->isGiven() || $options->paths !== [] || $options->offline || $options->jobs !== null)) { + throw new UsageException( + '`--paths`, `--offline`, `--jobs`, the commands of the tests and `--library` make a plan, which a target does; without one `upgrade run` carries out the saved plan as it is.', + $args->command, + ); + } elseif (($misuse = $planning->findMisuse()) !== null) { + throw new UsageException($misuse, $args->command); + } + + $project = $this->loadProject($args, $configuration); + if ($target !== null && PlanFile::exists($project->root)) { + throw new UsageException( + 'The project has a saved plan, `' + . PlanFile::Name + . '`, which `upgrade run` carries out; `upgrade plan --save` replaces it.', + $args->command, + ); + } + + $console = $this->findConsole($options->format); + $mayAsk = $this->mayAsk($options->format); + $types = $this->decideTypes($options->types, $mayAsk, $project->config); + $runner = $this->createPlanRunner($project, $types, (bool) $running->commit, $console); + $handoff = RunHandoff::take(); + if ($target === null) { + $plan = PlanFile::read($project->root); + if ($console !== null && $handoff->resumed === null) { + self::writeHeader($console, $project); + } + } else { + [$estimate, $plan, $mode] = $this->makePlan( + $args, $project, $target, $version, $types, $options, $planning, $configuration, $console, + ); + $console?->write( + new EstimatePrinter($estimate)->print($console, passive: false) . "\n" . new PlanPrinter($plan, $mode)->print($console), + ); + $this->savePlan($args, $plan, $project, (bool) $running->discard, $console); + } + + // the run after a raise goes on in a process of its own with what this one decided + $rerun = [ + 'upgrade', + 'run', + $types ? '--types' : '--no-types', + ...$options->format === null ? [] : ["--format=$options->format"], + ...$running->yes ? ['--yes'] : [], + ...$running->commit ? ['--commit'] : [], + ...$args->get('--no-color') ? ['--no-color'] : [], + ...$configuration->toArguments(), + ]; + return $this->runPlan($plan, $runner, $running, $mayAsk, $console, $rerun, $handoff); + } + + + #[Cli\Command('Undo an unfinished upgrade: restore the files of an interrupted step and the `composer.json` and lock a raise changed')] + public function abort( + ParseResult $args, + ConfigOptions $configuration, + #[Cli\Flag('Say what it would put back and leave, changing nothing')] + bool $dryRun = false, + ): int + { + $project = $this->loadProject($args, $configuration); + $console = $this->context->out; + self::writeHeader($console, $project); + $restoration = new RunState($project)->restore( + $project, + Composer::forProject($project->root), + $dryRun, + fn(string $what) => $console->setStatus(Markup::formatLabel($console, 'Upgrading') . "$what\u{2026}"), + ); + $console->clearStatus(); + [$restored, $left, $installFailure] = [$restoration->restored, $restoration->left, $restoration->installFailure]; + if ($restored !== [] || !$restoration->installs) { + $console->writeLine(Markup::formatLine( + $console, + $dryRun ? 'Restorable' : 'Restored', + $restored === [] ? 'nothing, as no run keeps anything to go back' : implode(', ', $restored), + )); + } + + if ($restoration->installs && $installFailure === null) { + $console->writeLine( + Markup::formatLine($console, $dryRun ? 'Installs' : 'Installed', 'the packages of the lock', ', by `composer install`'), + ); + } + + foreach ($left as $path => $why) { + $console->writeLine(Markup::formatLine($console, 'Left', "$path: $why")); + } + + if ($installFailure !== null) { + $console->writeLine(Markup::formatLine($console, 'Failed', "`composer install`: $installFailure")); + } + + return $dryRun || ($left === [] && $installFailure === null) ? 0 : 1; + } + + + #[Cli\Command('List the manual tasks the saved plan leaves in the code as it stands, changing nothing')] + public function tasks( + ParseResult $args, + #[Cli\Flag( + 'Look with the types of the code from PHPStan, without asking; `--no-types` without them', + negatable: true, + )] + ?bool $types, + #[Cli\Option( + 'Output format: `console`, or `json` for a tool or an AI agent, which never asks', + alias: '-f', + enum: ['console', 'json'], + )] + ?string $format, + ConfigOptions $configuration, + ): int + { + $project = $this->loadProject($args, $configuration); + $console = $this->findConsole($format); + $plan = PlanFile::read($project->root); + $runner = $this->createPlanRunner($project, $this->decideTypes($types, $this->mayAsk($format), $project->config), false, $console); + if ($console !== null) { + self::writeHeader($console, $project); + } + + try { + [$tasks, $unprocessed] = $runner->findTasks($plan); + $postponed = Postponement::findIn($project, $plan->paths); + } finally { + ($console ?? $this->context->err)->clearStatus(); + } + + $printer = new TasksPrinter($tasks, $postponed, $unprocessed, $project->root); + $left = $tasks !== [] || $postponed !== []; + $due = $plan->findDueRaise(ProjectPackages::read($project->root)); + $dueTitle = $due === null ? null : $plan->findSteps()[$due]->title; + if ($console === null) { + $this->writeJson($project, [ + 'version' => TasksPrinter::Version, + ...$printer->toArray(), + 'due' => $due === null ? null : ['step' => $due, 'title' => $dueTitle], + ], saved: true); + } else { + $console->write($printer->print($console)); + $found = $left ? 'manual tasks' : 'no manual task'; + $found = $due === null ? "the plan leaves $found" : "$found before step $due, $dueTitle"; + $console->writeLine(match (true) { + $unprocessed !== [] => $console->color('white/red', "FAILED $found" . ($due === null ? '' : ',') + . ' in the files the fixes could process'), + $left => $console->color('white/red', "FOUND $found"), + default => $console->color('white/green', "OK $found"), + }); + } + + return match (true) { + $unprocessed !== [] => 2, + $left => 1, + default => 0, + }; + } + + + #[Cli\Command('Say where the saved plan stands and what a run keeps to go back, running no fix')] + public function status( + ParseResult $args, + #[Cli\Option('Output format: `console`, or `json` for a tool or an AI agent', alias: '-f', enum: ['console', 'json'])] + ?string $format, + ConfigOptions $configuration, + ): int + { + $project = $this->loadProject($args, $configuration); + $console = $this->findConsole($format); + $plan = PlanFile::read($project->root); + $printer = new StatusPrinter($plan, PlanStatus::read($plan, $project)); + if ($console === null) { + $this->writeJson($project, $printer->toArray(), saved: true); + } else { + self::writeHeader($console, $project); + $console->write($printer->print($console)); + } + + return 0; + } + + + #[Cli\Command('Rewrite the old API for the versions `composer.json` requires now, keeping the style of the project')] + public function today(ParseResult $args, TodayOptions $options, ConfigOptions $configuration): int + { + $run = $options->toRunOptions(); + // a worker runs with what its parent installed, and what is installed, plugins among it, loads in a new process + if ( + $run->worker === null + && new DataPackageOffer($this->context)->install($args, $configuration, (bool) $options->yes, $this->mayAsk($options->format)) + ) { + $exit = $this->context->rerun(array_values(array_filter(array_slice($_SERVER['argv'], 1), is_string(...)))); + if ($exit === null) { + $this->context->err->writeLine('The upgrading data are installed; run the command again, which loads them.'); + } + + return $exit ?? 4; + } + + return $this->executor->run( + $args, + $configuration, + $run, + new CheckOptions(maxWarnings: $options->maxWarnings, fixRisky: $options->fixRisky, only: $options->only), + fix: true, + askRisky: (bool) $options->askRisky, + upgrade: new TodayUpgrade($this->context, (bool) $options->modernize, $options->only), + ); + } + + + /** Measures what upgrading to the targets changes, changing nothing. */ + private function measure( + ParseResult $args, + Project $project, + ?string $target, + ?string $version, + bool $types, + EstimateOptions $options, + ConfigOptions $configuration, + ?Console $console, + bool $library = false, + ): Estimate + { + $estimator = new Estimator( + $project, + $types, + (bool) $options->offline, + createWorkers: fn(UpgradeCheck $check, int $files) => $this->createEstimateWorkers( + $configuration, + $check, + $options->jobs ?? WorkerPool::countDefaultJobs($files), + $project->getCacheDir(), + ), + onProgress: $console === null + ? null + : fn(string $what) => $console->setStatus(Markup::formatLabel($console, 'Measuring') . "$what\u{2026}"), + library: $library, + ); + $targets = $this->resolveTargets($args, $target, $version, $estimator); + if ($console !== null) { + self::writeHeader($console, $project); + } + + try { + return $estimator->estimate($targets, array_map($this->context->resolvePath(...), $options->paths)); + } finally { + $console?->clearStatus(); + } + } + + + /** + * Measures what upgrading to the targets changes and orders it into the steps of an upgrade, of a library or of an + * application, which it says with why. + * @return array{Estimate, Plan, string} + */ + private function makePlan( + ParseResult $args, + Project $project, + ?string $target, + ?string $version, + bool $types, + EstimateOptions $options, + PlanOptions $planning, + ConfigOptions $configuration, + ?Console $console, + ): array + { + // a library moves no installed package, which the estimate would otherwise ask Composer about + [$library, $why] = $planning->library === null + ? $this->decideLibrary($this->mayAsk($options->format), $project) + : [$planning->library, 'as `--' . ($planning->library ? '' : 'no-') . 'library` says']; + $estimate = $this->measure($args, $project, $target, $version, $types, $options, $configuration, $console, $library); + if ($estimate->targets === []) { // a project on PHP 7 is offered none + throw new UsageException( + 'There is no version to plan an upgrade to; name one, as `php 8.4` or `vendor/name 4.0`.', + $args->command, + ); + } + + $plan = new PlanBuilder(ProjectPackages::read($project->root)) + ->build($estimate, $planning->testCommand, $planning->quickTestCommand); + return [$estimate, $plan, ($library ? 'library, ' : 'application, ') . $why]; + } + + + /** + * Saves the plan, which forgets what the runs of the one before kept, refusing to forget the files of a step a run left + * unfinished unless told to discard them; a plan of no step is no file, which nothing would run. + * @throws UsageException + */ + private function savePlan(ParseResult $args, Plan $plan, Project $project, bool $discard, ?Console $console): void + { + if ($plan->steps === []) { + $console?->writeLine(Markup::formatLine($console, 'Saved', 'nothing, as the upgrade has no step to make')); + return; + } + + $state = new RunState($project); + $state->runExclusively(function () use ($state, $discard, $args, $plan, $project) { + $interrupted = $state->snapshots->findInterrupted(); + if ($interrupted !== [] && !$discard) { + $files = array_merge(...array_values($interrupted)); + throw new UsageException( + 'Step ' . array_key_first($interrupted) . ' of a run did not finish' + . ($files === [] ? '' : ' and may have rewritten ' . implode(', ', $files)) + . '; saving a plan forgets what it kept, so put the files back with `dresscode upgrade abort` first, or pass `--discard`.', + $args->command, + ); + } + + PlanFile::write($plan, $project->root); + $state->remove(); + }); + $console?->writeLine(Markup::formatLine($console, 'Saved', PlanFile::Name)); + } + + + /** + * The runner of the plan, telling its progress on the status line of the console, which data have none. + * @throws ConfigurationException for a project without a configuration file + */ + private function createPlanRunner(Project $project, bool $types, bool $commit, ?Console $console): PlanRunner + { + $console ??= $this->context->err; + return new PlanRunner( + $project, + $types, + $commit, + fn(string $what) => $console->setStatus(Markup::formatLabel($console, 'Upgrading') . "$what\u{2026}"), + ); + } + + + /** + * Runs the plan over the working tree and says how far it got, as text on the console or, without one, as a document + * of data whose warnings go to standard error, with the exit code of the outcome. After a raise it goes on in a new + * process, `$rerun` its command line, which tells how far the whole run got; a run going on after a raise + * says nothing of what the run before it said, and hands back where it stopped instead. + * @param list $rerun + */ + private function runPlan( + Plan $plan, + PlanRunner $runner, + PlanRunOptions $running, + bool $mayAsk, + ?Console $output, + array $rerun, + RunHandoff $handoff, + ): int + { + $console = $output ?? $this->context->err; + if ($handoff->resumed === null) { // what the run before the raise said already + $this->warnBeforeRun($plan, $runner, (bool) $running->commit, $console); + } + + // without a terminal only `--yes` agrees, so without it Composer is not even asked what a raise changes + $approve = $running->yes || $mayAsk ? new RaiseApproval($this->context, $console, (bool) $running->yes)->approve(...) : null; + try { + $outcome = $runner->run($plan, $running->step, $approve, (bool) $running->discard, $handoff->resumed); + } finally { + $console->clearStatus(); + } + + if ($outcome->stop === RunStop::Raised && $handoff->resumed !== null) { + $handoff->handBack($outcome); + return 0; + } elseif ($outcome->stop === RunStop::Raised && ($exit = RunHandoff::goOn($this->context, $outcome, $plan, $rerun)) !== null) { + return $exit; + } + + $printer = new RunOutcomePrinter($plan, $outcome, $running->step, $runner->project->root); + if ($output !== null) { + $output->write($printer->print($output)); + } else { + $this->writeJson($runner->project, [ + 'version' => RunOutcomePrinter::Version, + 'plan' => new PlanPrinter($plan)->toArray(), + 'outcome' => $printer->toArray(), + ], saved: true); + } + + return $outcome->getExitCode(); + } + + + private function warnBeforeRun(Plan $plan, PlanRunner $runner, bool $commit, Console $console): void + { + if (!$plan->isMadeWith(Provenance::current(ProjectPackages::read($runner->project->root)))) { + $console->writeLine(Markup::formatLine( + $console, + 'Warning', + 'The plan was made with other versions of DressCode or of the upgrading data', + ', so a step may fix more or less than it did then.', + )); + } + + if ($plan->unestimated !== [] || $plan->missingData !== []) { + $console->writeLine(Markup::formatLine( + $console, + 'Warning', + 'The estimate of the plan ' . implode(' and ', array_filter([ + $plan->unestimated === [] ? '' : 'could not process ' . implode(', ', $plan->unestimated), + $plan->missingData === [] ? '' : 'lacked the upgrading data of ' . implode(', ', array_keys($plan->missingData)), + ])), + '; the run checks the whole code against the targets at its end.', + )); + } + + if (!$runner->state->durable) { + $console->writeLine(Markup::formatLine( + $console, + 'Warning', + 'Git finds no repository of the project', + ', so what a run keeps to go back lies in the cache directory, which clearing the cache loses.', + )); + } + + if (!$commit && $runner->hasOwnChanges()) { + $console->writeLine(Markup::formatLine( + $console, + 'Warning', + 'The working tree has changes of its own', + ', which the changes of the upgrade mix with.', + )); + } + } + + + /** @param array $data */ + private function writeJson(Project $project, array $data, bool $saved = false): void + { + $data = [ + 'version' => $data['version'], + 'root' => $project->root, + ...$saved ? ['planIdentity' => PlanFile::identify($project->root)] : [], + ...$data, + ]; + $this->context->writeJson($data); + } + + + /** The name of the tool and the configuration the command measures or runs with. */ + private static function writeHeader(Console $console, Project $project): void + { + $console->writeLine(CommandContext::formatName($console)); + $console->writeLine($project->configFile === null + ? Markup::formatLine($console, 'Config', 'none', ', the scope `init` would write: ' . implode(', ', $project->config->paths)) + : Markup::formatLine($console, 'Config', FileSystem::platformSlashes($project->configFile))); + } + + + /** The console the format writes text to; null for data. */ + private function findConsole(?string $format): ?Console + { + return ($format ?? 'console') === 'console' ? $this->context->out : null; + } + + + /** Whether the command may ask the user: in a terminal, writing text for a human rather than data for a tool. */ + private function mayAsk(?string $format): bool + { + return ($format ?? 'console') === 'console' && $this->context->prompt->isInteractive(); + } + + + /** + * The project of the command: its configuration, or the scope `init` would write where it has no file of its own. + * @throws ConfigurationException for a directory that is no project at all + */ + private function loadProject(ParseResult $args, ConfigOptions $configuration): Project + { + ['config' => $config, 'root' => $root, 'file' => $file, 'commandLine' => $commandLine] + = $this->context->loadConfig($args, $configuration, new Config(paths: ['.'])); + return Project::fromConfig($config, $root, $file, $commandLine); + } + + + /** + * The versions to measure the upgrade to: the package and the version named, PHP to the version named or to the + * newest its data know, and without a target what the estimator proposes. + * @return list + * @throws UsageException + */ + private function resolveTargets(ParseResult $args, ?string $target, ?string $version, Estimator $estimator): array + { + return match (true) { + $version !== null && !Versions::isVersion($version) + => throw new UsageException("The version to upgrade to is written as `8.4` or `4.0`, `$version` given.", $args->command), + $target === null => $estimator->proposeTargets(), + $target === PackageDiscovery::Php => $version === null ? $estimator->proposeTargets(phpOnly: true) : [Target::php($version)], + !Target::isPackageName($target) + => throw new UsageException("The target is `php` or a package as `vendor/name`, `$target` given.", $args->command), + $version === null => throw new UsageException("Name the version of `$target` to upgrade to, as `$target 4.0`.", $args->command), + default => [new Target($target, $version)], + }; + } + + + /** + * Whether the plan is the one of a library, which widens its constraints, where no option says, and why: by the `type` + * of the project and the lock it has none of, and for a library with a lock of its own in a terminal as the user + * answers, otherwise as Enter does: a library where the `type` is written, the application the lock makes it where not. + * @return array{bool, string} + */ + private function decideLibrary(bool $mayAsk, Project $project): array + { + $packages = ProjectPackages::read($project->root); + $type = $packages->findType(); + $typeGiven = $packages->rootPath !== null && isset(Config\ComposerJson::read("$packages->rootPath/composer.json")['type']); + $typed = $typeGiven + ? "`composer.json` gives the type `$type`" + : '`composer.json` gives no type, which Composer reads as `library`'; + return match ($packages->isLibrary()) { + Tristate::Yes => [true, is_file("$packages->rootPath/composer.lock") + ? "$typed, and its git ignores `composer.lock`" + : "$typed, and there is no `composer.lock`"], + Tristate::No => [false, $typed], + Tristate::Maybe => match (true) { + $mayAsk => [$this->context->prompt->choose( + Markup::formatQuestion( + $this->context->out, + 'Plan it as a library, which widens its constraints to the targets instead of raising them?', + "$typed, yet the project has a `composer.lock` of its own.", + ), + ['y', 'n'], + $typeGiven ? 'y' : 'n', + ) === 'y', 'as you answered'], + $typeGiven => [ + true, + "$typed, though the project has a `composer.lock` of its own; `--no-library` plans it as an application", + ], + default => [ + false, + "$typed, yet the project has a `composer.lock` of its own, as an application has; `--library` plans it as a library", + ], + }, + }; + } + + + /** + * Whether the upgrade goes with the types of the code: as `--types` says, as the configuration says, else in a + * terminal as the user answers, and otherwise without them. + * @throws ConfigurationException for the types asked for without PHPStan beside DressCode + */ + private function decideTypes(?bool $types, bool $mayAsk, Config $config): bool + { + $available = Analyses\PhpStan::isAvailable(); + if ($types === true && !$available) { + throw new ConfigurationException( + '`--types` asks for the types of the code, but `phpstan/phpstan` is not installed beside DressCode.', + docs: 'types#enable', + ); + } elseif ($types !== null) { + return $types; + } elseif ($config->typeAnalysis !== null || !$available) { + return $available; + } + + return $mayAsk + && $this->context->prompt->choose( + Markup::formatQuestion( + $this->context->out, + 'Measure with the types of the code?', + 'From PHPStan with the configuration of the project where it has one, they decide most of what a fix of a call needs to know.', + ), + ['y', 'n'], + 'y', + ) === 'y'; + } + + + /** + * The workers repeating the check of the estimate, `upgrade estimate` reading it from a file in the cache directory; + * null for one job, or where there is no PHP to start one with. + */ + private function createEstimateWorkers(ConfigOptions $configuration, UpgradeCheck $check, int $jobs, string $cacheDir): ?WorkerPool + { + $php = WorkerPool::buildPhpCommand(); + if ($jobs < 2 || $php === null) { + return null; + } + + $file = "$cacheDir/upgrade/estimate-" . bin2hex(random_bytes(8)) . '.json'; + $check->write($file); + register_shutdown_function(fn() => @unlink($file)); // @ a worker may hold it still + + $command = [...$php, $this->context->scriptFile, 'upgrade', 'estimate', '--no-color', "--check-file=$file"]; + foreach (['--config' => (array) $configuration->config, '--root' => (array) $configuration->root] as $option => $values) { + foreach ($values as $value) { + $command[] = "$option=$value"; + } + } + + return new WorkerPool($command, $jobs, $this->context->workingDirectory, warmFirst: $check->layer->typeAnalysis !== null); + } + + + /** The run of a worker of the estimate: the check repeated as the parent wrote it, the files coming over the connection. */ + private function runEstimateWorker(ParseResult $args, string $address, string $file, ConfigOptions $configuration): int + { + ['config' => $config, 'root' => $root] = $this->context->loadConfig($args, $configuration, new Config(paths: ['.'])); + [$factory, $resolution] = UpgradeCheck::read($file)->resolve($config, $root); + $runner = $factory->createRunner($resolution, cache: false); + ($runner->warmUp)?->__invoke(); // before connecting, which is what starts the other workers + return Worker::run($address, $runner, fix: false); + } +} diff --git a/src/Console/EstimatePrinter.php b/src/Console/EstimatePrinter.php new file mode 100644 index 0000000000..4a906d3d7f --- /dev/null +++ b/src/Console/EstimatePrinter.php @@ -0,0 +1,301 @@ + ['deprecations', 'cleanup'], 'May modernize' => ['modernizations']]; + + /** what the run can do about a finding, as the output says it */ + private const FixabilityWords = [ + 'automatic' => 'fixed by DressCode', + 'typeUnknown' => 'waiting for the types', + 'nameUncertain' => 'waiting for certain names', + 'manual' => 'left to you', + ]; + + + public function __construct( + private Estimate $estimate, + ) { + } + + + /** @param bool $passive no step of the run follows that would change the code */ + public function print(Console $console, bool $passive = true): string + { + $estimate = $this->estimate; + $targets = implode(', ', array_map(fn(Target $target) => $target->format(), $estimate->targets)); + $out = Markup::formatLine( + $console, + 'Upgrade', + "$targets over " . Helpers::formatCount($estimate->files, 'file'), + ($estimate->namesMeasured ? ', the names resolved for certain as measured' : '') + . ($estimate->types ? '' : ', without the types of the code') + . ($passive ? ', an estimate: nothing was changed' : ''), + ) . "\n\n"; + + $width = max([0, ...array_map(fn(Topic $topic) => strlen($topic->name), $estimate->topics)]); + foreach (self::Groups as $title => $sets) { + $topics = array_values(array_filter($estimate->topics, fn(Topic $topic) => in_array($topic->set, $sets, true))); + if ($topics === []) { + continue; + } + + $places = array_sum(array_map(fn(Topic $topic) => $topic->countPlaces(), $topics)); + $automatic = array_all( + $topics, + fn(Topic $topic) => array_keys(array_filter($topic->places)) === [Fixability::Automatic->value], + ); + $out .= $console->color('white', $title) . ', ' . Helpers::formatCount($places, 'finding') + . ($automatic ? ', all fixed by DressCode' : '') . "\n"; + foreach ($topics as $topic) { + $out .= sprintf( + " %s %s %s, %s\n", + str_pad($topic->name, $width), + str_pad( + Helpers::formatCount($topic->countPlaces(), 'finding') . ' in ' . Helpers::formatCount($topic->files, 'file'), + 24, + ), + self::formatPlaces($topic), + $console->color(...match ($topic->phase) { + Phase::Bridge => ['green', $topic->constraint === null ? 'already today' : "already on $topic->constraint"], + Phase::Jump => ['yellow', $topic->constraint === null ? 'after the raise' : "once $topic->constraint is installed"], + }), + ); + } + + $out .= "\n"; + } + + if ($estimate->topics === []) { + $out .= $estimate->isComplete() + ? "Nothing to upgrade: no rule and no upgrading data find anything for the targets.\n\n" + : "Nothing found for the targets in what the check could read, which the lines below say is not all.\n\n"; + } + + $today = array_sum(array_map( + fn(Topic $topic) => $topic->countPlaces(Fixability::Automatic), + $estimate->findTopics(Phase::Bridge, 'deprecations'), + )); + if ($today > 0) { + $out .= Markup::formatLine( + $console, + 'Right now', + "`dresscode upgrade today` can rewrite $today of these", + ', on the versions you have', + ) . "\n"; + } + + if (!$estimate->blindSpots->isEmpty()) { + $out .= Markup::formatLine($console, "Can't see", $this->formatBlindSpots()) . "\n"; + } + + if ($estimate->unprocessed !== []) { + $out .= Markup::formatLine( + $console, + 'Unverified', + Helpers::formatCount(count($estimate->unprocessed), 'file') . ' the check could not process', + ', whose findings are not counted', + ': ' . self::formatList(array_keys($estimate->unprocessed)), + ) . "\n"; + } + + foreach ($estimate->blockers as $blockers) { + $out .= Markup::formatLine($console, 'Composer', $blockers->target->format() . ': ' . self::formatBlockers($blockers)) . "\n"; + } + + $major = $estimate->moves?->findMajor() ?? []; + $moves = match (true) { + $estimate->library => 'nothing, a library widens its constraints with `--no-update`', + $estimate->moves?->unknown !== null => "unknown, {$estimate->moves->unknown}", + $major !== [] => self::wrapList(array_map( + fn(Move $move) => "`$move->package` $move->from => $move->to" + . match (true) { + $move->isKnown($estimate->knownVersions) => '', + $move->isSeriesKnown($estimate->knownVersions) => " (data up to {$estimate->knownVersions[$move->package]})", + default => ' (no data)', + }, + $major, + )), + default => null, + }; + if ($moves !== null) { + $out .= Markup::formatLine($console, 'Versions', $moves) . "\n"; + } + + foreach ($estimate->missingData as $package => $libraries) { + $out .= Markup::formatLine( + $console, + 'No data', + self::formatList(array_map(fn(string $library) => "`$library`", $libraries)), + ": the upgrading data are in `$package`, which `dresscode upgrade today` offers to install, with `--yes` without asking", + ) . "\n"; + } + + $out .= Markup::formatLine($console, 'Rules for', self::wrapList(array_map( + fn(string $library, string $version) => "`$library` up to $version", + array_keys($estimate->knownVersions), + $estimate->knownVersions, + )) ?: 'no upgrading data reach the project') . "\n"; + foreach ($estimate->warnings as $warning) { + $out .= "\n" . Markup::highlightCode($console, "Warning: $warning", 'yellow'); + } + + return $out . ($estimate->warnings === [] ? '' : "\n"); + } + + + /** + * The estimate as the data the format `json` writes. + * @return array + */ + public function toArray(): array + { + $estimate = $this->estimate; + return [ + 'version' => self::Version, + 'targets' => array_map(fn(Target $target) => (array) $target, $estimate->targets), + 'files' => $estimate->files, + 'namesMeasured' => $estimate->namesMeasured, + 'types' => $estimate->types, + 'topics' => array_map(fn(Topic $topic) => [ + 'name' => $topic->name, + 'set' => $topic->set, + 'phase' => $topic->phase->value, + 'constraint' => $topic->constraint, + 'files' => $topic->files, + 'findings' => ['total' => $topic->countPlaces(), ...$topic->places], + ], $estimate->topics), + 'blindSpots' => [...(array) $estimate->blindSpots, 'otherFiles' => (object) $estimate->blindSpots->otherFiles], + 'blockers' => array_map(fn(Blockers $blockers) => [ + 'target' => (array) $blockers->target, + 'packages' => array_map(fn(Blocker $blocker) => (array) $blocker, $blockers->packages), + 'unknown' => $blockers->unknown, + ], $estimate->blockers), + 'moves' => $estimate->moves === null ? null : [ + 'packages' => array_map(fn(Move $move) => [ + ...(array) $move, + 'major' => $move->isMajor(), + 'data' => $move->isKnown($estimate->knownVersions), + 'dataUpTo' => $estimate->knownVersions[$move->package] ?? null, + ], $estimate->moves->packages), + 'unknown' => $estimate->moves->unknown, + ], + 'library' => $estimate->library, + 'unverified' => TasksPrinter::listUnverified($estimate->unprocessed), + 'missingData' => (object) $estimate->missingData, + 'knownVersions' => (object) $estimate->knownVersions, + 'warnings' => $estimate->warnings, + ]; + } + + + /** What becomes of the findings of the topic: all fixed by DressCode, or the count of each. */ + private static function formatPlaces(Topic $topic): string + { + $places = array_filter($topic->places); + return array_keys($places) === [Fixability::Automatic->value] + ? self::FixabilityWords[Fixability::Automatic->value] + : implode(', ', array_map( + fn(string $fixability, int $count) => "$count " . self::FixabilityWords[$fixability], + array_keys($places), + $places, + )); + } + + + /** What the upgrade does not see, each kind of it counted. */ + private function formatBlindSpots(): string + { + $spots = $this->estimate->blindSpots; + return implode('; ', array_filter([ + $spots->classNameStrings + ? Helpers::formatCount($spots->classNameStrings, 'string') . ' naming a class the data rename or forbid' + : null, + $spots->dynamicAccesses ? Helpers::formatCount($spots->dynamicAccesses, 'place') . ' reached by a computed name' : null, + $spots->otherFiles + ? implode(', ', array_map( + fn(string $extension, int $count) => Helpers::formatCount($count, ".$extension file"), + array_keys($spots->otherFiles), + $spots->otherFiles, + )) . ', which no rule reads' + : null, + $spots->generatedFiles ? Helpers::formatCount($spots->generatedFiles, 'generated file') . ', left out' : null, + ])); + } + + + /** The packages refusing the target, or why nothing is known of them. */ + public static function formatBlockers(Blockers $blockers): string + { + return match (true) { + $blockers->unknown !== null => "unknown, $blockers->unknown", + $blockers->packages === [] => 'nothing in the lock refuses it', + default => 'refused by ' . self::formatList(array_map( + fn(Blocker $blocker) => "$blocker->package $blocker->version ($blocker->constraint)", + $blockers->packages, + )), + }; + } + + + /** + * The first names of the list, the rest counted. + * @param list $names + */ + private static function formatList(array $names): string + { + return implode(', ', array_slice($names, 0, self::ListedNames)) + . (count($names) > self::ListedNames ? ' and ' . (count($names) - self::ListedNames) . ' more' : ''); + } + + + /** + * The items separated by commas, broken onto lines that keep the width of the output, each under the value. + * @param list $items + */ + private static function wrapList(array $items): string + { + $lines = []; + $line = ''; + foreach ($items as $i => $item) { + $item .= $i < count($items) - 1 ? ',' : ''; + if ($line !== '' && strlen("$line $item") > self::Width - Markup::LabelWidth) { + $lines[] = $line; + $line = $item; + } else { + $line = $line === '' ? $item : "$line $item"; + } + } + + return implode("\n" . str_repeat(' ', Markup::LabelWidth), [...$lines, $line]); + } +} diff --git a/src/Console/Markup.php b/src/Console/Markup.php index dd3aa47924..7fc1827d3b 100644 --- a/src/Console/Markup.php +++ b/src/Console/Markup.php @@ -21,7 +21,7 @@ final class Markup { /** the width of the label a line of the output opens with */ - private const LabelWidth = 11; + public const LabelWidth = 11; private const DocsUrl = 'https://dresscode.run/'; diff --git a/src/Console/PlanPrinter.php b/src/Console/PlanPrinter.php new file mode 100644 index 0000000000..5c2134645d --- /dev/null +++ b/src/Console/PlanPrinter.php @@ -0,0 +1,104 @@ +mode === null ? '' : Markup::formatLine($console, 'Mode', $this->mode) . "\n") + . Markup::formatLine( + $console, + 'Plan', + implode(', ', array_map(fn(Target $target) => $target->format(), $this->plan->targets)) + . ($this->plan->paths === [] ? '' : ' over ' . implode(', ', $this->plan->paths)), + ) + . "\n"; + $width = max([0, ...array_map(fn(Step $step) => strlen($step->title), $this->plan->steps)]); + foreach ($this->plan->steps as $index => $step) { + $out .= rtrim(sprintf( + ' %2d %s %s %s', + $index + 1, + $console->color(...match (true) { + $step->skip => ['gray', 'skipped '], + $step instanceof ManualStep => ['yellow', 'manual '], + $step instanceof DependencyStep => ['white', 'composer'], + default => ['green', 'fix '], + }), + str_pad($step->title, $width), + match (true) { + $step instanceof FixStep => implode(', ', $step->topics), + $step instanceof ManualStep => $step->formatCommand(), + default => '', + }, + )) . "\n"; + } + + $test = $this->plan->testCommand; + $quick = $this->plan->quickTestCommand; + return $out . Markup::formatLine($console, 'Tests', match (true) { + $test === null && $quick === null => 'not run, no `--test-command` given', + $test === null || $quick === null => Violation::formatCode($test ?? $quick) . ' after every step', + default => Violation::formatCode($quick) + . ' after every step, ' + . Violation::formatCode($test) + . ' after a raise and the last one', + }) . "\n"; + } + + + /** + * The plan as the data the format `json` writes. + * @return array + */ + public function toArray(): array + { + return [ + 'version' => self::Version, + 'targets' => array_map(fn(Target $target) => (array) $target, $this->plan->targets), + 'steps' => array_map(fn(Step $step) => [ + ...PlanFile::encodeStep($step), + 'commands' => match (true) { + $step instanceof DependencyStep => $step->formatCommands(), + $step instanceof ManualStep => [$step->formatCommand()], + default => [], + }, + 'skip' => $step->skip, + ], $this->plan->steps), + 'toolVersion' => $this->plan->toolVersion, + 'dataVersions' => (object) $this->plan->dataVersions, + 'testCommand' => $this->plan->testCommand, + 'quickTestCommand' => $this->plan->quickTestCommand, + 'paths' => $this->plan->paths, + 'unverified' => $this->plan->unestimated, + 'missingData' => (object) $this->plan->missingData, + ]; + } +} diff --git a/src/Console/RiskReview.php b/src/Console/RiskReview.php index 264242e55e..f829c3caab 100644 --- a/src/Console/RiskReview.php +++ b/src/Console/RiskReview.php @@ -42,7 +42,7 @@ public function __construct( public function review(RunResult $result): int { foreach ($result->files as $file) { - if (array_filter($file->remaining, fn(Violation $v) => $v->refused) && !$this->reviewFile($file)) { + if ($file->remaining->countRefused() > 0 && !$this->reviewFile($file)) { break; } } diff --git a/src/Console/RunExecutor.php b/src/Console/RunExecutor.php new file mode 100644 index 0000000000..697d9b30d9 --- /dev/null +++ b/src/Console/RunExecutor.php @@ -0,0 +1,598 @@ +stdin !== null; + foreach ([ + '--format' => $run->format, + '--diff' => $check?->diff, + '--max-warnings' => $check?->maxWarnings, + '--ask-risky' => $askRisky ?: null, + '--lines' => $check?->lines ?: null, + '--before' => $check?->before, + ] as $option => $value) { + if ($formatter && $value !== null) { + throw new UsageException( + "`fix --stdin` writes the fixed code alone, so it takes no `$option`; `check --stdin` reports on the code in any format.", + $args->command, + ); + } + } + + [$factory, $resolution, $configFile] = $upgrade === null + ? $this->context->resolveProject($args, $configuration, $check->only ?? []) + : $upgrade->resolve($args, $configuration); + [$config, $root] = [$resolution->config, $resolution->root]; + $profiler = $run->profile === null ? null : new Profiler; + $fixRisky = in_array(true, $check->fixRisky ?? [], true); // a bare `--fix-risky`, the names given go to the configuration + if ($run->worker !== null) { // the parent keeps the cache; the baseline decides what is reported + $runner = $factory->createRunner( + $resolution, + strict: (bool) $run->strictRules, + cache: false, + fixRisky: $fixRisky, + baseline: !$generate, + profiler: $profiler, + ); + ($runner->warmUp)?->__invoke(); // before connecting, which is what starts the other workers + return Worker::run($run->worker, $runner, $fix, $profiler); + } + + $options = [ + 'strict' => (bool) $run->strictRules, + // a file served from the cache has nothing to measure, and its counts are those the baseline left + 'cache' => !$generate && !$profiler, + 'configFile' => $configFile, + 'fixRisky' => $fixRisky, + 'baseline' => !$generate, + 'profiler' => $profiler, + 'refreshCache' => (bool) $run->noCache, + ]; + $runner = $factory->createRunner($resolution, ...$options); + [$out, $err] = [$this->context->out, $this->context->err]; + $format = self::resolveFormat($run->format, detect: true); + // only the parent warns, a worker has returned above; an agent can do nothing about the configuration + foreach ($formatter || $format === 'agent' ? [] : $resolution->warnings as $warning => $docs) { + $err->writeLine(Markup::highlightCode($err, "Warning: $warning", 'yellow')); + if ($docs !== null) { + $err->writeLine(Markup::formatDocsLink($err, $docs)); + } + } + + $stdinPath = $check?->stdin; + $paths = array_values(array_unique(array_map($this->context->resolvePath(...), $run->paths))); + $maxWarnings = $check?->maxWarnings; + if ($askRisky && ($check?->fixRisky || is_string($stdinPath))) { + throw new UsageException( + '`--ask-risky` asks about the risky fixes one by one, so it goes with neither `--fix-risky` nor `--stdin`.', + $args->command, + ); + } elseif ($askRisky && ($format !== 'console' || !$this->context->prompt->isInteractive())) { + throw new UsageException( + '`--ask-risky` asks in an interactive terminal; without one, allow the risky fixes with `--fix-risky=`.', + $args->command, + ); + } + + $lines = $check?->lines ? new LineRanges($check->lines) : null; + $before = $check?->before; + if ($lines && $format !== 'agent') { + throw new UsageException('`--lines` narrows what the `agent` format reports, so it goes with no other format.', $args->command); + } elseif ($before !== null && ($format !== 'agent' || is_string($stdinPath))) { + throw new UsageException( + '`--before` tells the `agent` format what an edit of a file did, so it goes with no other format and no `--stdin`.', + $args->command, + ); + } elseif ($lines && $run->strictRules) { + throw new UsageException( + '`--lines` names the lines of the file as it was read, which `--strict-rules` reads again in every round.', + $args->command, + ); + } + + if (is_string($stdinPath)) { + if ($paths) { + throw new UsageException('Paths cannot be combined with `--stdin`.', $args->command); + } + + return $formatter + ? $this->runFormatter($runner, $stdinPath, (bool) $run->skipExcluded, $config->paths) + : $this->runStdin( + self::resolveFormat($run->format, detect: false), // the caller of stdin is an editor or a hook waiting for the format it asked for + (bool) $check->diff, + $runner, + $factory->registry, + $resolution, + $stdinPath, + $maxWarnings, + (bool) $run->skipExcluded, + $config->paths, + $lines, + ); + } + + $scope = $paths ? $runner->files->narrowPaths($paths, $config->paths) : $config->paths; + if (!$scope) { + throw new UsageException('No paths given and none configured.', $args->command); + } + + // the machine-readable formats must not be prefaced, and a generated baseline is not a report + $preface = !$generate && in_array($format, ['console', 'github'], true); + if ($preface) { + if ($this->context->xdebug) { + $err->writeLine('Warning: Xdebug is loaded and makes the run many times slower.', 'red'); + } + + $this->context->writeHeader($configFile, $resolution, Baseline::findFile($config, $root)); + $upgrade?->writePreface($resolution); + + $out->setStatus(Markup::formatLabel($out, $fix ? 'Fixing' : 'Checking') . 'looking for files…'); + } + + try { + $files = $runner->files->findFiles($scope, skipExcluded: (bool) $run->skipExcluded, configured: $config->paths); + } finally { + $out->clearStatus(); + } + + $files = $upgrade?->leaveOutGenerated($files, $root, $preface) ?? $files; + if ($preface) { + $this->writeScope(files: $files, paths: $scope, root: $root, fix: $fix, narrowed: $paths && $scope !== $paths); + } + + if (($lines || $before !== null) && count($files) > 1) { + throw new UsageException( + ($lines ? '`--lines` names the lines of one file' : '`--before` names the text of one file') + . ', but ' . count($files) . ' files are to be run.', + $args->command, + ); + } elseif ($before !== null && $files) { + $code = @file_get_contents($this->context->resolvePath($before)); // @ the failure is said below + if ($code === false) { + throw new UsageException("Cannot read file `$before`, which `--before` names.", $args->command); + } + + $left = $this->findBrokenDecisions($runner, $files[0], $code); + $runner = $factory->createRunner($resolution, ...$options, leftAsWritten: $left); + $lines = new LineRanges($check->lines, array_fill_keys($left, true)); + } + + $jobs = $run->jobs ?? WorkerPool::countDefaultJobs(count($files)); + $command = $jobs > 1 && $files + ? $this->buildWorkerCommand($args, $configuration, $run, $check, $upgrade?->getWorkerOptions($resolution) ?? []) + : null; + $workers = $command + ? new WorkerPool($command, $jobs, $this->context->workingDirectory, profiler: $profiler, warmFirst: $runner->warmUp !== null) + : null; + $progress = !$generate && $format === 'console' && count($files) > 1 && $out->isTerminal() + ? new ProgressBar($out, count($files)) + : null; + $onProgress = $progress === null ? null : $progress->advance(...); + + $profiler?->addPhase('start of the process', (int) ((microtime(as_float: true) - $_SERVER['REQUEST_TIME_FLOAT']) * 1e9)); + $start = hrtime(as_number: true); + try { + if ($generate) { + return $this->generateBaseline($runner, $config, $root, $configFile, $files, $workers, $format); + } + + $reporter = $this->createReporter( + (bool) $check?->diff, + $out, + $this->context->stdout, + $root, + $format, + $factory->registry, + $runner, + $resolution, + $run->paths, + $upgrade === null ? 'fix' : TodayUpgrade::Command, + ); + $result = $runner->run($files, $fix, $reporter, $workers, $onProgress, $maxWarnings, $lines); + if ($upgrade !== null && $preface && $result->countChangedFiles()) { + $out->writeLine('Run `dresscode ' . TodayUpgrade::Command . '` again: the code it rewrote may hold more to upgrade.'); + } + + return $askRisky + ? $this->review($runner, $result, $files, $root, $maxWarnings, $factory->registry) + : $result->getExitCode(); + + } finally { + $progress?->clear(); // an error must not be written into the bar + if ($profiler && $run->profile !== null) { + $profiler->addPhase('run', hrtime(as_number: true) - $start); + FileSystem::write( + $this->context->resolvePath($run->profile), + json_encode($profiler->toArray(), JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR) . "\n", + ); + } + } + } + + + /** + * The decisions the file as it was before an edit broke, which the run then leaves as the file writes them. + * @return list + */ + private function findBrokenDecisions(Runner $runner, string $file, string $code): array + { + if ($runner->isKnownClean($file, $code)) { // the text the previous fix of the file wrote, most often + return []; + } + + $decisions = array_column($runner->processCode($file, $code)->violations, 'decision'); + return array_values(array_unique($decisions)); + } + + + /** + * Reports on the code read from stdin as if it were the file at the path; nothing of a path the excluded ones leave + * out where the caller asks to skip it. + * @param list $configured + */ + private function runStdin( + string $format, + bool $diff, + Runner $runner, + PluginRegistry $registry, + ResolvedProject $resolution, + string $path, + ?int $maxWarnings, + bool $skipExcluded, + array $configured, + ?LineRanges $lines, + ): int + { + $reporter = $this->createReporter( + $diff, + $this->context->out, + $this->context->stdout, + $resolution->root, + $format, + $registry, + $runner, + $resolution, + [$path], + ); + $code = (string) stream_get_contents($this->context->stdin); + $absolute = $this->context->resolvePath($path); + $skipped = $skipExcluded && $runner->files->excludes($absolute, $configured); + $reporter->start($runner->createRunInfo(false, $skipped ? 0 : 1)); + $result = $skipped ? null : $runner->processPath($absolute, fix: false, code: $code); + $result = $result === null ? null : $lines?->select($result, fix: false) ?? $result; + if ($result) { + $reporter->reportFile($result); + } + + $run = new RunResult($result ? [FileSummary::of($result)] : [], fix: false, maxWarnings: $maxWarnings); + $reporter->finish($run); + return $run->getExitCode(); + } + + + /** + * Formats the code read from stdin as if it were the file at the path, for an editor: the whole fixed code goes to + * stdout with exit code 0, whatever it still violates; a syntax error or a failure leaves the code as it came, its + * one line on stderr, and so does a path the excluded ones leave out, without a word. + * @param list $configured + */ + private function runFormatter(Runner $runner, string $path, bool $skipExcluded, array $configured): int + { + $code = (string) stream_get_contents($this->context->stdin); + $path = $this->context->resolvePath($path); + $result = $skipExcluded && $runner->files->excludes($path, $configured) + ? null + : $runner->processPath($path, fix: false, code: $code); + [$output, $error, $exit] = match (true) { + $result?->syntaxError !== null => [$code, "$result->path:$result->syntaxErrorLine: Syntax error: $result->syntaxError", 1], + $result?->failure !== null => [$code, "$result->path: " . strtok($result->failure, "\n"), 2], + default => [$result->output ?? $code, null, 0], + }; + + if ($error !== null) { + fwrite($this->context->stderr, "$error\n"); + } + + return fwrite($this->context->stdout, $output) === strlen($output) ? $exit : 2; + } + + + /** + * Asks about the risky fixes the fix left and makes those accepted, then says how it ended; the exit code is that of + * the files as the review left them. + * @param list $files + */ + private function review(Runner $runner, RunResult $result, array $files, string $root, ?int $maxWarnings, PluginRegistry $registry): int + { + $out = $this->context->out; + if ($result->countRefused() === 0) { + $out->writeLine("\n" . $out->color($result->getExitCode() === 0 ? 'white/green' : 'white/red', 'REVIEWED no risky fixes to ask about')); + return $result->getExitCode(); + } + + $made = new RiskReview($runner, $out, $this->context->prompt, $root, $registry)->review($result); + $final = $runner->run($files, true, new Reporters\NullReporter, maxWarnings: $maxWarnings); + $left = $final->countRefused(); + $out->writeLine( + "\n" . $out->color( + $final->getExitCode() === 0 ? 'white/green' : 'white/red', + sprintf( + 'REVIEWED %s made, %s', + Helpers::formatCount($made, 'risky fix', 'risky fixes'), + $left ? "$left left" : 'none left', + ), + ), + ); + return $final->getExitCode(); + } + + + /** + * What the rules are applied to: the scope reaches wherever the configuration was found, + * not where the run was started. + * @param list $files relative to the root, or absolute when outside it + * @param list $paths they were found under these + * @param bool $narrowed a directory named on the command line was narrowed to the configured paths + */ + private function writeScope(array $files, array $paths, string $root, bool $fix, bool $narrowed): void + { + $out = $this->context->out; + $absolute = array_map(fn(string $file) => FileSystem::isAbsolute($file) ? $file : "$root/$file", $files); + $scope = count($files) === 1 + ? FileSystem::platformSlashes($absolute[0]) + : sprintf('%d files in %s', count($files), FileSystem::platformSlashes(self::findCommonDirectory($absolute) ?: $root)); + $out->write($files + ? Markup::formatLabel($out, $fix ? 'Fixing' : 'Checking') . $scope + . ($narrowed ? $out->color('gray', ', narrowed to the configured paths') : '') . "\n\n" + : $out->color('yellow', sprintf( + ($fix ? 'Nothing to fix' : 'Nothing to check') . ': no file in %s', + implode(', ', array_map(FileSystem::platformSlashes(...), $paths)), + )) . "\n"); + } + + + /** + * The directory all the files share; that is the scope the run really has. + * @param list $files + */ + private static function findCommonDirectory(array $files): string + { + $common = null; + foreach ($files as $file) { + $segments = explode('/', $file); + array_pop($segments); + if ($common === null) { + $common = $segments; + continue; + } + + $length = 0; + while (isset($common[$length], $segments[$length]) && $common[$length] === $segments[$length]) { + $length++; + } + + $common = array_slice($common, 0, $length); + } + + return implode('/', $common ?? []); + } + + + /** + * The command line of a worker: the same PHP, the same command and configuration; the paths come over the + * connection. Null where there is no PHP to start one with, and the run stays in the process. + * @param ?CheckOptions $check null for the baseline + * @param list $extra what the parent decided for the run beyond its command line + * @return ?list + */ + private function buildWorkerCommand( + ParseResult $args, + ConfigOptions $configuration, + RunOptions $run, + ?CheckOptions $check, + array $extra = [], + ): ?array + { + $php = WorkerPool::buildPhpCommand(); + if ($php === null) { + return null; + } + + $command = [ + ...$php, + $this->context->scriptFile, + ...explode(' ', $args->command->getFullName()), + '--no-color', + ...$extra, + ...$configuration->toArguments(), + ...array_map(fn(string $only) => "--only=$only", $check->only ?? []), + ]; + + if ($run->strictRules) { + $command[] = '--strict-rules'; + } + + foreach ($check->fixRisky ?? [] as $value) { // what a worker may fix has to be what the parent was asked for + $command[] = is_string($value) ? "--fix-risky=$value" : '--fix-risky'; + } + + if ($run->profile !== null) { // a worker measures and hands it over with every file, the parent writes + $command[] = "--profile=$run->profile"; + } + + return $command; + } + + + /** + * Runs the check without the current baseline over code a fix leaves alone and writes what remains into the + * configured baseline file, or into the one of the default name the run finds by itself; code a fix would still + * change, or a file that fails or does not parse, is refused. + * @param list $files + */ + private function generateBaseline( + Runner $runner, + Config $config, + string $root, + ?string $configFile, + array $files, + ?WorkerPool $workers, + string $format, + ): int + { + $name = $config->baseline ?? Baseline::getDefaultName($configFile); + $file = Helpers::toAbsolutePath($name, $root); + $collected = new Reporters\CollectingReporter; + $run = $runner->run($files, fix: false, reporter: $collected, workers: $workers); + $changed = $failed = []; + foreach ($run->files as $result) { + if ($result->failure !== null || $result->syntaxError !== null) { + $failed[] = $result->path; + } elseif ($result->changed) { + $changed[] = $result->path; + } + } + + if ($changed || $failed) { + $counts = array_filter([ + $changed ? 'a fix would change ' . Helpers::formatCount(count($changed), 'file') : null, + $failed ? Helpers::formatCount(count($failed), 'file') . ' failed' : null, + ]); + $paths = [...$changed, ...$failed]; + $this->context->writeError( + 'The baseline is generated over code a fix leaves alone: ' . implode(', ', $counts) . '. Run `fix` first.', + 'suppressing#baseline', + implode('', array_map(fn(string $path) => " $path\n", array_slice($paths, 0, 10))) + . (count($paths) > 10 ? ' and ' . (count($paths) - 10) . " more\n" : ''), + ); + return 1; + } + + $baseline = Baseline::fromViolations($collected->violations); + $baseline->save($file); + $message = 'Baseline with ' . Helpers::formatCount($baseline->count(), 'violation') . " written to `$name`.\n"; + // every other format keeps its stream to itself + $format === 'console' ? $this->context->write($message) : $this->context->writeNote($message); + return 0; + } + + + /** + * @param bool $diff the console shows the fixes as a unified diff + * @param resource $stream the same place as the console; a machine-readable format is no text of a console + * @param string $root the paths of the results are relative to it + * @param list $paths the paths as the command line gave them + * @param string $command the command whose `--ask-risky` decides the risky fixes left + */ + private function createReporter( + bool $diff, + Console $console, + $stream, + string $root, + string $format, + PluginRegistry $registry, + Runner $runner, + ResolvedProject $resolution, + array $paths, + string $command = 'fix', + ): Reporter + { + return match ($format) { + 'lines' => new Reporters\LinesReporter($stream, $root, Helpers::canonicalizePath($this->context->workingDirectory)), + 'agent' => new Reporters\AgentReporter( + $stream, + $root, + Helpers::canonicalizePath($this->context->workingDirectory), + givenPaths: array_combine( + array_map(fn(string $path) => Helpers::canonicalizePath($this->context->resolvePath($path)), $paths), + $paths, + ), + findSuppressionExamples: function (string $path) use ($runner, $resolution): array { + $config = $resolution->resolveFor($runner->findOverridesFor($path)); + $examples = []; + foreach ($config->suppressionComments as $pattern => $decisions) { + foreach (isset($config->suppressionExamples[$pattern]) ? $decisions : [] as $decision) { + $examples[$decision][] = $config->suppressionExamples[$pattern]; + } + } + + return $examples; + }, + ), + 'json' => new Reporters\JsonReporter($stream), + 'checkstyle' => new Reporters\CheckstyleReporter($stream), + 'github' => new Reporters\GithubReporter($stream, $root, self::findEnv('GITHUB_WORKSPACE')), + default => new Reporters\ConsoleReporter( + $console, + diff: $diff, + root: $root, + cwd: Helpers::canonicalizePath($this->context->workingDirectory), + findDecisionUrl: $registry->findUrl(...), + command: $command, + ), + }; + } + + + /** + * The format asked for, or the one the surroundings call for: annotations when the run is a step + * of a GitHub Actions workflow, where nobody reads the log. + * @param bool $detect let the surroundings decide when the command line does not + */ + private static function resolveFormat(?string $format, bool $detect): string + { + return $format ?? ($detect && self::findEnv('GITHUB_ACTIONS') === 'true' ? 'github' : 'console'); + } + + + private static function findEnv(string $name): ?string + { + $value = getenv($name); + return $value === false || $value === '' ? null : $value; + } +} diff --git a/src/Console/RunOutcomePrinter.php b/src/Console/RunOutcomePrinter.php new file mode 100644 index 0000000000..5dc53970fe --- /dev/null +++ b/src/Console/RunOutcomePrinter.php @@ -0,0 +1,245 @@ +outcome; + $out = ''; + foreach ($outcome->applied as $number => $topics) { + $out .= Markup::formatLine($console, "Step $number", implode(', ', array_map( + fn(string $topic, array $files) => "$topic " + . ($files === [] ? 'left nothing to fix' : Helpers::formatCount(count($files), 'file')), + array_keys($topics), + $topics, + ))) . "\n"; + } + + $out .= new TasksPrinter( + $outcome->tasks, $outcome->postponed, $outcome->unprocessed, $this->root, self::ListedTasks, + )->print($console); + if ($baseline = $outcome->baseline) { + // a test failing before the first step is no regression, so passing the comparison is not passing the tests + $out .= Markup::formatLine( + $console, + 'Tests', + 'compared with their run before the first step' + . ($baseline->time === null ? '' : ', ' . date('Y-m-d H:i', $baseline->time)) + . ', where ' . $baseline->countNotPassed() . ' of ' . count($baseline->tests) . ' did not pass', + ) . "\n"; + } + + foreach ($outcome->warnings as $warning) { + $out .= Markup::formatLine($console, 'Warning', $warning) . "\n"; + } + + if ($outcome->raisedFiles !== []) { + $out .= Markup::formatLine( + $console, + 'Raised', + implode(', ', $outcome->raisedFiles) . ' changed', + ', which `dresscode upgrade abort` puts back as they were before the raise and installs', + ) . "\n"; + } + + return $out . match ($outcome->stop) { + RunStop::Tests => Markup::formatLine($console, 'Failed', match (true) { + $outcome->step === null => "$outcome->crash, so nothing was changed", + $this->plan->steps[$outcome->step - 1] instanceof DependencyStep + => "step $outcome->step raised the dependencies, which stay raised, and ", + default => "step $outcome->step went back, its fixes undone and the dependencies as the steps before left them, as ", + } . match (true) { + $outcome->step === null => '', + $outcome->newFailures === [] => $outcome->crash ?? 'the tests wrote no results after it', + default => 'these tests now fail: ' . implode(', ', $outcome->newFailures), + }), + RunStop::Commit => Markup::formatLine($console, 'Failed', "step $outcome->step, $outcome->commitFailure"), + RunStop::Composer => $outcome->composerFailure === null + ? Markup::formatLine($console, 'Waiting', "step $outcome->step, {$this->formatComposerStep((int) $outcome->step)}") + : Markup::formatLine( + $console, + 'Failed', + "step $outcome->step, $outcome->composerFailure; {$this->formatComposerStep((int) $outcome->step)}", + ), + RunStop::Raised => Markup::formatLine( + $console, + 'Waiting', + "step $outcome->step raised the dependencies", + ', which what runs after it loads anew', + ': run `dresscode upgrade run` again', + ), + RunStop::Manual + => Markup::formatLine($console, 'Waiting', "step $outcome->step, {$this->formatManualStep((int) $outcome->step)}"), + RunStop::Interrupted => $outcome->interrupted === [] + ? Markup::formatLine( + $console, + 'Failed', + "step $outcome->step did not finish and may have rewritten files its snapshots no longer tell", + ', which `git status` and `git diff` show', + ', or go on from the code as it is with `dresscode upgrade run --discard`', + ) + : Markup::formatLine( + $console, + 'Failed', + "step $outcome->step did not finish, and may have rewritten " . implode(', ', $outcome->interrupted) + . ': `dresscode upgrade abort` puts them back as they were before it' + . ', or go on from the code as it is with `dresscode upgrade run --discard`', + ), + RunStop::Tasks => Markup::formatLine( + $console, + 'Waiting', + ($outcome->step === null ? 'the plan leaves' : "step $outcome->step leaves") . ' the manual tasks above: fix each or accept it with ' + . '`// dresscode:ignore -- `, then run `dresscode upgrade run`', + ), + RunStop::Unprocessed => Markup::formatLine( + $console, + 'Waiting', + "step $outcome->step did not fix the files above: make each parse, or leave it out of the paths, then run `dresscode upgrade run`", + ), + RunStop::Remaining => Markup::formatLine( + $console, + 'Waiting', + 'the targets still find what no step of the plan fixed' + . ($outcome->remaining === [] + ? ', listed above' + : ', which `dresscode upgrade today` fixes in ' . implode(', ', $outcome->remaining)) + . ', then run `dresscode upgrade run`', + ), + RunStop::Done => $console->color('white/green', $this->singleStep === null + ? 'UPGRADED ' . $this->formatDoneSteps() . ', and the final check finds nothing more to upgrade' + . (($this->plan->testCommand ?? $this->plan->quickTestCommand) === null ? ', no tests run' : '') + . ($this->plan->missingData === [] + ? '' + : ', though without the upgrading data of ' + . implode(', ', array_keys($this->plan->missingData)) + . ', which the estimate lacked') + : "DONE step $this->singleStep") + . ($this->singleStep === null && $this->leavesLowest() + ? "\n" . Markup::highlightCode( + $console, + 'A raise of the plan installs the lowest versions the constraints allow, which the code is written for; `composer update` installs the newest.', + ) + : ''), + } . "\n"; + } + + + /** + * The run as the data the format `json` writes beside the plan. + * @return array + */ + public function toArray(): array + { + $outcome = $this->outcome; + $applied = []; + foreach ($outcome->applied as $step => $topics) { + foreach ($topics as $topic => $files) { + $applied[] = ['step' => $step, 'topic' => $topic, 'files' => $files]; + } + } + + $found = new TasksPrinter($outcome->tasks, $outcome->postponed, $outcome->unprocessed)->toArray(); + return [ + 'stop' => lcfirst($outcome->stop->name), + 'step' => $outcome->step, + 'applied' => $applied, + 'tasks' => $found['tasks'], + 'exceptions' => $found['exceptions'], + 'newFailures' => $outcome->newFailures, + 'crash' => $outcome->crash, + 'baseline' => $outcome->baseline === null ? null : [ + 'time' => $outcome->baseline->time === null ? null : date(DATE_ATOM, $outcome->baseline->time), + 'tests' => count($outcome->baseline->tests), + 'notPassed' => $outcome->baseline->countNotPassed(), + ], + 'unverified' => $found['unverified'], + 'blockers' => $outcome->blockers === null ? null : [ + 'packages' => array_map(fn(Blocker $blocker) => (array) $blocker, $outcome->blockers->packages), + 'unknown' => $outcome->blockers->unknown, + ], + 'interrupted' => $outcome->interrupted, + 'raisedFiles' => $outcome->raisedFiles, + 'remaining' => $outcome->remaining, + 'warnings' => $outcome->warnings, + 'composerFailure' => $outcome->composerFailure, + 'commitFailure' => $outcome->commitFailure, + ]; + } + + + /** The steps of the plan that ran and those it skips: "3 steps done, 1 skipped as the plan says". */ + private function formatDoneSteps(): string + { + $done = count($this->plan->findSteps()); + $skipped = count($this->plan->steps) - $done; + return Helpers::formatCount($done, 'step') . ' done' . ($skipped ? ", $skipped skipped as the plan says" : ''); + } + + + /** + * Whether a step of the plan updates the packages, which it leaves at the lowest versions the constraints allow, and + * no step of it updates them to the newest then. + */ + private function leavesLowest(): bool + { + $steps = $this->plan->findSteps(); + return array_any($steps, fn(Step $step) => $step instanceof ComposerStep && $step->update) + && !array_any($steps, fn(Step $step) => $step instanceof UpdateStep); + } + + + private function formatComposerStep(int $number): string + { + $step = $this->plan->steps[$number - 1]; + assert($step instanceof DependencyStep); + return "$step->title: run `" . implode('` and `', $step->formatCommands()) . '`, then `dresscode upgrade run`'; + } + + + private function formatManualStep(int $number): string + { + $step = $this->plan->steps[$number - 1]; + assert($step instanceof ManualStep && $this->outcome->blockers !== null); + return "make way for {$step->target->format()}, " . EstimatePrinter::formatBlockers($this->outcome->blockers) + . ($this->outcome->blockers->unknown === null + ? ": update or replace what refuses it, as `{$step->formatCommand()}` tells" + : ': where you know nothing refuses it, set `skip: true` on the step in `' . PlanFile::Name . '`') + . ', then run `dresscode upgrade run`'; + } +} diff --git a/src/Console/StatusPrinter.php b/src/Console/StatusPrinter.php new file mode 100644 index 0000000000..c0b771e1a2 --- /dev/null +++ b/src/Console/StatusPrinter.php @@ -0,0 +1,123 @@ +status; + $out = Markup::formatLine($console, 'Plan', implode(', ', array_map(fn(Target $target) => $target->format(), $this->plan->targets))) + . "\n"; + $width = max([0, ...array_map(fn(Step $step) => strlen($step->title), $this->plan->steps)]); + foreach ($this->plan->steps as $index => $step) { + $out .= sprintf(' %2d %s %s', $index + 1, str_pad($step->title, $width), match ($status->steps[$index + 1]) { + StepStatus::Done => $console->color('green', 'done'), + StepStatus::Due => $console->color('yellow', 'due'), + StepStatus::Skipped => $console->color('gray', 'skipped'), + StepStatus::Unknown => Markup::formatAside($console, $step instanceof FixStep + ? 'what is left `upgrade run` fixes and `upgrade tasks` lists' + : '`upgrade run` tells'), + }) . "\n"; + } + + foreach ($status->interrupted as $step => $files) { + $out .= Markup::formatLine($console, 'Stopped', "step $step did not finish and may have rewritten " . implode(', ', $files)) + . "\n"; + } + + if ($status->raisedFiles !== []) { + $out .= Markup::formatLine( + $console, + 'Raised', + "step $status->raisedStep changed " . implode(', ', $status->raisedFiles), + ', which `dresscode upgrade abort` puts back', + ) . "\n"; + } + + if ($status->awaitingInstall) { + $out .= Markup::formatLine( + $console, + 'Install', + 'the files of Composer are put back, but not the packages yet', + ', which `dresscode upgrade abort` installs', + ) . "\n"; + } + + if ($status->uncommittedStep !== null) { + $out .= Markup::formatLine( + $console, + 'Commit', + "step $status->uncommittedStep is not committed yet", + ', which the next `upgrade run --commit` does', + ) . "\n"; + } + + foreach ($status->baselines as $command => $time) { + $out .= ($time === null + ? Markup::formatLine( + $console, + 'Tests', + Violation::formatCode($command) . ' has no run before the first step yet', + ', which the next `upgrade run` takes', + ) + : Markup::formatLine( + $console, + 'Tests', + Violation::formatCode($command) . ' is compared with its run of ' . date('Y-m-d H:i', $time), + )) + . "\n"; + } + + return $out . Markup::formatLine($console, 'Next', $status->interrupted === [] + ? '`dresscode upgrade run` carries on from where the code stands, and ends at once where nothing is left' + : '`dresscode upgrade abort --dry-run` shows what `upgrade abort` puts back, or `dresscode upgrade run --discard` goes on from the code as it is') + . "\n"; + } + + + /** + * Where the plan stands as the data the format `json` writes. + * @return array + */ + public function toArray(): array + { + $status = $this->status; + return [ + 'version' => self::Version, + 'steps' => array_map(fn(StepStatus $step) => lcfirst($step->name), $status->steps), + 'interrupted' => (object) $status->interrupted, + 'raisedStep' => $status->raisedStep, + 'raisedFiles' => $status->raisedFiles, + 'awaitingInstall' => $status->awaitingInstall, + 'uncommittedStep' => $status->uncommittedStep, + 'baselines' => (object) array_map(fn(?int $time) => $time === null ? null : date(DATE_ATOM, $time), $status->baselines), + ]; + } +} diff --git a/src/Console/TasksPrinter.php b/src/Console/TasksPrinter.php new file mode 100644 index 0000000000..f07fc2db45 --- /dev/null +++ b/src/Console/TasksPrinter.php @@ -0,0 +1,174 @@ +> topic => its tasks */ + private array $tasks, + /** @var list */ + private array $postponed = [], + /** @var array the files the fixes could not process, relative to the root => why */ + private array $unprocessed = [], + /** the root the paths are relative to, whose files show the lines of a task; none shows none */ + private ?string $root = null, + /** more tasks than this are only counted by topic, `dresscode upgrade tasks` listing them */ + private int $listed = PHP_INT_MAX, + ) { + } + + + public function print(Console $console): string + { + $tasks = array_merge(...array_values($this->tasks)); + $out = ''; + if (count($tasks) > $this->listed) { + $topics = array_filter($this->tasks); + $byTopic = array_map(fn(string $topic, array $found) => "`$topic` " . count($found), array_keys($topics), $topics); + $out .= Markup::formatLine( + $console, + 'Manual', + Helpers::formatCount(count($tasks), 'task') . ' the fixes left, ' . implode(', ', $byTopic), + ': `dresscode upgrade tasks` lists them', + ) . "\n"; + } elseif ($tasks !== []) { + $out .= Markup::formatLine($console, 'Manual', Helpers::formatCount(count($tasks), 'task') . ' the fixes left') . "\n"; + $files = []; + foreach ($tasks as $task) { + $violation = $task->violation; + $out .= " $task->path:$violation->line " . Markup::highlightCode($console, $violation->message) + . ' ' . $console->color('gray', "[$violation->decision]") . "\n" + . ($violation->risk === null ? '' : ' ' . Markup::formatAside($console, self::formatRisk($violation)) . "\n"); + if ($this->root !== null) { + $files[$task->path] ??= explode("\n", (string) @file_get_contents("$this->root/$task->path")); // @ a file gone meanwhile shows no lines + foreach (self::selectLines($files[$task->path], $violation->line) as $code) { + $out .= ' ' . Markup::highlightCode($console, Violation::formatCode($code)) . "\n"; + } + } + } + } + + if ($this->postponed !== []) { + $out .= Markup::formatLine( + $console, + 'Exceptions', + Helpers::formatCount(count($this->postponed), 'suppression') + . ' giving no reason, so not accepted yet: accept each with ` -- `', + ) . "\n"; + foreach ($this->postponed as $postponement) { + $out .= " $postponement->path:$postponement->line $postponement->comment\n"; + } + } + + if ($this->unprocessed !== []) { + $out .= Markup::formatLine( + $console, + 'Unverified', + Helpers::formatCount(count($this->unprocessed), 'file') . ' the fixes could not process, left as they are', + ) . "\n"; + foreach ($this->unprocessed as $path => $why) { + $out .= " $path " . Markup::highlightCode($console, (string) strtok($why, "\n")) . "\n"; + } + } + + return $out; + } + + + /** + * The line of a task with the one above and the one below, a blank one left out, without the indentation they share. + * @param list $lines of the file + * @return list + */ + private static function selectLines(array $lines, int $line): array + { + $around = array_slice($lines, max(0, $line - 2), $line === 1 ? 2 : 3); + return Markup::stripIndentation(array_values(array_filter(array_map(rtrim(...), $around), fn(string $code) => $code !== ''))); + } + + + /** What the fix of a risky place waits for, and how to give it. */ + private static function formatRisk(Violation $violation): string + { + return match ($violation->risk) { + Risk::TypeUnknown => 'its fix needs the type of the expression, which the analysis does not know; where the types are off, `--types` turns them on', + Risk::NameUncertain => 'its fix needs to know which function the name calls, which a declaration elsewhere could change; fix it by hand, or list what the namespaces declare under `namespaces` with `nameResolution: certain`', + default => 'its fix is risky' . ($violation->because === null ? '' : ", as $violation->because") + . "; once you checked it, `fixRisky: [$violation->decision]` allows it", + }; + } + + + /** + * The tasks as the data the format `json` writes. + * @return array{ + * tasks: list>, + * exceptions: list, + * unverified: list, + * } + */ + public function toArray(): array + { + $tasks = []; + foreach ($this->tasks as $topic => $topicTasks) { + foreach ($topicTasks as $task) { + $tasks[] = [ + 'topic' => $topic, + 'file' => $task->path, + 'line' => $task->violation->line, + 'decision' => $task->violation->decision, + 'message' => $task->violation->message, + 'fixable' => $task->violation->fixable, + 'risk' => $task->violation->risk?->value, + 'because' => $task->violation->because, + ]; + } + } + + return [ + 'tasks' => $tasks, + 'exceptions' => array_map( + fn(Postponement $postponement) => [ + 'file' => $postponement->path, + 'line' => $postponement->line, + 'comment' => $postponement->comment, + ], + $this->postponed, + ), + 'unverified' => self::listUnverified($this->unprocessed), + ]; + } + + + /** + * The files a check could not process as the JSON documents write them. + * @param array $unprocessed file => why + * @return list + */ + public static function listUnverified(array $unprocessed): array + { + return array_map(fn(string $path, string $why) => ['file' => $path, 'message' => $why], array_keys($unprocessed), $unprocessed); + } +} diff --git a/src/Engine/Baseline.php b/src/Engine/Baseline.php index d464249022..ce37b3088b 100644 --- a/src/Engine/Baseline.php +++ b/src/Engine/Baseline.php @@ -7,7 +7,7 @@ namespace DressCode\Engine; -use DressCode\{Config, ConfigurationException, FileResult}; +use DressCode\{Config, ConfigurationException, Violation}; use DressCode\Config\Loader; use Nette\Neon\{Exception as NeonException, Neon}; use function is_array, is_string; @@ -120,15 +120,15 @@ public static function load(string $file, bool $required = false): ?self } - /** @param list $results */ - public static function fromResults(array $results): self + /** @param array> $violations the path => what the file violates */ + public static function fromViolations(array $violations): self { $baseline = new self; - foreach ($results as $result) { - foreach ($result->violations as $violation) { + foreach ($violations as $path => $list) { + foreach ($list as $violation) { // a refused risky fix that is only uncertain waits for what the project can tell, not for the baseline if (!$violation->refused || !$violation->risk?->isResolvable()) { - $baseline->add($result->path, $violation->fingerprint, $violation->decision, $violation->message); + $baseline->add($path, $violation->fingerprint, $violation->decision, $violation->message); } } } diff --git a/src/Engine/CycleCollector.php b/src/Engine/CycleCollector.php index bbe3852a15..fdf62b337a 100644 --- a/src/Engine/CycleCollector.php +++ b/src/Engine/CycleCollector.php @@ -24,8 +24,9 @@ final class CycleCollector private int $threshold = self::Floor; - public function __construct() - { + public function __construct( + private readonly ?Profiler $profiler = null, + ) { $this->enabled = gc_enabled(); gc_disable(); } @@ -38,7 +39,9 @@ public function collect(): void return; } + $start = $this->profiler ? hrtime(as_number: true) : 0; gc_collect_cycles(); + $this->profiler?->addPhase('gc', hrtime(as_number: true) - $start); $this->threshold = max(self::Floor, min(2 * memory_get_usage(), self::findCeiling())); } diff --git a/src/Engine/FileSummary.php b/src/Engine/FileSummary.php index 18c5d4c410..3f4a1f448d 100644 --- a/src/Engine/FileSummary.php +++ b/src/Engine/FileSummary.php @@ -7,22 +7,20 @@ namespace DressCode\Engine; -use DressCode\{FileResult, Violation}; +use DressCode\FileResult; /** - * What a run keeps of a file once it was reported: the result without its texts, so that a large tree does not stay - * in memory. + * What a run keeps of a file once it was reported: the result without its texts and with its violations only counted, + * so that a large tree does not stay in memory. * @internal */ final readonly class FileSummary { public function __construct( public string $path, - /** @var list */ - public array $violations, - /** @var list */ - public array $remaining, + public ViolationTally $violations, + public ViolationTally $remaining, /** the output differs from the code */ public bool $changed, public bool $written, @@ -36,8 +34,14 @@ public function __construct( public static function of(FileResult $result): self { return new self( - $result->path, $result->violations, $result->remaining, $result->changed, - $result->written, $result->cached, $result->syntaxError, $result->failure, + $result->path, + ViolationTally::of($result->violations), + ViolationTally::of($result->remaining), + $result->changed, + $result->written, + $result->cached, + $result->syntaxError, + $result->failure, ); } } diff --git a/src/Engine/Gaps/Claims.php b/src/Engine/Gaps/Claims.php index 0a3064da4b..0f02d3c9d3 100644 --- a/src/Engine/Gaps/Claims.php +++ b/src/Engine/Gaps/Claims.php @@ -8,6 +8,7 @@ namespace DressCode\Engine\Gaps; use DressCode\{Claim, ConfigurationException, Gap, GapRule, Rule}; +use DressCode\Engine\Profiler; use PhpSyntax\{LayoutData, Node}; use PhpSyntax\Nodes\{PlainNodeList, SeparatedNodeList}; use function sprintf, strlen; @@ -49,6 +50,7 @@ final class Claims */ public function __construct( array $rules, + private readonly ?Profiler $profiler = null, ) { foreach ($rules as $rule) { if (!$rule instanceof GapRule) { @@ -172,10 +174,31 @@ private function claim(array &$side, string $name, string $key, Rule $rule, Clai } } + if ($claim instanceof \Closure && $this->profiler) { + $claim = self::measureClaim($claim, $rule::class, $this->profiler); + } + $side[$key][] = [$rule, $claim, $key]; } + /** + * @param \Closure(Gap): ?Claim $claim + * @return \Closure(Gap): ?Claim + */ + private static function measureClaim(\Closure $claim, string $rule, Profiler $profiler): \Closure + { + return static function (Gap $gap) use ($claim, $rule, $profiler): ?Claim { + $start = hrtime(as_number: true); + try { + return $claim($gap); + } finally { + $profiler->addClaim($rule, hrtime(as_number: true) - $start); + } + }; + } + + /** @throws ConfigurationException */ public static function refuseSecond(Rule $first, Rule $second, string $side, string $key): never { diff --git a/src/Engine/Helpers.php b/src/Engine/Helpers.php index 092648f596..65b4b6b4ed 100644 --- a/src/Engine/Helpers.php +++ b/src/Engine/Helpers.php @@ -156,6 +156,26 @@ public static function writeFile(string $file, string $content): bool } + /** + * Writes through a temporary file of its own renamed over the target, so that the file is either as it was or whole, + * with no fallback in place; the directory is created where it is missing. + * @throws IOException + */ + public static function replaceFile(string $file, string $content): void + { + $temp = self::writeTemporary($file, $content); + // Windows refuses a rename over a file another process holds open, as a scanner does for a moment after a write + for ($attempt = 1; !@rename($temp, $file); $attempt++) { // @ the failure is thrown below + if ($attempt === 10) { + @unlink($temp); // @ nothing to clean up then + throw new IOException("Unable to write file '$file'."); + } + + usleep(20_000); + } + } + + /** * Writes a file that does not exist yet, whole, and never over one another process created meanwhile. * @return bool false where the file exists diff --git a/src/Engine/PassLoop.php b/src/Engine/PassLoop.php index f2b9fcec7c..0e3c241628 100644 --- a/src/Engine/PassLoop.php +++ b/src/Engine/PassLoop.php @@ -76,6 +76,7 @@ public function __construct( private readonly RulePlan $plan, private readonly Analyses\Registry $analyses, private readonly ReportPolicy $policy = new ReportPolicy, + private readonly ?Profiler $profiler = null, ) { $this->gaps = new Resolver($plan->claims); } @@ -139,7 +140,9 @@ public function run(FileNode $file, string $code, string $path, Style $style, st $context->passStorage = []; } + $start = $this->profiler ? hrtime(as_number: true) : 0; $this->analyses->beginPass($file); + $this->profiler?->addPhase('analyses: begin pass', hrtime(as_number: true) - $start); $revision = $file->revision; foreach ($this->plan->stages as $stage => $rules) { $this->runStage($stage, $rules, $style); @@ -158,7 +161,9 @@ public function run(FileNode $file, string $code, string $path, Style $style, st $mutated = true; $mutatedRules += $this->mutatedRules; + $start = $this->profiler ? hrtime(as_number: true) : 0; $output = Printer::print($file); + $this->profiler?->addPhase('print', hrtime(as_number: true) - $start); $hash = hash('xxh3', $output); if (isset($seen[$hash])) { // a state seen before: the rules cycle throw new ConvergenceException($path, array_keys($this->mutatedRules), Diff::unified($last, $output, $path)); @@ -261,6 +266,7 @@ private static function createViolation( offset: $span[0] ?? null, length: $span[1] ?? null, originalLines: $originalLines, + source: $report->source, ); } @@ -353,8 +359,10 @@ static function (string $class, Rule $rule) use ($analyses, $file, $path, $stric return; } + $start = $this->profiler ? hrtime(as_number: true) : 0; try { $node instanceof Token ? $gaps->enterToken($node) : $gaps->enterNode($node); + $this->profiler?->addPhase('gaps', hrtime(as_number: true) - $start); } catch (ConfigurationException|RuleException $e) { // two claims deciding one gap, or a claim of the rule named failing throw $e; } catch (\Throwable $e) { @@ -394,14 +402,17 @@ private function visit(string $stage, Node|Token $node, bool $enter): void $parent = $node->parent; $file = $this->file; + $profiler = $this->profiler; foreach ($rules as [$rule, $context, $ruleClass]) { $before = $file->revision; + $start = $profiler ? hrtime(as_number: true) : 0; try { $enter ? $rule->enter($node, $context) : $rule->leave($node, $context); } catch (\Throwable $e) { throw new RuleException($ruleClass, $this->path, $e); } + $profiler?->addRule($ruleClass, hrtime(as_number: true) - $start, $file->revision !== $before); if ($file->revision !== $before || $context->hasReports()) { $this->account($ruleClass, $context, $before); } @@ -444,12 +455,14 @@ private function invoke(NodeRule $rule, \Closure $callback): void $ruleClass = $rule::class; $context = $this->contexts[$ruleClass]; $before = $this->file->revision; + $start = $this->profiler ? hrtime(as_number: true) : 0; try { $callback($context); } catch (\Throwable $e) { throw new RuleException($ruleClass, $this->path, $e); } + $this->profiler?->addRule($ruleClass, hrtime(as_number: true) - $start, $this->file->revision !== $before); $this->account($ruleClass, $context, $before); } diff --git a/src/Engine/PhpFileProcessor.php b/src/Engine/PhpFileProcessor.php index c7ddd4c170..c1f5a7e554 100644 --- a/src/Engine/PhpFileProcessor.php +++ b/src/Engine/PhpFileProcessor.php @@ -11,6 +11,7 @@ use PhpSyntax\Nodes\FileNode; use PhpSyntax\Nodes\Statement\{NamespaceNode, UseNode}; use PhpSyntax\{ParseException, Parser, SymbolKind}; +use function strlen; /** @@ -36,11 +37,12 @@ public function __construct( /** the line ending of the style follows the prevailing one of each file */ private bool $detectLineEnding = true, private ReportPolicy $policy = new ReportPolicy, + private ?Profiler $profiler = null, /** @var array the class of a rule => the gate of its reports */ private array $gates = [], ) { $this->parser = new Parser; - $this->plan = new RulePlan($this->rules, $this->gates); + $this->plan = new RulePlan($this->rules, $this->profiler, $this->gates); } @@ -74,15 +76,18 @@ public function process(string $path, string $code, array $acceptedRisks = []): $settled = false; $remaining = null; $removedImports = $mutatedRules = []; + $start = $this->profiler ? hrtime(as_number: true) : 0; + $times = ['parse' => 0, 'passes' => 0]; // a mutated tree is not the tree the parser would build from the printed text, so a rule can miss what another // one has just written; the strict run makes the text settle in rounds, the others take what the last pass // of the tree left for what a round over the text would report, which spares a pass; they only parse the printed // text, so that a broken rule never writes code PHP refuses - $passLoop = new PassLoop($this->plan, $this->analyses, $this->policy); + $passLoop = new PassLoop($this->plan, $this->analyses, $this->policy, $this->profiler); $rounds = 0; while (!$settled) { $rounds++; + $lap = $this->profiler ? hrtime(as_number: true) : 0; try { $file = $this->parser->parse($text); self::checkImports($file); @@ -90,6 +95,11 @@ public function process(string $path, string $code, array $acceptedRisks = []): return self::createSyntaxError($path, $code, $e, $rounds); } + if ($this->profiler) { + $times['parse'] += hrtime(as_number: true) - $lap; + $lap = hrtime(as_number: true); + } + try { $result = $passLoop->run($file, $text, $path, $style, $this->phpVersion, $acceptedRisks); } catch (RuleException $e) { @@ -104,6 +114,10 @@ public function process(string $path, string $code, array $acceptedRisks = []): $passes += $result->passes; array_push($removedImports, ...$result->removedImports); array_push($mutatedRules, ...$result->mutatedRules); + if ($this->profiler) { + $times['passes'] += hrtime(as_number: true) - $lap; + } + $printed = $result->output ?? $text; $settled = $printed === $text; $seen[hash('xxh3', $text)] = true; @@ -114,17 +128,38 @@ public function process(string $path, string $code, array $acceptedRisks = []): $text = $printed; if (!$settled && !$this->policy->strict && $result->remaining !== null) { + $lap = $this->profiler ? hrtime(as_number: true) : 0; try { self::checkImports($this->parser->parse($text)); } catch (ParseException $e) { return self::createParseFailure($path, $code, $e); } + if ($this->profiler) { + $times['parse'] += hrtime(as_number: true) - $lap; + } + $remaining = $result->remaining; + $rounds++; // the parse of the printed text stands for the round over it break; } } + if ($this->profiler) { + foreach ($times as $phase => $time) { + $this->profiler->addPhase($phase, $time, $rounds); + } + + $this->profiler->addFile([ + 'path' => $path, + 'size' => strlen($code), + 'time' => hrtime(as_number: true) - $start, + ...$times, + 'rounds' => $rounds, + 'passCount' => $passes, + ]); + } + // the last round is a check of the text the fix writes; a round after the first parsed that text, not the file as read $remaining ??= $result === $first ? $result->violations diff --git a/src/Engine/ProcessRunner.php b/src/Engine/ProcessRunner.php index b6622ef35f..960c0afa09 100644 --- a/src/Engine/ProcessRunner.php +++ b/src/Engine/ProcessRunner.php @@ -7,7 +7,7 @@ namespace DressCode\Engine; -use function count; +use function count, is_string; use const PHP_OS_FAMILY; @@ -25,20 +25,22 @@ final class ProcessRunner /** * The exit code and the output of both streams, or of the standard one alone, the exit code null where the command did * not end in time. - * @param list $command the program and its arguments + * @param string|list $command a command line, or its program and arguments to quote * @param ?string $input what the command reads on its standard input + * @param array $env the variables set beside those of this process * @return array{?int, string} */ public static function run( - array $command, + string|array $command, string $cwd, int $timeout, ?string $input = null, bool $errors = true, + array $env = [], ): array { - // the shell of Windows is what finds a program that is a `.bat` - $command = PHP_OS_FAMILY !== 'Windows' + // the shell of Windows is what finds `composer.bat` + $command = is_string($command) || PHP_OS_FAMILY !== 'Windows' ? $command : implode(' ', array_map(escapeshellarg(...), $command)); // files rather than pipes, which Windows reads only blocking, so that a command holding them open still ends in time @@ -49,7 +51,13 @@ public static function run( fwrite($stdin, (string) $input); rewind($stdin); - $process = proc_open($command, [0 => $stdin, 1 => $stdout, 2 => $stderr ?? $stdout], $pipes, $cwd); + $process = proc_open( + $command, + [0 => $stdin, 1 => $stdout, 2 => $stderr ?? $stdout], + $pipes, + $cwd, + $env === [] ? null : [...getenv(), ...$env], + ); if ($process === false) { return [127, 'The command could not be started.']; } diff --git a/src/Engine/Profiler.php b/src/Engine/Profiler.php new file mode 100644 index 0000000000..cd0d8883d4 --- /dev/null +++ b/src/Engine/Profiler.php @@ -0,0 +1,146 @@ +> phase => nanoseconds, calls */ + private array $phases = []; + + /** @var array> rule => nanoseconds, calls, calls that changed the tree */ + private array $rules = []; + + /** @var array> gap rule => nanoseconds, calls of its claims */ + private array $claims = []; + + /** @var list> every file with the phases of its processing */ + private array $files = []; + + /** @var array process id => its peak memory */ + private array $memory = []; + + + public function addPhase(string $phase, int $time, int $calls = 1): void + { + self::add($this->phases, $phase, [$time, $calls]); + } + + + public function addRule(string $rule, int $time, bool $mutated): void + { + self::add($this->rules, $rule, [$time, 1, (int) $mutated]); + } + + + public function addClaim(string $rule, int $time): void + { + self::add($this->claims, $rule, [$time, 1]); + } + + + /** @param array $file path, size, time and the phases of its processing */ + public function addFile(array $file): void + { + $this->files[] = $file; + } + + + /** + * What was measured since the last call, as data for another process, and forgets it. + * @return array + */ + public function takeRecords(): array + { + $records = [ + 'phases' => $this->phases, + 'rules' => $this->rules, + 'claims' => $this->claims, + 'files' => $this->files, + 'memory' => [getmypid() => memory_get_peak_usage()], + ]; + $this->phases = $this->rules = $this->claims = $this->files = []; + return $records; + } + + + /** @param array $records as `takeRecords()` of another process made them */ + public function merge(array $records): void + { + foreach (['phases', 'rules', 'claims'] as $table) { + foreach (is_array($records[$table] ?? null) ? $records[$table] : [] as $name => $values) { + self::add($this->$table, (string) $name, array_values(array_map(intval(...), (array) $values))); + } + } + + foreach (is_array($records['files'] ?? null) ? $records['files'] : [] as $file) { + $this->files[] = (array) $file; + } + + foreach (is_array($records['memory'] ?? null) ? $records['memory'] : [] as $pid => $peak) { + $this->memory[(int) $pid] = max($this->memory[(int) $pid] ?? 0, (int) $peak); + } + } + + + /** + * The profile of the whole run, the most expensive first; every file with its size and time, in the order + * of the paths, for a sample to be drawn from. + * @return array + */ + public function toArray(): array + { + $files = $this->files; + usort($files, fn(array $a, array $b) => $b['time'] <=> $a['time']); + $times = []; + foreach ($files as $file) { + $times[(string) $file['path']] = [(int) $file['size'], (int) $file['time']]; + } + + ksort($times); + $pid = (int) getmypid(); + $this->memory[$pid] = max($this->memory[$pid] ?? 0, memory_get_peak_usage()); + $byTime = static function (array $table, array $names): array { + uasort($table, fn(array $a, array $b) => $b[0] <=> $a[0]); + return array_map(fn(array $values) => array_combine($names, $values), $table); + }; + return [ + 'schema' => self::Schema, + 'files' => count($files), + 'phases' => $byTime($this->phases, ['time', 'calls']), + 'rules' => $byTime($this->rules, ['time', 'calls', 'mutating']), + 'claims' => $byTime($this->claims, ['time', 'calls']), + 'slowestFiles' => array_slice($files, 0, self::SlowestFiles), + 'fileTimes' => $times, + 'peakMemory' => $this->memory, + ]; + } + + + /** + * @param array> $table + * @param list $values + */ + private static function add(array &$table, string $name, array $values): void + { + $table[$name] = isset($table[$name]) + ? array_map(fn(int $a, int $b) => $a + $b, $table[$name], $values) + : $values; + } +} diff --git a/src/Engine/Report.php b/src/Engine/Report.php index d8f9326e08..d3eac951c0 100644 --- a/src/Engine/Report.php +++ b/src/Engine/Report.php @@ -7,6 +7,7 @@ namespace DressCode\Engine; +use DressCode\Config\Layer; use DressCode\Risk; use PhpSyntax\{Node, Token, Trivia}; @@ -58,6 +59,8 @@ public function __construct( public int $lineInTrivia = 0, /** @var ?array{int, int} the offset and the length of what the report is about in the original file */ public ?array $span = null, + /** the section of the upgrading data of a package whose entry the occurrence is of */ + public ?Layer $source = null, ) { } } diff --git a/src/Engine/RulePlan.php b/src/Engine/RulePlan.php index ff4791df72..cc613f7e6d 100644 --- a/src/Engine/RulePlan.php +++ b/src/Engine/RulePlan.php @@ -48,6 +48,7 @@ final class RulePlan public function __construct( /** @var list in configuration order */ public readonly array $rules, + ?Profiler $profiler = null, array $gates = [], ) { $stages = $leaves = []; @@ -79,7 +80,7 @@ public function __construct( $this->stages = $stages; $this->leaves = $leaves; $this->gates = $gates; - $this->claims = new Claims($rules); + $this->claims = new Claims($rules, $profiler); } diff --git a/src/Engine/RunResult.php b/src/Engine/RunResult.php index 36bf349bff..824acfbbec 100644 --- a/src/Engine/RunResult.php +++ b/src/Engine/RunResult.php @@ -7,7 +7,7 @@ namespace DressCode\Engine; -use DressCode\{Risk, Severity, Violation}; +use DressCode\{Risk, Severity}; use function count; @@ -18,7 +18,7 @@ final readonly class RunResult { public function __construct( - /** @var list without their code and output, which a reporter sees in `reportFile()` */ + /** @var list without their texts and violations, which a reporter sees in `reportFile()` */ public array $files, public bool $fix, /** violations the baseline matched */ @@ -34,7 +34,7 @@ public function __construct( /** Violations the files have as they were read. */ public function countViolations(?Severity $severity = null): int { - return self::countBySeverity(array_merge(...array_map(fn(FileSummary $f) => $f->violations, $this->files)), $severity); + return $this->sum(fn(FileSummary $f) => $f->violations->count($severity)); } @@ -44,35 +44,35 @@ public function countViolations(?Severity $severity = null): int */ public function countRemaining(?Severity $severity = null): int { - return self::countBySeverity(array_merge(...array_map(fn(FileSummary $f) => $f->remaining, $this->files)), $severity); + return $this->sum(fn(FileSummary $f) => $f->remaining->count($severity)); } /** Violations left to the user that follow from another one of the same file, whose fix opened, closed or moved their line. */ public function countDerived(?Severity $severity = null): int { - return self::countBySeverity(array_filter($this->listReported(), fn(Violation $v) => $v->derivedFrom !== null), $severity); + return $this->sum(fn(FileSummary $f) => $this->selectReported($f)->countDerived($severity)); } /** Fixes a fix leaves because the run did not allow them; a fix it made is not one of them. */ public function countRefused(): int { - return count($this->listRefused()); + return $this->sum(fn(FileSummary $f) => $f->remaining->countRefused()); } /** Fixes a fix leaves because the run did not allow them, of those the risk would decide. */ public function countRefusedBy(Risk $risk): int { - return count(array_filter($this->listRefused(), fn(Violation $v) => $v->risk === $risk)); + return $this->sum(fn(FileSummary $f) => $f->remaining->countRefused($risk)); } /** Violations the run leaves to the user that no rule has a fix for. */ public function countUnfixable(): int { - return count(array_filter($this->listReported(), fn(Violation $v) => !$v->fixable)); + return $this->sum(fn(FileSummary $f) => $this->selectReported($f)->countUnfixable()); } @@ -101,7 +101,7 @@ public function countFailures(): int */ public function countReported(?Severity $severity = null): int { - return self::countBySeverity($this->listReported(), $severity); + return $this->sum(fn(FileSummary $f) => $this->selectReported($f)->count($severity)); } @@ -120,26 +120,15 @@ public function getExitCode(): int } - /** @return list */ - private function listReported(): array + /** @param \Closure(FileSummary): int $count */ + private function sum(\Closure $count): int { - return array_merge(...array_map(fn(FileSummary $f) => $this->fix ? $f->remaining : $f->violations, $this->files)); + return array_sum(array_map($count, $this->files)); } - /** @return list */ - private function listRefused(): array + private function selectReported(FileSummary $file): ViolationTally { - return array_values(array_filter( - array_merge(...array_map(fn(FileSummary $f) => $f->remaining, $this->files)), - fn(Violation $v) => $v->refused, - )); - } - - - /** @param array $violations */ - private static function countBySeverity(array $violations, ?Severity $severity): int - { - return count(array_filter($violations, fn(Violation $v) => $severity === null || $v->severity === $severity)); + return $this->fix ? $file->remaining : $file->violations; } } diff --git a/src/Engine/Runner.php b/src/Engine/Runner.php index 1d5b330fd3..55df254e09 100644 --- a/src/Engine/Runner.php +++ b/src/Engine/Runner.php @@ -39,6 +39,8 @@ public function __construct( private ?ResultCache $cache = null, /** the run is narrowed to some of the decisions, so it says nothing about the baseline entries of the others */ private bool $narrowed = false, + /** measures the cycle collection of the files processed in this process */ + private ?Profiler $profiler = null, /** @var ?\Closure(): void fills the cache the workers share, which those started together would all write at once */ public ?\Closure $warmUp = null, /** @var ?\Closure(): ?list the files the results depend on beyond the configuration, once the run knows them */ @@ -229,7 +231,7 @@ private function processPending( return; } - $collector = new CycleCollector; + $collector = new CycleCollector($this->profiler); try { foreach ($paths as $path) { if ($onProgress !== null) { diff --git a/src/Engine/Suppression.php b/src/Engine/Suppression.php index ec21e61aef..cd0dee7dba 100644 --- a/src/Engine/Suppression.php +++ b/src/Engine/Suppression.php @@ -10,6 +10,7 @@ use PhpSyntax\{Node, Token, Trivia}; use PhpSyntax\Nodes\{FileNode, PlainNodeList, SeparatedNodeList}; use function count; +use const PREG_OFFSET_CAPTURE, PREG_UNMATCHED_AS_NULL; /** @@ -109,19 +110,26 @@ public static function fromFile(FileNode $file, \Closure $expandName, ?string $c /** - * The directive the comment holds, `dresscode:ignore upgrading -- why` or one of phpcs: its kind, the names it lists - * and its text; null for none. A directive runs to the end of its comment or its line. - * @return ?array{kind: string, names: string, text: string} + * The directive the comment holds, `dresscode:ignore upgrading -- why` or one of phpcs: its kind, the names it lists, + * the reason after ` -- `, its text and where it starts in the comment; null for none. A directive runs to the end of + * its comment or its line. + * @return ?array{kind: string, names: string, reason: string, text: string, offset: int} */ - private static function findDirective(string $comment): ?array + public static function findDirective(string $comment): ?array { return preg_match( - '~(?:dresscode|phpcs):(ignoreFile|ignore|disable|enable)(?:\s+([\w/.\\\\][\w/.\\\\,\s-]*?))?(?:\s+--(?:\s.*?)?)?(?=\s*(?:\*/|$))~m', + '~(?:dresscode|phpcs):(ignoreFile|ignore|disable|enable)(?:\s+([\w/.\\\\][\w/.\\\\,\s-]*?))?(?:\s+--(?:\s(.*?))?)?(?=\s*(?:\*/|$))~m', $comment, $m, - PREG_UNMATCHED_AS_NULL, + PREG_OFFSET_CAPTURE | PREG_UNMATCHED_AS_NULL, ) - ? ['kind' => (string) $m[1], 'names' => (string) ($m[2] ?? ''), 'text' => (string) $m[0]] + ? [ + 'kind' => (string) $m[1][0], + 'names' => (string) ($m[2][0] ?? ''), + 'reason' => trim((string) ($m[3][0] ?? '')), + 'text' => (string) $m[0][0], + 'offset' => $m[0][1], + ] : null; } diff --git a/src/Engine/ViolationTally.php b/src/Engine/ViolationTally.php new file mode 100644 index 0000000000..6c0be573e1 --- /dev/null +++ b/src/Engine/ViolationTally.php @@ -0,0 +1,78 @@ + the severity => how many */ + private array $all, + /** @var array the severity => how many follow from another violation of the file */ + private array $derived, + /** @var array the risk => how many fixes the run did not allow */ + private array $refused, + private int $unfixable, + ) { + } + + + /** @param list $violations */ + public static function of(array $violations): self + { + $all = $derived = $refused = []; + $unfixable = 0; + foreach ($violations as $violation) { + $severity = $violation->severity->value; + $all[$severity] = ($all[$severity] ?? 0) + 1; + if ($violation->derivedFrom !== null) { + $derived[$severity] = ($derived[$severity] ?? 0) + 1; + } + + if ($violation->refused) { + $risk = $violation->risk->value ?? ''; + $refused[$risk] = ($refused[$risk] ?? 0) + 1; + } + + $unfixable += $violation->fixable ? 0 : 1; + } + + return new self($all, $derived, $refused, $unfixable); + } + + + public function count(?Severity $severity = null): int + { + return $severity === null ? array_sum($this->all) : $this->all[$severity->value] ?? 0; + } + + + public function countDerived(?Severity $severity = null): int + { + return $severity === null ? array_sum($this->derived) : $this->derived[$severity->value] ?? 0; + } + + + public function countRefused(?Risk $risk = null): int + { + return $risk === null ? array_sum($this->refused) : $this->refused[$risk->value] ?? 0; + } + + + public function countUnfixable(): int + { + return $this->unfixable; + } +} diff --git a/src/Engine/Worker.php b/src/Engine/Worker.php index a127f5ffce..ba76b4536e 100644 --- a/src/Engine/Worker.php +++ b/src/Engine/Worker.php @@ -19,7 +19,7 @@ final class Worker { /** @return int exit code */ - public static function run(string $address, Runner $runner, bool $fix): int + public static function run(string $address, Runner $runner, bool $fix, ?Profiler $profiler = null): int { $context = stream_context_create(['socket' => ['tcp_nodelay' => true]]); // Nagle would delay every small message by an ACK $socket = @stream_socket_client("tcp://$address", $errno, $error, timeout: 10, context: $context); // @ reported below @@ -28,10 +28,15 @@ public static function run(string $address, Runner $runner, bool $fix): int return 2; } - $collector = new CycleCollector; + $collector = new CycleCollector($profiler); $sent = false; while (($line = fgets($socket)) !== false) { $job = json_decode($line, associative: true); + if (is_array($job) && ($job['finish'] ?? null) === true) { // nothing is left; the parent waits for what was measured since the last file + fwrite($socket, json_encode(['profile' => $profiler?->takeRecords() ?? []], JSON_THROW_ON_ERROR) . "\n"); + continue; + } + $path = is_array($job) && is_string($job['path'] ?? null) ? base64_decode($job['path'], strict: true) : false; if ($path === false) { fwrite(STDERR, "Unexpected message from the parent: $line"); @@ -39,7 +44,7 @@ public static function run(string $address, Runner $runner, bool $fix): int } $result = $runner->processPath($path, $fix); - $message = WorkerCodec::encode($result); + $message = WorkerCodec::encode($result, $profiler?->takeRecords()); // the files the results depend on and what the analyses tell, with the first result after they are known if (!$sent && ($dependencies = ($runner->findDependencies)?->__invoke()) !== null) { $message['dependencies'] = $dependencies; diff --git a/src/Engine/WorkerCodec.php b/src/Engine/WorkerCodec.php index 10420b22fb..5c8fe0f449 100644 --- a/src/Engine/WorkerCodec.php +++ b/src/Engine/WorkerCodec.php @@ -7,19 +7,24 @@ namespace DressCode\Engine; +use DressCode\Config\{Layer, LayerKind}; use DressCode\{FileResult, Risk, Rule, Severity, Violation}; use function is_array, is_string; /** - * The result of a file as a worker sends it to the parent: the output only where it differs from the code, which - * the parent has, the output and the path base64-encoded since neither need be UTF-8. + * The result of a file as a worker sends it to the parent, with what it measured for `--profile`: the output only + * where it differs from the code, which the parent has, the output and the path base64-encoded since neither need + * be UTF-8. * @internal */ final class WorkerCodec { - /** @return array */ - public static function encode(FileResult $result): array + /** + * @param ?array $profile see `Profiler::takeRecords()` + * @return array + */ + public static function encode(FileResult $result, ?array $profile): array { return [ 'path' => base64_encode($result->path), @@ -37,6 +42,7 @@ public static function encode(FileResult $result): array 'cached' => $result->cached, 'removedImports' => $result->removedImports, 'mutatedRules' => $result->mutatedRules, + 'profile' => $profile, ]; } @@ -44,11 +50,12 @@ public static function encode(FileResult $result): array /** * @param array $data as `encode()` made it * @param string $code the content the parent handed the worker + * @return array{FileResult, ?array} the result and what the worker measured with it */ - public static function decode(array $data, string $code): FileResult + public static function decode(array $data, string $code): array { $output = $data['output']; - return new FileResult( + $result = new FileResult( path: (string) base64_decode((string) $data['path'], strict: true), code: $code, output: $output === true ? $code : ($output === null ? null : (string) base64_decode((string) $output, strict: true)), @@ -75,11 +82,12 @@ public static function decode(array $data, string $code): FileResult ], is_array($data['removedImports']) ? $data['removedImports'] : [])), mutatedRules: is_array($data['mutatedRules']) ? array_values(array_filter($data['mutatedRules'], self::isRule(...))) : [], ); + return [$result, is_array($data['profile']) ? $data['profile'] : null]; } /** @return array */ - private static function encodeViolation(Violation $violation): array + public static function encodeViolation(Violation $violation): array { return [ 'decision' => $violation->decision, @@ -96,12 +104,23 @@ private static function encodeViolation(Violation $violation): array 'offset' => $violation->offset, 'length' => $violation->length, 'originalLines' => $violation->originalLines, + 'source' => $violation->source === null ? null : [ + $violation->source->name, + $violation->source->package, + $violation->source->decision, + $violation->source->library, + $violation->source->since, + $violation->source->from, + ], ]; } - /** @return list */ - private static function decodeViolations(mixed $data): array + /** + * @param mixed $data a list of what `encodeViolation()` made + * @return list + */ + public static function decodeViolations(mixed $data): array { return array_values(array_map(fn(array $item) => new Violation( (string) $item['decision'], @@ -118,10 +137,19 @@ private static function decodeViolations(mixed $data): array $item['offset'] === null ? null : (int) $item['offset'], $item['length'] === null ? null : (int) $item['length'], is_array($item['originalLines']) ? [(int) $item['originalLines'][0], (int) $item['originalLines'][1]] : null, + is_array($item['source']) ? self::decodeSource($item['source']) : null, ), is_array($data) ? $data : [])); } + /** @param array $data */ + private static function decodeSource(array $data): Layer + { + [$name, $package, $decision, $library, $since, $from] = array_map(fn($value) => $value === null ? null : (string) $value, $data); + return new Layer(LayerKind::Package, $name, $package, $decision, $library, $since, $from); + } + + /** @phpstan-assert-if-true class-string $class */ private static function isRule(mixed $class): bool { diff --git a/src/Engine/WorkerPool.php b/src/Engine/WorkerPool.php index 29ace2cb0a..59525aa59d 100644 --- a/src/Engine/WorkerPool.php +++ b/src/Engine/WorkerPool.php @@ -8,7 +8,7 @@ namespace DressCode\Engine; use DressCode\FileResult; -use function array_key_exists, count, function_exists, in_array, is_array, strlen; +use function array_key_exists, count, dirname, function_exists, in_array, is_array, strlen; use const PHP_OS_FAMILY, PHP_SAPI; @@ -63,6 +63,9 @@ final class WorkerPool /** @var list */ private array $queue = []; + /** @var array workers asked for what they measured last, by socket id */ + private array $finishing = []; + /** @var array the files the results depend on, as the workers sent them */ private array $dependencies = []; @@ -76,16 +79,28 @@ public function __construct( private readonly int $jobs, /** working directory of the workers */ private readonly ?string $cwd = null, - /** seconds a worker may spend on one file before the run fails, since a rule has most likely looped */ + /** seconds a worker may spend on one file before the run fails */ private readonly int $taskTimeout = 300, /** seconds a worker may take to connect, the first one filling the cache the others share among them */ private readonly int $connectTimeout = 300, + /** with it, every worker hands over what it measured last once nothing is left, one that got no file among them */ + private readonly ?Profiler $profiler = null, /** the first worker fills a cache the others share before it connects, and they start after that */ private readonly bool $warmFirst = false, ) { } + /** + * The workers a run of the files takes by default: a worker costs about the processing of a few files to start, so one + * for every four files at most, and no more than the processors. + */ + public static function countDefaultJobs(int $files): int + { + return max(1, min(self::detectCpuCount(), intdiv($files, 4))); + } + + /** Processors the machine has, 1 when unknown. */ public static function detectCpuCount(): int { @@ -102,6 +117,16 @@ public static function detectCpuCount(): int } + /** + * The program of this very package, which a process of DressCode is started as: never the one the process itself was + * started as, which for a test or an application embedding DressCode is another program. + */ + public static function locateProgram(): string + { + return \Phar::running(returnPhar: false) ?: dirname(__DIR__, 2) . '/bin/dresscode'; + } + + /** * The PHP a process of DressCode is started with: the same binary with the same ini file, the binary alone loading the * default one, and the settings the process has beyond it; null where no CLI binary is found to start one. @@ -190,7 +215,7 @@ public function process(array $paths, \Closure $read, ?\Closure $onProgress = nu $this->workers[] = $this->spawn($address); } - while ($done < count($paths)) { + while ($done < count($paths) || $this->isFinishing()) { foreach ($this->await(watched: $onProgress !== null) as $stream) { foreach ($this->receive((int) $stream) as $path => $result) { $done++; @@ -407,6 +432,12 @@ private function receive(int $id): array while (($end = strpos($buffer, "\n")) !== false) { $data = json_decode(substr($buffer, 0, $end), associative: true); $buffer = substr($buffer, $end + 1); + if (isset($this->finishing[$id]) && is_array($data['profile'] ?? null)) { + $this->profiler?->merge($data['profile']); + $this->disconnect($id); + break; + } + [$path, , $code] = $this->inProgress[$id] ?? [null, null, '']; if (!is_array($data) || $path === null || ($data['path'] ?? null) !== base64_encode($path)) { throw new \RuntimeException('A worker sent an unexpected message.' . $this->collectErrors()); @@ -421,7 +452,11 @@ private function receive(int $id): array $this->warnings[(string) $warning] = true; } - $results[$path] = WorkerCodec::decode($data, $code); + [$results[$path], $profile] = WorkerCodec::decode($data, $code); + if ($profile !== null) { + $this->profiler?->merge($profile); + } + $this->assign($id); } @@ -435,11 +470,15 @@ private function receive(int $id): array } - /** Hands the next path to the worker, or closes its connection when there is none. */ + /** Hands the next path to the worker; when there is none, asks it for what it measured last, or closes its connection. */ private function assign(int $id): void { $path = array_shift($this->queue); - if ($path === null) { + if ($path === null && $this->profiler !== null) { + $this->finishing[$id] = true; + fwrite($this->sockets[$id], json_encode(['finish' => true], JSON_THROW_ON_ERROR) . "\n"); + return; + } elseif ($path === null) { $this->disconnect($id); return; } @@ -465,7 +504,25 @@ private function getInProgress(): array private function disconnect(int $id): void { fclose($this->sockets[$id]); - unset($this->sockets[$id], $this->inProgress[$id], $this->buffers[$id]); + unset($this->sockets[$id], $this->inProgress[$id], $this->buffers[$id], $this->finishing[$id]); + } + + + /** + * Whether the run still waits for what the workers measured last: from one asked for it, and from one still + * starting, which gets nothing to process but has its peak memory. + */ + private function isFinishing(): bool + { + if ($this->profiler === null) { + return false; + } elseif ($this->finishing !== []) { + return true; + } + + // which process a connection belongs to is unknown, so a worker done with its work is waited for too, until it exits + return $this->accepted < count($this->workers) + && array_any($this->workers, fn(array $worker) => proc_get_status($worker[0])['running']); } @@ -507,7 +564,7 @@ private function checkWorkers(bool $resultsMissing): void foreach ($this->inProgress as [$path, $since]) { if (microtime(as_float: true) - $since > $this->taskTimeout) { - throw new \RuntimeException("A worker has spent more than $this->taskTimeout s on `$path`; a rule has most likely looped." . $this->collectErrors()); + throw new \RuntimeException("A worker process has not answered about `$path` within $this->taskTimeout s: a rule may loop on it, or the answer does not reach the main process. Run with `--jobs 1`, which uses no workers: if it finishes, the rules are fine." . $this->collectErrors()); } } diff --git a/src/Measuring/InProcessProbeRunner.php b/src/Measuring/InProcessProbeRunner.php index 41889eb025..f9225661c0 100644 --- a/src/Measuring/InProcessProbeRunner.php +++ b/src/Measuring/InProcessProbeRunner.php @@ -10,7 +10,7 @@ use DressCode\Config\{Loader, RunnerFactory}; use DressCode\ConfigurationException; use DressCode\Engine\Runner; -use DressCode\Reporters\NullReporter; +use DressCode\Reporters\CollectingReporter; use Nette\Neon\Neon; use Nette\Utils\FileSystem; use function count; @@ -39,8 +39,9 @@ public function run(array $probes): array try { foreach ($probes as $key => $probe) { [$runner, $paths] = $this->createRunner($probe, $file); - $run = $runner->run($runner->files->findFiles($paths), fix: false, reporter: new NullReporter); - $results[$key] = ProbeResult::fromRun($run); + $collected = new CollectingReporter; + $run = $runner->run($runner->files->findFiles($paths), fix: false, reporter: $collected); + $results[$key] = ProbeResult::fromRun($run, $collected->violations); ($this->onProgress)?->__invoke(count($results), count($probes)); } } finally { diff --git a/src/Measuring/ProbeResult.php b/src/Measuring/ProbeResult.php index 5cd55b7fbf..4b3618beeb 100644 --- a/src/Measuring/ProbeResult.php +++ b/src/Measuring/ProbeResult.php @@ -8,6 +8,7 @@ namespace DressCode\Measuring; use DressCode\Engine\RunResult; +use DressCode\Violation; use function count, is_array; @@ -43,12 +44,13 @@ public function __construct( } - public static function fromRun(RunResult $run): self + /** @param array> $found the path => what the file violates */ + public static function fromRun(RunResult $run, array $found): self { $files = []; foreach ($run->files as $result) { $violations = []; - foreach ($result->violations as $violation) { + foreach ($found[$result->path] ?? [] as $violation) { $violations[] = [$violation->decision, $violation->derivedFrom !== null, new Finding( $result->path, $violation->line, diff --git a/src/Measuring/ProcessProbeRunner.php b/src/Measuring/ProcessProbeRunner.php index a382d062d6..915a5a7234 100644 --- a/src/Measuring/ProcessProbeRunner.php +++ b/src/Measuring/ProcessProbeRunner.php @@ -10,7 +10,7 @@ use DressCode\Engine\{ProcessRunner, WorkerPool}; use Nette\Neon\Neon; use Nette\Utils\FileSystem; -use function count, dirname, is_array; +use function count, is_array; use const PHP_OS_FAMILY; @@ -51,8 +51,7 @@ public function __construct( */ public static function create(string $root, ?\Closure $onProgress = null, ?int $processors = null): self { - $script = \Phar::running(returnPhar: false) ?: dirname(__DIR__, 2) . '/bin/dresscode'; - $command = [...WorkerPool::buildPhpCommand() ?? [PHP_BINARY], $script]; + $command = [...WorkerPool::buildPhpCommand() ?? [PHP_BINARY], WorkerPool::locateProgram()]; return new self($root, $command, $processors ?? WorkerPool::detectCpuCount(), $onProgress); } diff --git a/src/Reporters/CollectingReporter.php b/src/Reporters/CollectingReporter.php new file mode 100644 index 0000000000..d163e2d099 --- /dev/null +++ b/src/Reporters/CollectingReporter.php @@ -0,0 +1,41 @@ +> the path => what the code of the file violates, a clean file left out */ + public private(set) array $violations = []; + + + public function start(RunInfo $run): void + { + } + + + public function reportFile(FileResult $result): void + { + if ($result->violations !== []) { + $this->violations[$result->path] = $result->violations; + } + } + + + public function finish(RunResult $result): void + { + } +} diff --git a/src/Reporters/ConsoleReporter.php b/src/Reporters/ConsoleReporter.php index 012ef2aa48..559da5f88c 100644 --- a/src/Reporters/ConsoleReporter.php +++ b/src/Reporters/ConsoleReporter.php @@ -69,6 +69,8 @@ public function __construct( private readonly string $cwd = '', /** @var ?\Closure(string): ?string the path of a decision => the address of its page */ private readonly ?\Closure $findDecisionUrl = null, + /** the command whose `--ask-risky` decides the risky fixes left */ + private readonly string $command = 'fix', ) { } @@ -366,11 +368,11 @@ private function formatRefused(Risk $risk, RunResult $result): string : 'run `dresscode init`, which lists what the namespaces declare, or set `nameResolution: certain` if they declare nothing'), Risk::TypeUnknown => match ($this->typeAnalysis) { TypeAnalysisStatus::Available => "$wait, the type is unknown: set `typeAnalysis: phpstan`", - TypeAnalysisStatus::Enabled => "$wait, not even the types tell: check $them with `fix --ask-risky`", - TypeAnalysisStatus::Unavailable => "$wait, the type is unknown: check $them with `fix --ask-risky`", + TypeAnalysisStatus::Enabled => "$wait, not even the types tell: check $them with `$this->command --ask-risky`", + TypeAnalysisStatus::Unavailable => "$wait, the type is unknown: check $them with `$this->command --ask-risky`", }, Risk::BehaviorChanges => Helpers::formatCount($count, 'risky fix changes', 'risky fixes change') - . " what the code does: decide $them with `fix --ask-risky`, or accept $decisions in `fixRisky`", + . " what the code does: decide $them with `$this->command --ask-risky`, or accept $decisions in `fixRisky`", }; $docs = match ($risk) { Risk::TypeUnknown => 'types#enable', @@ -396,7 +398,7 @@ private function formatVerdict(RunResult $result): string $failures = $result->countFailures(); $affected = count(array_filter( $result->files, - fn(FileSummary $f) => $f->violations || $f->syntaxError !== null || $f->failure !== null, + fn(FileSummary $f) => $f->violations->count() > 0 || $f->syntaxError !== null || $f->failure !== null, )); $derived = $result->countDerived(Severity::Error); diff --git a/src/Reporters/JsonReporter.php b/src/Reporters/JsonReporter.php index 13c05a106c..133105445a 100644 --- a/src/Reporters/JsonReporter.php +++ b/src/Reporters/JsonReporter.php @@ -104,6 +104,12 @@ private static function formatViolation(Violation $violation, string $text): arr 'because' => $violation->because, 'fingerprint' => $violation->fingerprint, 'derivedFrom' => $violation->derivedFrom, + 'source' => $violation->source === null ? null : [ + 'package' => $violation->source->package, + 'library' => $violation->source->library, + 'since' => $violation->source->since, + 'from' => $violation->source->from, + ], ]; } diff --git a/src/RuleContext.php b/src/RuleContext.php index 9b6fbfd961..53a6a19872 100644 --- a/src/RuleContext.php +++ b/src/RuleContext.php @@ -73,6 +73,8 @@ public function __construct( * false comes back whatever the run allows, and a mutation after it breaks the contract. * `$decision` is the path of the decision the occurrence violates, which only a rule of one requirement leaves * out; one the run does not report, being `keep` or narrowed away, records nothing and returns false. + * `$source` is the section of the upgrading data of a package whose entry the occurrence is of, as a rule reading + * a map gets it from `Values::getEntryOrigin()`. */ public function report( Node|Token $at, @@ -85,6 +87,7 @@ public function report( bool $byLine = false, bool $fixable = true, ?string $because = null, + ?Config\Layer $source = null, ): bool { if ($trivia === null && $lineInTrivia !== 0) { @@ -113,6 +116,7 @@ public function report( fixable: $fixable, because: $because, lineInTrivia: $lineInTrivia, + source: $source, ); } @@ -188,6 +192,7 @@ private function record( bool $fixable = true, ?string $because = null, int $lineInTrivia = 0, + ?Config\Layer $source = null, ): bool { if ($this->policy->strict && $because !== null && $risk === null) { @@ -245,6 +250,7 @@ private function record( construct: $construct, lineInTrivia: $lineInTrivia, span: $this->spans?->find($at, $trivia, $lineInTrivia, $gap, $follows), + source: $source, ); return $fixable && !$refused && !$left; } diff --git a/src/Rules/Upgrading/AnnotationMap.php b/src/Rules/Upgrading/AnnotationMap.php index b5a3a01071..854817cf2a 100644 --- a/src/Rules/Upgrading/AnnotationMap.php +++ b/src/Rules/Upgrading/AnnotationMap.php @@ -8,6 +8,7 @@ namespace DressCode\Rules\Upgrading; use DressCode\Analyses\PhpDoc; +use DressCode\Config\Layer; use DressCode\{QualifiedNames, RuleContext, Values}; use DressCode\Upgrading\MemberMapGrammar; use PHPStan\PhpDocParser\Ast\PhpDoc\PhpDocTagNode; @@ -52,7 +53,10 @@ private function __construct( private array $attributes, /** @var array lowercased class of an attribute, fully qualified => the attribute written instead */ private array $replacedAttributes, - /** @var array lowercased namespace of annotations => the namespace of the attributes written instead */ + /** + * @var array lowercased namespace of annotations => the namespace of the attributes + * written instead and the section of the upgrading data that laid it + */ private array $namespaces, /** @var array lowercased classes withdrawn from the map, which no namespace reaches */ private array $withdrawn = [], @@ -64,11 +68,12 @@ public static function fromValues(Values $values): self { $attributes = $replacedAttributes = $namespaces = []; foreach ($values->readMap(MemberMapGrammar::AttributeForAnnotation) as $key => $code) { + $origin = $values->getEntryOrigin(MemberMapGrammar::AttributeForAnnotation, (string) $key); if (str_ends_with((string) $key, '*')) { if (($namespace = AttributeTarget::findNamespace($code)) !== null) { - $namespaces[strtolower(trim((string) $key, '\\*'))] = $namespace; + $namespaces[strtolower(trim((string) $key, '\\*'))] = [$namespace, $origin]; } - } elseif (($target = AttributeTarget::fromCode($code)) === null) { + } elseif (($target = AttributeTarget::fromCode($code, $origin)) === null) { continue; } elseif (str_contains((string) $key, '\\')) { $replacedAttributes[strtolower(ltrim((string) $key, '\\'))] = $target; @@ -110,9 +115,12 @@ public function findAttributeOfClass(?string $class): ?AttributeTarget } $namespace = QualifiedNames::extractNamespace($class); - $target = $this->namespaces[strtolower($namespace)] ?? null; - return $this->replacedAttributes[strtolower($class)] - ?? ($target === null ? null : new AttributeTarget($target . substr($class, strlen($namespace)), fromNamespace: true)); + [$target, $origin] = $this->namespaces[strtolower($namespace)] ?? [null, null]; + return $this->replacedAttributes[strtolower($class)] ?? ($target === null ? null : new AttributeTarget( + $target . substr($class, strlen($namespace)), + fromNamespace: true, + origin: $origin, + )); } diff --git a/src/Rules/Upgrading/AttributeForAnnotationRule.php b/src/Rules/Upgrading/AttributeForAnnotationRule.php index ba8cc1550a..914a438fa8 100644 --- a/src/Rules/Upgrading/AttributeForAnnotationRule.php +++ b/src/Rules/Upgrading/AttributeForAnnotationRule.php @@ -120,9 +120,9 @@ public function enter(Node|Token $node, RuleContext $context): void $message = "Annotation `$child->name` is replaced by the attribute " . Violation::formatCode("#[$attribute->class$attribute->arguments]"); if ($refusal !== null) { - $context->report($node, $message . $refusal . '.', trivia: $docComment, fixable: false); + $context->report($node, $message . $refusal . '.', trivia: $docComment, fixable: false, source: $attribute->origin); $kept[] = $child; - } elseif ($context->report($node, $message . '.', trivia: $docComment)) { + } elseif ($context->report($node, $message . '.', trivia: $docComment, source: $attribute->origin)) { [$arguments] = $this->renderArguments( $child, $attribute, @@ -206,6 +206,7 @@ private function enterAttribute(AttributeNode $node, RuleContext $context): void . ($refusal ?? '') . '.', fixable: $refusal === null, + source: $attribute->origin, )) { // the arguments go over as they are, the library reading them the same way $code = CodeWriter::writeClass($attribute->class, $node, $context) . ($arguments === '' ? $attribute->arguments : $arguments); diff --git a/src/Rules/Upgrading/AttributeForMemberEntry.php b/src/Rules/Upgrading/AttributeForMemberEntry.php index 85fbc67f28..51972422bc 100644 --- a/src/Rules/Upgrading/AttributeForMemberEntry.php +++ b/src/Rules/Upgrading/AttributeForMemberEntry.php @@ -7,6 +7,7 @@ namespace DressCode\Rules\Upgrading; +use DressCode\Config\Layer; use DressCode\Upgrading\MemberMapGrammar; use DressCode\{Values, Violation}; use PhpSyntax\{Builder, ParseException}; @@ -34,6 +35,8 @@ public function __construct( public string $arguments, /** @var ?array{mixed} the default of the property the entry stands for alone, wrapped so that null is one too */ public ?array $literal = null, + /** the section of the upgrading data of a package that laid the entry */ + public ?Layer $origin = null, ) { } @@ -47,7 +50,8 @@ public static function fromValues(Values $values): array { $entries = []; foreach ($values->readMap(MemberMapGrammar::AttributeForMember) as $key => $value) { - $entries[] = self::fromEntry((string) $key, $value); + $origin = $values->getEntryOrigin(MemberMapGrammar::AttributeForMember, (string) $key); + $entries[] = self::fromEntry((string) $key, $value, $origin); } usort($entries, fn(self $a, self $b) => ($b->literal !== null) <=> ($a->literal !== null)); @@ -59,7 +63,7 @@ public static function fromValues(Values $values): array * The entry of the map, its key the member or the interface and its value the attribute. * @throws \InvalidArgumentException saying what of it is not written as the map takes it */ - public static function fromEntry(string $key, string $value): self + public static function fromEntry(string $key, string $value, ?Layer $origin = null): self { if (!preg_match('~^' . self::ClassPattern . '(\(.*\))?$~Ds', trim($value), $attribute)) { throw new \InvalidArgumentException('The attribute ' . Violation::formatCode($value) . ' for ' . Violation::formatCode($key) . ' is not written as `Class` or `Class(arguments)`.'); @@ -88,6 +92,7 @@ public static function fromEntry(string $key, string $value): self $attribute[1], $arguments, isset($m[3]) ? [self::readLiteral($m[3], $key)] : null, + $origin, ), (bool) preg_match('~^' . self::ClassPattern . '::(\w+)\(\)$~D', $key, $m) => new self( AttributeForMemberKind::Method, @@ -95,6 +100,7 @@ public static function fromEntry(string $key, string $value): self $m[2], $attribute[1], $arguments, + origin: $origin, ), (bool) preg_match('~^' . self::ClassPattern . '$~D', $key, $m) => new self( AttributeForMemberKind::Interface, @@ -102,6 +108,7 @@ public static function fromEntry(string $key, string $value): self '', $attribute[1], $arguments, + origin: $origin, ), default => throw new \InvalidArgumentException('The member ' . Violation::formatCode($key) . " is not written as `Class::\$name`, `'Class::\$name = literal'`, `Class::method()` or `Interface`."), }; diff --git a/src/Rules/Upgrading/AttributeForMemberRule.php b/src/Rules/Upgrading/AttributeForMemberRule.php index e50d76239d..64c5e46b59 100644 --- a/src/Rules/Upgrading/AttributeForMemberRule.php +++ b/src/Rules/Upgrading/AttributeForMemberRule.php @@ -202,7 +202,15 @@ private function write(ClassNode $class, array $found, RuleContext $context): vo $planned[strtolower($attribute)] = [$attribute, [...($planned[strtolower($attribute)][1] ?? []), ...$arguments]]; } - $reports[] = [$at, "$described is replaced by the attribute `#[$attribute]`", $refusal, $member, $attribute, $arguments]; + $reports[] = [ + $at, + "$described is replaced by the attribute `#[$attribute]`", + $refusal, + $member, + $attribute, + $arguments, + $entry->origin, + ]; } // the members of one attribute together must give every argument it requires @@ -217,11 +225,11 @@ private function write(ClassNode $class, array $found, RuleContext $context): vo } $attributes = $removed = []; - foreach ($reports as [$at, $message, $refusal, $member, $attribute, $arguments]) { + foreach ($reports as [$at, $message, $refusal, $member, $attribute, $arguments, $source]) { $refusal ??= $missing[strtolower($attribute)] ?? null; if ($refusal !== null) { - $context->report($at, $message . $refusal . '.', fixable: false); - } elseif ($context->report($at, $message . '.')) { + $context->report($at, $message . $refusal . '.', fixable: false, source: $source); + } elseif ($context->report($at, $message . '.', source: $source)) { $attributes[strtolower($attribute)] = [$attribute, [...($attributes[strtolower($attribute)][1] ?? []), ...$arguments]]; $removed[] = $member; } diff --git a/src/Rules/Upgrading/AttributeTarget.php b/src/Rules/Upgrading/AttributeTarget.php index 8afafad4f2..6adda97fce 100644 --- a/src/Rules/Upgrading/AttributeTarget.php +++ b/src/Rules/Upgrading/AttributeTarget.php @@ -7,6 +7,8 @@ namespace DressCode\Rules\Upgrading; +use DressCode\Config\Layer; + /** * What attributeForAnnotation writes instead of an annotation or an attribute. @@ -26,14 +28,16 @@ public function __construct( public string $arguments = '', /** a namespace of the map gave the class, which may therefore not exist */ public bool $fromNamespace = false, + /** the section of the upgrading data of a package that laid the entry */ + public ?Layer $origin = null, ) { } /** The attribute written as `Class` or `Class(arguments)`, its class fully qualified; null for code of another shape. */ - public static function fromCode(string $code): ?self + public static function fromCode(string $code, ?Layer $origin = null): ?self { - return preg_match(self::Pattern, $code, $m) ? new self($m[1], $m[2] ?? '') : null; + return preg_match(self::Pattern, $code, $m) ? new self($m[1], $m[2] ?? '', origin: $origin) : null; } diff --git a/src/Rules/Upgrading/CallTemplate.php b/src/Rules/Upgrading/CallTemplate.php index f83e170073..562486ac97 100644 --- a/src/Rules/Upgrading/CallTemplate.php +++ b/src/Rules/Upgrading/CallTemplate.php @@ -7,6 +7,7 @@ namespace DressCode\Rules\Upgrading; +use DressCode\Config\Layer; use DressCode\{RuleContext, Violation}; use DressCode\Rules\NodeHelpers; use DressCode\Upgrading\{ @@ -309,13 +310,14 @@ public function describe(string $subject): string * Takes the call doing nothing away with its statement, where neither what it is made on nor its arguments would do * anything when evaluated; a call whose value is used, one that is the body of a construct without braces and one * holding a comment are only reported. The subject is the called function or member as the message names it, the - * decision the one it is reported under, and the uncertainty why the name of a function may call another one - * (`GlobalCalls::findUncertainty()`). + * decision the one it is reported under with the section of the upgrading data the entry came with, and the + * uncertainty why the name of a function may call another one (`GlobalCalls::findUncertainty()`). */ public function removeCall( FunctionCallNode|MethodCallNode|StaticMethodCallNode $call, string $subject, string $decision, + ?Layer $source, RuleContext $context, ?string $uncertainty = null, ): void @@ -340,6 +342,7 @@ public function removeCall( $call->name, $this->describe($subject) . "$refusal.", decision: $decision, + source: $source, fixable: $refusal === null, risk: NodeHelpers::findRisk($behaviorChange, $uncertainty), because: $behaviorChange ?? $uncertainty, diff --git a/src/Rules/Upgrading/ClassReplacement.php b/src/Rules/Upgrading/ClassReplacement.php index 10dc1f3b0f..25bf93bcff 100644 --- a/src/Rules/Upgrading/ClassReplacement.php +++ b/src/Rules/Upgrading/ClassReplacement.php @@ -9,6 +9,7 @@ use DressCode\Analyses\{MemberKind, PhpDoc, Types}; use DressCode\{CodeWriter, QualifiedNames, Risk, RuleContext, Tristate}; +use DressCode\Config\Layer; use DressCode\Rules\Namespaces\NameReferences; use DressCode\Rules\NodeHelpers; use PHPStan\PhpDocParser\Lexer\Lexer; @@ -44,10 +45,10 @@ final class ClassReplacement /** * Reports every reference of a class the closure has something to say about, and rewrites the ones it names * a replacement for and the report allows. - * @param \Closure(string): ?array{0: string, 1: ?string, 2?: ?string} $find given a fully qualified class, the message, - * the class written instead, null for none, and why writing it may change what the code does, which makes the fix - * risky; null for a class that is left alone - * @param \Closure(string, ?array{string, MemberKind}, Token, list): (array{0: string, 1: ?string, 2?: ?string}|false|null) $findInDocs + * @param \Closure(string): ?array{0: string, 1: ?string, 2?: ?string, 3?: ?Layer} $find given a fully qualified class, + * the message, the class written instead, null for none, why writing it may change what the code does, which makes + * the fix risky, and the section of the upgrading data that names the class; null for a class that is left alone + * @param \Closure(string, ?array{string, MemberKind}, Token, list): (array{0: string, 1: ?string, 2?: ?string, 3?: ?Layer}|false|null) $findInDocs * the same as `$find` for a class a doc comment names, with the member it names, the token holding the comment and * the lowercased classes beside it in a union type, false for one that goes on naming the class and keeps its import * @param ?\Closure(NameNode): bool $keeps whether the reference goes on naming the class, which nothing is said @@ -81,6 +82,7 @@ public static function rewriteReferences( $result[1], $result[2] ?? null, $result[1] !== null && in_array(strtolower($result[1]), $union, true), + $result[3] ?? null, ]; } } @@ -95,7 +97,7 @@ public static function rewriteReferences( if ($item instanceof UseItemNode) { $found = $item->symbolKind === SymbolKind::ClassLike ? $find($item->fullName) : null; if ($found !== null) { - $imports[] = [$item, $item->fullName, $found[0], $found[1], $found[2] ?? null]; + $imports[] = [$item, $item->fullName, $found[0], $found[1], $found[2] ?? null, $found[3] ?? null]; } } elseif ($name->symbolKind === SymbolKind::ClassLike && $name->isReference()) { @@ -115,11 +117,11 @@ public static function rewriteReferences( } elseif ( // reported before the import goes, which a reference the run leaves as it is needs $dataUse !== null - && !self::report($context, $name, $found[0], $found[1], $found[2] ?? $dataUse) + && !self::report($context, $name, $found[0], $found[1], $found[2] ?? $dataUse, $found[3] ?? null) ) { $kept[strtolower($class)] = true; } else { - $references[] = [$name, $found[0], $found[1], $found[2] ?? null, $refusal, $dataUse !== null]; + $references[] = [$name, $found[0], $found[1], $found[2] ?? null, $refusal, $found[3] ?? null, $dataUse !== null]; if ($refusal !== null) { $kept[strtolower($class)] = true; // the reference left as it is needs its import } @@ -129,10 +131,10 @@ public static function rewriteReferences( // an annotation read as an attribute resolves through the import until it is one $kept += $annotations?->findAnnotatedClasses($scope, $context) ?? []; - foreach ($imports as [$item, $class, $message, $new, $because]) { + foreach ($imports as [$item, $class, $message, $new, $because, $source]) { if (isset($kept[strtolower($class)])) { continue; // the short name below goes on naming the class the import brings - } elseif (self::report($context, $item->name, $message, $new, $because) && $new !== null) { + } elseif (self::report($context, $item->name, $message, $new, $because, $source) && $new !== null) { $local = self::replaceImport($item, $new, $context); if ($local !== null) { self::shortenFullyQualified($scope, $new, $local); @@ -140,14 +142,14 @@ public static function rewriteReferences( } } - foreach ($references as [$name, $message, $new, $because, $refusal, $reported]) { + foreach ($references as [$name, $message, $new, $because, $refusal, $source, $reported]) { $inList = self::findList($name); $list = $inList[0] ?? null; $named = $list === null || $new === null ? null : $lists[spl_object_id($list)] ?? []; if ($refusal !== null) { - $context->report($name, $message . $refusal . '.', fixable: false); + $context->report($name, $message . $refusal . '.', fixable: false, source: $source); - } elseif (!($reported || self::report($context, $name, $message, $new, $because)) || $new === null) { + } elseif (!($reported || self::report($context, $name, $message, $new, $because, $source)) || $new === null) { continue; } elseif ($inList !== null && isset($named[strtolower($new)])) { @@ -231,17 +233,18 @@ private static function findDocMember(array $tokens, int $index): ?array * Reports every name of a doc comment, and writes the class that replaces it where the report allows, token by * token, so that the rest of the comment stays as it is written. * @param list $tokens - * @param list $found per name the index of its token, the message, the class - * written instead, why writing it is risky and whether the union type it stands in names that class already + * @param list $found per name the index of its token, the message, + * the class written instead, why writing it is risky, whether the union type it stands in names that class already + * and the section of the upgrading data that names the class */ private static function replaceInDocComment(Token $token, Trivia $trivia, array $tokens, array $found, RuleContext $context): void { $changed = false; $unfixable = []; - foreach ($found as [$index, $message, $new, $because, $named]) { + foreach ($found as [$index, $message, $new, $because, $named, $source]) { if ($new === null || $token->parent === null) { - $unfixable[] = $message; // reported once the comment is written, nothing changing after them - } elseif (!self::report($context, $token, $message, $new, $because, $trivia)) { + $unfixable[] = [$message, $source]; // reported once the comment is written, nothing changing after them + } elseif (!self::report($context, $token, $message, $new, $because, $source, $trivia)) { continue; } elseif ($named) { foreach (self::findDocUnionSpan($tokens, $index) as $i) { @@ -263,8 +266,8 @@ private static function replaceInDocComment(Token $token, Trivia $trivia, array $token->replaceTrivia($trivia, $trivia->withText(implode('', array_column($tokens, Lexer::VALUE_OFFSET)))); } - foreach ($unfixable as $message) { - $context->report($token, $message . '.', trivia: $trivia, fixable: false); + foreach ($unfixable as [$message, $source]) { + $context->report($token, $message . '.', trivia: $trivia, fixable: false, source: $source); } } @@ -276,6 +279,7 @@ private static function report( string $message, ?string $new, ?string $because, + ?Layer $source, ?Trivia $trivia = null, ): bool { @@ -283,6 +287,7 @@ private static function report( $at, $message . '.', trivia: $trivia, + source: $source, risk: $because === null ? null : Risk::BehaviorChanges, fixable: $new !== null, because: $because, diff --git a/src/Rules/Upgrading/ForbiddenMembersRule.php b/src/Rules/Upgrading/ForbiddenMembersRule.php index 98dc997383..8c1e190837 100644 --- a/src/Rules/Upgrading/ForbiddenMembersRule.php +++ b/src/Rules/Upgrading/ForbiddenMembersRule.php @@ -9,7 +9,7 @@ use DressCode\Analyses\{MemberKind, Types}; use DressCode\{NodeRule, RuleContext, RuleInfo, Stage, Values}; -use DressCode\Upgrading\{MemberMap, MemberMapEntry, MemberMapGrammar, MemberPattern}; +use DressCode\Upgrading\{MemberMap, MemberMapEntry, MemberMapGrammar}; use PhpSyntax\Analyses\NameResolver; use PhpSyntax\{Builder, Node, Token}; use PhpSyntax\Nodes\{ClassLikeNode, IdentifierNode, ParameterNode}; @@ -49,21 +49,13 @@ final class ForbiddenMembersRule extends NodeRule { public const Map = MemberMapGrammar::ForbiddenMembers; - /** @var MemberMap the entries with the end of the message, and whether the data of a package laid it */ + /** @var MemberMap the entries with the end of the message */ private MemberMap $map; public function configure(Values $values): void { - $fromPackages = $values->findPackageEntries(self::Map); - $this->map = MemberMap::fromValues( - $values, - self::Map, - fn(?string $message, MemberPattern $pattern, string $key) => [ - $message === null ? '' : ": $message", - isset($fromPackages[$key]), - ], - ); + $this->map = MemberMap::fromValues($values, self::Map, fn(?string $message) => $message === null ? '' : ": $message"); } @@ -162,8 +154,9 @@ private function reportMember( }; $context->report( $node instanceof NewNode ? $node->class : $node->name, - "$described " . self::formatVerdict($entry->value, $types->knowsMember($pattern->class, $access->kind, $access->name)), + "$described " . self::formatVerdict($entry, $types->knowsMember($pattern->class, $access->kind, $access->name)), decision: $entry->decision, + source: $entry->origin, fixable: false, ); return true; @@ -211,8 +204,9 @@ private function enterMagic(PropertyFetchNode|ArrayAccessNode $node, RuleContext $node instanceof PropertyFetchNode ? $node->name : $node->openBracket, $entry->pattern->describe(MemberKind::Method) . ' ' - . self::formatVerdict($entry->value, $types->knowsMember($entry->pattern->class, MemberKind::Method, $method)), + . self::formatVerdict($entry, $types->knowsMember($entry->pattern->class, MemberKind::Method, $method)), decision: $entry->decision, + source: $entry->origin, fixable: false, ); } @@ -242,8 +236,9 @@ private function enterCallableValue(ArrayNode|StringNode $node, RuleContext $con $callable->literal, $entry->pattern->describe($access->kind) . ' ' - . self::formatVerdict($entry->value, $types->knowsMember($entry->pattern->class, $access->kind, $access->name)), + . self::formatVerdict($entry, $types->knowsMember($entry->pattern->class, $access->kind, $access->name)), decision: $entry->decision, + source: $entry->origin, fixable: false, ); } @@ -263,8 +258,9 @@ private function enterDeclaration(MethodNode $node, RuleContext $context): void $exists = $types->knowsMember($entry->pattern->class, $kind, $entry->pattern->name); $context->report( $node->name, - $entry->pattern->describe($kind) . ' ' . self::formatVerdict($entry->value, $exists), + $entry->pattern->describe($kind) . ' ' . self::formatVerdict($entry, $exists), decision: $entry->decision, + source: $entry->origin, fixable: false, ); } @@ -295,8 +291,9 @@ private function enterPropertyDeclaration(PropertyNode|ParameterNode $node, Rule $exists = $types->knowsMember($entry->pattern->class, $kind, $name); $context->report( $at, - $entry->pattern->describe($kind) . ' ' . self::formatVerdict($entry->value, $exists), + $entry->pattern->describe($kind) . ' ' . self::formatVerdict($entry, $exists), decision: $entry->decision, + source: $entry->origin, fixable: false, ); } @@ -307,10 +304,10 @@ private function enterPropertyDeclaration(PropertyNode|ParameterNode $node, Rule /** * What the entry says of the use, with the end of its message: a member the data of a package retired is deprecated * while the installed version still has it and removed once it has not, one of the project is forbidden. - * @param array{string, bool} $value + * @param MemberMapEntry $entry */ - private static function formatVerdict(array $value, bool $exists): string + private static function formatVerdict(MemberMapEntry $entry, bool $exists): string { - return 'is ' . Retirement::of($value[1], $exists)->value . $value[0] . '.'; + return 'is ' . Retirement::of($entry->origin !== null, $exists)->value . $entry->value . '.'; } } diff --git a/src/Rules/Upgrading/ForbiddenSymbolsRule.php b/src/Rules/Upgrading/ForbiddenSymbolsRule.php index 03bf05bbab..a228a82f61 100644 --- a/src/Rules/Upgrading/ForbiddenSymbolsRule.php +++ b/src/Rules/Upgrading/ForbiddenSymbolsRule.php @@ -8,6 +8,7 @@ namespace DressCode\Rules\Upgrading; use DressCode\Analyses\{PhpSymbols, Types}; +use DressCode\Config\Layer; use DressCode\{NodeRule, RuleContext, RuleInfo, Stage, Values}; use DressCode\Upgrading\MemberMapGrammar; use PhpSyntax\Analyses\NameResolver; @@ -45,14 +46,14 @@ final class ForbiddenSymbolsRule extends NodeRule private const Constructs = [EvalNode::class, ExitNode::class, PrintNode::class, EmptyNode::class, IssetNode::class, UnsetNode::class]; /** - * @var array lowercased class => the class as the map spells it, the end - * of the message, whether the data of a package laid it and the decision it is reported under + * @var array lowercased class => the class as the map spells it, the + * end of the message, the section of the upgrading data of a package that laid it and the decision it is reported under */ private array $classes = []; /** - * @var list regular expression, what to do instead, whether the data of a package - * laid it, the decision it is reported under + * @var list regular expression, what to do instead, the section of the + * upgrading data of a package that laid it, the decision it is reported under */ private array $functions = []; @@ -60,8 +61,8 @@ final class ForbiddenSymbolsRule extends NodeRule private array $withdrawnFunctions = []; /** - * @var list regular expression, what to do instead, whether the data of a package - * laid it, the decision it is reported under + * @var list regular expression, what to do instead, the section of the + * upgrading data of a package that laid it, the decision it is reported under */ private array $constants = []; @@ -72,12 +73,11 @@ final class ForbiddenSymbolsRule extends NodeRule public function configure(Values $values): void { $this->classes = []; - $fromPackages = $values->findPackageEntries(self::Classes); foreach ($values->readMap(self::Classes) as $class => $message) { $this->classes[strtolower(ltrim((string) $class, '\\'))] = [ ltrim((string) $class, '\\'), $message === null ? '' : ": $message", - isset($fromPackages[$class]), + $values->getEntryOrigin(self::Classes, (string) $class), $values->getEntryDecision(self::Classes, (string) $class), ]; } @@ -89,17 +89,16 @@ public function configure(Values $values): void /** * The patterns of a map of names with what to do instead, and the names withdrawn from it. - * @return array{list, array} + * @return array{list, array} */ private static function readPatterns(Values $values, string $path, bool $caseInsensitive): array { $patterns = []; - $fromPackages = $values->findPackageEntries($path); foreach ($values->readMap($path) as $pattern => $sentence) { $patterns[] = [ '~^' . str_replace('\*', '.*', preg_quote(ltrim((string) $pattern, '\\'), '~')) . '$~' . ($caseInsensitive ? 'i' : ''), $sentence, - isset($fromPackages[$pattern]), + $values->getEntryOrigin($path, (string) $pattern), $values->getEntryDecision($path, (string) $pattern), ]; } @@ -140,10 +139,10 @@ private function checkClass(NameNode $node, RuleContext $context): void $entry = $this->classes[strtolower($context->getAnalysis(NameResolver::class)->resolveClass($node))] ?? null; if ($entry !== null) { - [$class, $sentence, $fromPackage, $decision] = $entry; + [$class, $sentence, $source, $decision] = $entry; $types = $context->findAnalysis(Types::class); - $verdict = Retirement::of($fromPackage, $types === null ? null : $types->findClassName($class) !== null); - $context->report($node, "Class `$class` is $verdict->value$sentence.", decision: $decision, fixable: false); + $verdict = Retirement::of($source !== null, $types === null ? null : $types->findClassName($class) !== null); + $context->report($node, "Class `$class` is $verdict->value$sentence.", decision: $decision, fixable: false, source: $source); } } @@ -157,15 +156,21 @@ private function checkFunction(FunctionCallNode $node, RuleContext $context): vo $resolved = $context->getAnalysis(NameResolver::class)->resolveFunction($node->name); $entry = isset($this->withdrawnFunctions[strtolower($resolved)]) ? null : self::findEntry($this->functions, $resolved); if ($entry !== null) { - [$sentence, $fromPackage, $decision] = $entry; + [$sentence, $source, $decision] = $entry; $types = $context->findAnalysis(Types::class); $php = $context->getAnalysis(PhpSymbols::class); - $verdict = Retirement::of($fromPackage, match (true) { + $verdict = Retirement::of($source !== null, match (true) { $types !== null => $types->findFunctionName($resolved) !== null, $php->isBuiltinFunction($resolved) => $php->isBuiltinFunction($resolved, $context->phpVersion), default => null, }); - $context->report($node->name, "Function `$resolved()` is $verdict->value$sentence.", decision: $decision, fixable: false); + $context->report( + $node->name, + "Function `$resolved()` is $verdict->value$sentence.", + decision: $decision, + fixable: false, + source: $source, + ); } } @@ -180,9 +185,15 @@ private function checkConstruct(Node $node, RuleContext $context): void $name = strtolower($keyword->text); $entry = isset($this->withdrawnFunctions[$name]) ? null : self::findEntry($this->functions, $name); if ($entry !== null) { - [$sentence, $fromPackage, $decision] = $entry; - $verdict = Retirement::of($fromPackage, exists: true); - $context->report($keyword, "Function `$name()` is $verdict->value$sentence.", decision: $decision, fixable: false); + [$sentence, $source, $decision] = $entry; + $verdict = Retirement::of($source !== null, exists: true); + $context->report( + $keyword, + "Function `$name()` is $verdict->value$sentence.", + decision: $decision, + fixable: false, + source: $source, + ); } } @@ -196,29 +207,36 @@ private function checkConstant(NameNode $node, RuleContext $context): void $resolved = $context->getAnalysis(NameResolver::class)->resolveConstant($node); $entry = isset($this->withdrawnConstants[$resolved]) ? null : self::findEntry($this->constants, $resolved); if ($entry !== null) { - [$sentence, $fromPackage, $decision] = $entry; + [$sentence, $source, $decision] = $entry; $types = $context->findAnalysis(Types::class); - $verdict = Retirement::of($fromPackage, match (true) { + $verdict = Retirement::of($source !== null, match (true) { $types !== null => $types->knowsConstant($resolved), $context->getAnalysis(PhpSymbols::class)->isBuiltinConstant($resolved) => true, default => null, }); - $context->report($node, "Constant `$resolved` is $verdict->value$sentence.", decision: $decision, fixable: false); + $context->report( + $node, + "Constant `$resolved` is $verdict->value$sentence.", + decision: $decision, + fixable: false, + source: $source, + ); } } /** * The first pattern the name matches, as the end of its message, empty where its entry says nothing to do instead, - * whether the data of a package laid it and the decision it is reported under; null where none matches. - * @param list $patterns - * @return ?array{string, bool, string} + * the section of the upgrading data of a package that laid it and the decision it is reported under; null where none + * matches. + * @param list $patterns + * @return ?array{string, ?Layer, string} */ private static function findEntry(array $patterns, string $name): ?array { - foreach ($patterns as [$pattern, $sentence, $fromPackage, $decision]) { + foreach ($patterns as [$pattern, $sentence, $source, $decision]) { if (preg_match($pattern, $name)) { - return [$sentence === null ? '' : ": $sentence", $fromPackage, $decision]; + return [$sentence === null ? '' : ": $sentence", $source, $decision]; } } diff --git a/src/Rules/Upgrading/ReplacedCallsRule.php b/src/Rules/Upgrading/ReplacedCallsRule.php index c2749eef6d..ac320c2d87 100644 --- a/src/Rules/Upgrading/ReplacedCallsRule.php +++ b/src/Rules/Upgrading/ReplacedCallsRule.php @@ -166,12 +166,17 @@ private function enterCall(MethodCallNode|StaticMethodCallNode|NewNode $node, Ru return; } - [$pattern, $template, $decision] = [$found->entry->pattern, $found->entry->value, $found->entry->decision]; + [$pattern, $template, $decision, $source] = [ + $found->entry->pattern, + $found->entry->value, + $found->entry->decision, + $found->entry->origin, + ]; [$bindings, $access] = [$found->bindings, $found->access]; assert($bindings !== null); if ($template->removesCall()) { assert(!$node instanceof NewNode); // only a method is removed - $template->removeCall($node, $pattern->describeAccess($access, $node), $decision, $context); + $template->removeCall($node, $pattern->describeAccess($access, $node), $decision, $source, $context); return; } @@ -208,7 +213,7 @@ private function enterCall(MethodCallNode|StaticMethodCallNode|NewNode $node, Ru return; } - if ($rewrite->report($node instanceof NewNode ? $node->class : $node->name, $message, $decision, $context)) { + if ($rewrite->report($node instanceof NewNode ? $node->class : $node->name, $message, $decision, $source, $context)) { $node->replaceWithExpression($rewrite->write($node, $context)); } } @@ -248,7 +253,7 @@ private function enterCallable(MethodCallNode|StaticMethodCallNode $node, RuleCo }; $message = self::describeCall($node, $access, $pattern, $template); - if ($rewrite->report($node->name, $message, $entry->decision, $context)) { + if ($rewrite->report($node->name, $message, $entry->decision, $entry->origin, $context)) { $node->replaceWithExpression((new Builder)->expression('fn() => $value', value: $rewrite->write($node, $context))); } } @@ -305,6 +310,7 @@ private function reportUnbound(MethodCallNode|StaticMethodCallNode|NewNode $node $node instanceof NewNode ? $node->class : $node->name, self::describeCall($node, $access, $entry->pattern, $entry->value) . ", but $reason.", decision: $entry->decision, + source: $entry->origin, fixable: false, ); } @@ -343,6 +349,7 @@ private function enterCallableValue(ArrayNode|StringNode $node, RuleContext $con $entry->value->describe($entry->pattern->describe($access->kind)) . ', but no expression stands for a callable value.', decision: $entry->decision, + source: $entry->origin, fixable: false, ); } @@ -403,7 +410,7 @@ private function enterAccess(PropertyFetchNode|StaticPropertyFetchNode|ArrayAcce return; } - [$message, $decision, $template, $bindings, $arguments] = $found; + [$message, $entry, $template, $bindings, $arguments] = $found; $rewrite = match (true) { $use === 'written' => new Rewrite(null, ', but it is written to, which a call cannot be'), $template === null => new Rewrite(null, ', but nothing says what a read of it becomes'), @@ -420,7 +427,13 @@ private function enterAccess(PropertyFetchNode|StaticPropertyFetchNode|ArrayAcce } $rewrite = self::fitPlace($node, $rewrite); - if ($rewrite->report($node instanceof ArrayAccessNode ? $node->openBracket : $node->name, $message, $decision, $context)) { + if ($rewrite->report( + $node instanceof ArrayAccessNode ? $node->openBracket : $node->name, + $message, + $entry->decision, + $entry->origin, + $context, + )) { $node->replaceWithExpression($rewrite->write($node, $context)); } } @@ -436,7 +449,7 @@ private function enterAssignment(AssignmentNode $node, RuleContext $context): vo return; } - [$message, $decision, $template, $bindings, $arguments] = $found; + [$message, $entry, $template, $bindings, $arguments] = $found; $rewrite = match (true) { $template === null => new Rewrite(null, ', but nothing says what an assignment to it becomes'), !$node->parent instanceof ExpressionStatementNode => new Rewrite(null, ', but the value of the assignment is used'), @@ -447,7 +460,13 @@ private function enterAssignment(AssignmentNode $node, RuleContext $context): vo static: $target instanceof StaticPropertyFetchNode, ), }; - if ($rewrite->report($target instanceof ArrayAccessNode ? $target->openBracket : $target->name, $message, $decision, $context)) { + if ($rewrite->report( + $target instanceof ArrayAccessNode ? $target->openBracket : $target->name, + $message, + $entry->decision, + $entry->origin, + $context, + )) { $node->replaceWithExpression($rewrite->write($node, $context)); } } @@ -463,7 +482,7 @@ private function enterIssetOrUnset(IssetNode|UnsetNode $node, RuleContext $conte continue; } - [$message, $decision, $template, $bindings, $arguments] = $found; + [$message, $entry, $template, $bindings, $arguments] = $found; $receiver = self::getReceiver($variable); $rewrite = match (true) { $template === null => new Rewrite( @@ -494,7 +513,7 @@ private function enterIssetOrUnset(IssetNode|UnsetNode $node, RuleContext $conte } $at = $variable instanceof PropertyFetchNode ? $variable->name : $variable->openBracket; - if (!$rewrite->report($at, $message, $decision, $context)) { + if (!$rewrite->report($at, $message, $entry->decision, $entry->origin, $context)) { continue; } elseif ($node instanceof IssetNode) { $node->replaceWithExpression($rewrite->write($node, $context)); @@ -553,6 +572,7 @@ private function enterAttribute(AttributeNode $node, RuleContext $context): void $node->name, $template->describe($found->entry->pattern->describe(MemberKind::Constructor)), $found->entry->decision, + $found->entry->origin, $context, )) { assert($new instanceof NewNode); @@ -574,6 +594,7 @@ private function enterDeclaration(MethodNode $node, RuleContext $context): void $entry->value->describe($entry->pattern->describe($kind)) . ', but a declaration is nothing an expression could stand for.', decision: $entry->decision, + source: $entry->origin, fixable: false, ); } @@ -582,12 +603,12 @@ private function enterDeclaration(MethodNode $node, RuleContext $context): void /** * What the map says of a property or an offset used the given way: the property of a key, else the magic method - * PHP calls for it, with the name or the key and the values as its arguments. The message, the decision it is - * reported under, the template or null where the key has none for that use, and what the template is instantiated - * with; null where the map says nothing. + * PHP calls for it, with the name or the key and the values as its arguments. The message, the entry deciding it, + * the template or null where the key has none for that use, and what the template is instantiated with; null where + * the map says nothing. * @param 'get'|'set'|'isset'|'unset' $use * @param list $values what the magic method gets besides the name or the key - * @return ?array{string, string, ?CallTemplate, ArgumentBindings, ArgumentListNode} + * @return ?array{string, MemberMapEntry, ?CallTemplate, ArgumentBindings, ArgumentListNode} */ private function findTemplate( PropertyFetchNode|StaticPropertyFetchNode|ArrayAccessNode $node, @@ -632,7 +653,7 @@ private function findTemplate( $bound = $arguments->findArgument(null, 0); return [ ($template ?? $known->value)->describe($known->pattern->describe($access->kind)), - ($hooks[$use] ?? $known)->decision, + $hooks[$use] ?? $known, $template, new ArgumentBindings($bound === null ? [] : ['value' => $bound]), $arguments, @@ -667,7 +688,7 @@ function (MemberMapEntry $entry) use ($call, $types, &$bindings): bool { ? null : [ $entry->value->describe($entry->pattern->describe(MemberKind::Method)), - $entry->decision, + $entry, $entry->value, $bindings[spl_object_id($entry)], $call->arguments, diff --git a/src/Rules/Upgrading/ReplacedClassesRule.php b/src/Rules/Upgrading/ReplacedClassesRule.php index ea1e15e037..cffb741efd 100644 --- a/src/Rules/Upgrading/ReplacedClassesRule.php +++ b/src/Rules/Upgrading/ReplacedClassesRule.php @@ -9,6 +9,7 @@ use DressCode\Analyses\{MemberAccess, MemberKind, PhpDoc, Types}; use DressCode\{CodeWriter, NodeRule, RuleContext, RuleInfo, Stage, Values}; +use DressCode\Config\Layer; use DressCode\Upgrading\{MemberMap, MemberMapGrammar}; use PhpSyntax\Analyses\NameResolver; use PhpSyntax\{Node, Token}; @@ -41,7 +42,10 @@ final class ReplacedClassesRule extends NodeRule { public const Map = MemberMapGrammar::ReplacedClasses; - /** @var array lowercased replaced name => the name written instead, both fully qualified */ + /** + * @var array lowercased replaced name => the name written instead, both fully + * qualified, and the section of the upgrading data that laid it + */ private array $classes = []; /** @var MemberMap */ @@ -55,7 +59,7 @@ public function configure(Values $values): void $options = $values->readMap(self::Map); $this->classes = []; foreach ($options as $old => $new) { - $this->classes[strtolower(ltrim((string) $old, '\\'))] = ltrim($new, '\\'); + $this->classes[strtolower(ltrim((string) $old, '\\'))] = [ltrim($new, '\\'), $values->getEntryOrigin(self::Map, (string) $old)]; } $this->forbiddenMembers = MemberMap::fromValues($values, MemberMapGrammar::ForbiddenMembers); @@ -78,14 +82,16 @@ public function enter(Node|Token $node, RuleContext $context): void ) { $types = $context->findAnalysis(Types::class); $find = function (string $class) use ($types): ?array { - $new = $this->classes[strtolower($class)] ?? null; + [$new, $source] = $this->classes[strtolower($class)] ?? [null, null]; return match (true) { $new === null => null, $types !== null && $types->findClassName($new, traits: true) === null => [ "Class `$class` is replaced by `$new`, but class `$new` does not exist in the project", null, + null, + $source, ], - default => ["Class `$class` is replaced by `$new`", $new], + default => ["Class `$class` is replaced by `$new`", $new, null, $source], }; }; ClassReplacement::rewriteReferences( diff --git a/src/Rules/Upgrading/ReplacedFunctionCallsRule.php b/src/Rules/Upgrading/ReplacedFunctionCallsRule.php index b084d44fb1..0037ebab6d 100644 --- a/src/Rules/Upgrading/ReplacedFunctionCallsRule.php +++ b/src/Rules/Upgrading/ReplacedFunctionCallsRule.php @@ -8,6 +8,7 @@ namespace DressCode\Rules\Upgrading; use DressCode\{CodeWriter, GlobalCalls, NodeRule, QualifiedNames, RuleContext, RuleInfo, Stage, Values}; +use DressCode\Config\Layer; use DressCode\Rules\NodeHelpers; use DressCode\Upgrading\{FunctionPattern, MemberMapGrammar}; use PhpSyntax\Analyses\NameResolver; @@ -33,8 +34,8 @@ final class ReplacedFunctionCallsRule extends NodeRule { /** - * @var array> the function => its keys with the - * decision each is reported under, the most specific first + * @var array> the function => its keys + * with the decision each is reported under and the section of the upgrading data it came with, the most specific first */ private array $functions = []; @@ -52,6 +53,7 @@ public function configure(Values $values): void $pattern, CallTemplate::fromEntry($value, $pattern), $values->getEntryDecision(MemberMapGrammar::ReplacedCalls, (string) $key), + $values->getEntryOrigin(MemberMapGrammar::ReplacedCalls, (string) $key), ]; $this->shortNames[strtolower(QualifiedNames::stripNamespace($pattern->name))] = true; } @@ -90,7 +92,7 @@ public function enter(Node|Token $node, RuleContext $context): void return; } - foreach ($this->functions[$function] as [$pattern, $template, $decision]) { + foreach ($this->functions[$function] as [$pattern, $template, $decision, $source]) { $bindings = $pattern->bind($call->arguments); if ($bindings === null) { continue; @@ -99,7 +101,7 @@ public function enter(Node|Token $node, RuleContext $context): void $subject = "Function `$pattern->name()`"; $uncertainty = str_contains($function, '\\') ? null : GlobalCalls::findUncertainty($call, $context); if ($template->removesCall()) { - $template->removeCall($call, $subject, $decision, $context, $uncertainty); + $template->removeCall($call, $subject, $decision, $source, $context, $uncertainty); return; } @@ -109,6 +111,7 @@ public function enter(Node|Token $node, RuleContext $context): void $call->name, $template->describe($subject) . "$rewrite->refusal.", decision: $decision, + source: $source, fixable: $rewrite->expression !== null, risk: $rewrite->expression === null ? null : NodeHelpers::findRisk($rewrite->because, $uncertainty), because: $rewrite->expression === null ? null : $rewrite->because ?? $uncertainty, diff --git a/src/Rules/Upgrading/ReplacedFunctionsRule.php b/src/Rules/Upgrading/ReplacedFunctionsRule.php index 6665a8e529..f1c10e2db4 100644 --- a/src/Rules/Upgrading/ReplacedFunctionsRule.php +++ b/src/Rules/Upgrading/ReplacedFunctionsRule.php @@ -9,6 +9,7 @@ use DressCode\Analyses\{Parameter, PhpSignatures, PhpSymbols}; use DressCode\{CodeWriter, GlobalCalls, NodeRule, QualifiedNames, Risk, RuleContext, RuleInfo, Stage, Values}; +use DressCode\Config\Layer; use DressCode\Rules\NodeHelpers; use DressCode\Upgrading\MemberMapGrammar; use PhpSyntax\Analyses\NameResolver; @@ -49,8 +50,8 @@ final class ReplacedFunctionsRule extends NodeRule public const Map = MemberMapGrammar::ReplacedFunctions; /** - * @var array lowercased replaced name => the replaced and the replacing name - * as the project spells them + * @var array lowercased replaced name => the replaced and the + * replacing name as the project spells them, and the section of the upgrading data that laid it */ private array $functions = []; @@ -61,7 +62,11 @@ public function configure(Values $values): void $this->functions = []; foreach ($options as $old => $new) { // both as the project spells them, which is what its message quotes back at it - $this->functions[strtolower(ltrim((string) $old, '\\'))] = [ltrim((string) $old, '\\'), ltrim($new, '\\')]; + $this->functions[strtolower(ltrim((string) $old, '\\'))] = [ + ltrim((string) $old, '\\'), + ltrim($new, '\\'), + $values->getEntryOrigin(self::Map, (string) $old), + ]; } } @@ -81,7 +86,7 @@ public function enter(Node|Token $node, RuleContext $context): void return; } - [$old, $new] = $this->functions[$key]; + [$old, $new, $source] = $this->functions[$key]; $resolver = $context->getAnalysis(NameResolver::class); $namespace = $resolver->getNamespace($node); @@ -93,6 +98,7 @@ public function enter(Node|Token $node, RuleContext $context): void fixable: $refusal === null, risk: $uncertainty === null ? null : Risk::NameUncertain, because: $uncertainty, + source: $source, )) { return; } diff --git a/src/Rules/Upgrading/ReplacedMembersRule.php b/src/Rules/Upgrading/ReplacedMembersRule.php index b8ca0d8e45..dcc9848a50 100644 --- a/src/Rules/Upgrading/ReplacedMembersRule.php +++ b/src/Rules/Upgrading/ReplacedMembersRule.php @@ -139,6 +139,7 @@ public function enter(Node|Token $node, RuleContext $context): void $node->name, $pattern->describeAccess($access, $node) . ' is replaced by ' . $target->describe($access->kind, $pattern) . $refusal . '.', decision: $entry->decision, + source: $entry->origin, fixable: $refusal === null, risk: $risk === null ? null : Risk::BehaviorChanges, because: $risk, @@ -195,6 +196,7 @@ private function enterDeclaration(MethodNode $node, RuleContext $context): void $node->name, $pattern->describe($kind) . ' is replaced by ' . $target->describe($kind, $pattern) . ($refusal ?? '') . '.', decision: $entry->decision, + source: $entry->origin, fixable: $refusal === null, )) { $node->name->text = $target->name; @@ -232,6 +234,7 @@ private function enterCallable(ArrayNode|StringNode $node, RuleContext $context) $callable->literal, $pattern->describe($access->kind) . ' is replaced by ' . $target->describe($access->kind, $pattern) . $refusal . '.', decision: $entry->decision, + source: $entry->origin, fixable: $refusal === null, risk: $risk === null ? null : Risk::BehaviorChanges, because: $risk, diff --git a/src/Rules/Upgrading/Rewrite.php b/src/Rules/Upgrading/Rewrite.php index 0a6d22659d..17fe638b4b 100644 --- a/src/Rules/Upgrading/Rewrite.php +++ b/src/Rules/Upgrading/Rewrite.php @@ -8,6 +8,7 @@ namespace DressCode\Rules\Upgrading; use DressCode\{CodeWriter, Risk, RuleContext}; +use DressCode\Config\Layer; use PhpSyntax\Analyses\NameResolver; use PhpSyntax\{Node, SymbolKind, Token}; use PhpSyntax\Nodes\{ArgumentListNode, ArgumentNode, ExpressionNode, NameNode}; @@ -45,15 +46,17 @@ public function withRisk(string $because): self /** - * Reports the use under the decision with what the template made of it, and says whether it is to be rewritten. + * Reports the use under the decision, with the section of the upgrading data the entry came with, and with what + * the template made of it, and says whether it is to be rewritten. * @phpstan-assert-if-true !null $this->expression */ - public function report(Node|Token $at, string $message, string $decision, RuleContext $context): bool + public function report(Node|Token $at, string $message, string $decision, ?Layer $source, RuleContext $context): bool { return $context->report( $at, $message . $this->refusal . '.', decision: $decision, + source: $source, fixable: $this->expression !== null, risk: $this->because === null ? null : Risk::BehaviorChanges, because: $this->because, diff --git a/src/Rules/Upgrading/UnseenReferencesRule.php b/src/Rules/Upgrading/UnseenReferencesRule.php new file mode 100644 index 0000000000..6abdec334f --- /dev/null +++ b/src/Rules/Upgrading/UnseenReferencesRule.php @@ -0,0 +1,137 @@ + lowercased class => the class as the map spells it, what the map + * does with it, the section of the upgrading data that laid it + */ + private array $classes = []; + + + public static function getDecisions(): array + { + return [ + new Decision(self::ClassNameString, new Words([ + 'reported' => 'reported where it stands: the string `\'Acme\Old\'` naming a class the maps rename or forbid', + ]), 'A string holding the name of a class `replacedClasses` or `forbiddenClasses` names, which no rename of the class reaches'), + new Decision(self::DynamicAccess, new Words([ + 'reported' => 'reported where it stands: `$object->$method()`, `new $class`, `call_user_func($callback)`', + ]), 'A member, a class or a function reached by a name the code computes, which no map of upgrading data matches'), + ]; + } + + + public function configure(Values $values): void + { + $this->classes = []; + foreach ([self::Forbidden => 'forbidden', self::Replaced => 'replaced'] as $path => $verdict) { + foreach ($values->readMap($path) as $class => $value) { + $class = ltrim((string) $class, '\\'); + $this->classes[strtolower($class)] = [ + $class, + $verdict === 'replaced' ? 'replaced by `' . ltrim((string) $value, '\\') . '`' : 'forbidden', + $values->getEntryOrigin($path, $class), + ]; + } + } + } + + + public function getVisitedNodes(): array + { + return [ + ...$this->classes === [] ? [] : [StringNode::class], + MethodCallNode::class, + StaticMethodCallNode::class, + PropertyFetchNode::class, + NewNode::class, + FunctionCallNode::class, + ]; + } + + + public function enter(Node|Token $node, RuleContext $context): void + { + if ($node instanceof StringNode) { + $this->checkString($node, $context); + return; + } + + $subject = match (true) { + $node instanceof MethodCallNode && !$node->name instanceof IdentifierNode => 'A method called', + $node instanceof PropertyFetchNode && !$node->name instanceof IdentifierNode => 'A property read', + $node instanceof StaticMethodCallNode && (!$node->name instanceof IdentifierNode || !$node->class instanceof NameNode) + => 'A static method called', + $node instanceof NewNode && $node->class instanceof ExpressionNode => 'A class instantiated', + $node instanceof FunctionCallNode && (!$node->name instanceof NameNode || $this->callsComputedName($node, $context)) + => 'A function called', + default => null, + }; + if ($subject !== null) { + $context->report( + $node, + "$subject by a name the code computes, which no map of upgrading data sees.", + decision: self::DynamicAccess, + fixable: false, + ); + } + } + + + private function checkString(StringNode $node, RuleContext $context): void + { + [$class, $verdict, $source] = $this->classes[strtolower(ltrim($node->toValue(), '\\'))] ?? [null, null, null]; + if ($class !== null) { + $context->report( + $node, + "The string names class `$class`, which is $verdict; no rewrite reaches a string.", + decision: self::ClassNameString, + fixable: false, + source: $source, + ); + } + } + + + /** Whether the call is of a function calling what its first argument names, given as other than a literal. */ + private function callsComputedName(FunctionCallNode $node, RuleContext $context): bool + { + assert($node->name instanceof NameNode); + $function = strtolower($context->getAnalysis(NameResolver::class)->resolveFunction($node->name)); + $first = $node->arguments->findArgument(null, 0); + return in_array($function, self::CallingFunctions, true) && $first !== null && !$first->value instanceof StringNode; + } +} diff --git a/src/Testing/RuleTester.php b/src/Testing/RuleTester.php index 73c1e0b534..856491eb7b 100644 --- a/src/Testing/RuleTester.php +++ b/src/Testing/RuleTester.php @@ -351,7 +351,7 @@ private static function createInstance(string|\Closure $rule, string $file, stri if (($tree['upgrading']['php']['deprecatedApi'] ?? 'keep') !== 'keep') { // the upgrading data of PHP lie beneath, as a run lays them $data = PackageDiscovery::readPhpData((new ProjectPackages)->withPhp($phpTarget)) ?? throw new \LogicException; - array_unshift($layers, [$data->layer, $data->buildDecisions(fn(string $map) => "upgrading.api.$map")]); + array_unshift($layers, ...$data->buildDecisions(fn(string $map) => "upgrading.api.$map")); } $catalogue = Catalogue::fromRules(self::getRules($class, $layers)); diff --git a/src/Testing/UpgradingTester.php b/src/Testing/UpgradingTester.php index 4dff3e7bc1..8c6169a999 100644 --- a/src/Testing/UpgradingTester.php +++ b/src/Testing/UpgradingTester.php @@ -12,6 +12,7 @@ use DressCode\Domains\Map; use DressCode\Rules\Upgrading\MemberTarget; use DressCode\Upgrading\{MemberMapGrammar, MemberPattern, MemberPatternKind}; +use Nette\Neon\{Exception, Neon}; use Nette\Schema\ValidationException; use Nette\Utils\FileSystem; use function count, is_array, is_string, strlen; @@ -78,6 +79,51 @@ public static function collectProblems(string $file, string $root, array $packag } + /** + * Checks that `extra.dresscode.packages` of the package at the root says exactly which packages its upgrading files + * are about, by which `upgrade` offers it to a project lacking it: none of them left out, and none listed that no + * file is about. + * @return list + */ + public static function collectPackageProblems(string $root): array + { + $composer = ComposerJson::read("$root/composer.json") ?? []; + $name = is_string($composer['name'] ?? null) ? $composer['name'] : 'the root package'; + $extra = $composer['extra']['dresscode'] ?? null; + if (!is_array($extra)) { + return []; + } + + try { + $about = []; + foreach (PackageDiscovery::findUpgradingFiles($root, $extra, $name) as $file) { + $package = Neon::decodeFile("$root/$file")['package'] ?? null; + if (is_string($package)) { + $about[$package] = $file; + } + } + } catch (ConfigurationException|Exception $e) { + return [$e->getMessage()]; + } + + $listed = is_array($extra['packages'] ?? null) ? array_values(array_filter($extra['packages'], is_string(...))) : []; + $problems = []; + foreach ($about as $package => $file) { + if (!PackageDiscovery::isAbout($listed, $package)) { + $problems[] = "Package `$name`: `extra.dresscode.packages` in its `composer.json` does not list `$package`, which `$file` is about."; + } + } + + foreach ($listed as $package) { + if (!array_any(array_keys($about), fn(string $library) => PackageDiscovery::isAbout([$package], $library))) { + $problems[] = "Package `$name`: `extra.dresscode.packages` in its `composer.json` lists `$package`, which no upgrading file is about."; + } + } + + return $problems; + } + + /** * Runs code written for the old API of the libraries through the rules as the project fixes it: every section * the installed version of a library reaches applies, whatever the constraint of the project allows, and the diff --git a/src/Upgrade/BlindSpots.php b/src/Upgrade/BlindSpots.php new file mode 100644 index 0000000000..e489b63e01 --- /dev/null +++ b/src/Upgrade/BlindSpots.php @@ -0,0 +1,34 @@ + the extension of the files no rule reads that an upgrade may change too => their count */ + public array $otherFiles = [], + /** the files a generator wrote, as their heads say, which the estimate leaves out */ + public int $generatedFiles = 0, + ) { + } + + + public function isEmpty(): bool + { + return $this->classNameStrings === 0 && $this->dynamicAccesses === 0 && $this->otherFiles === [] && $this->generatedFiles === 0; + } +} diff --git a/src/Upgrade/Blocker.php b/src/Upgrade/Blocker.php new file mode 100644 index 0000000000..b67db95660 --- /dev/null +++ b/src/Upgrade/Blocker.php @@ -0,0 +1,25 @@ + */ + public array $packages = [], + /** why Composer gave no answer, null where it gave one */ + public ?string $unknown = null, + ) { + } + + + /** Whether Composer said that nothing of the lock refuses the target. */ + public function isClear(): bool + { + return $this->packages === [] && $this->unknown === null; + } +} diff --git a/src/Upgrade/Composer.php b/src/Upgrade/Composer.php new file mode 100644 index 0000000000..ebec2156cd --- /dev/null +++ b/src/Upgrade/Composer.php @@ -0,0 +1,309 @@ +rootPath ?? $root, $packages->rootName); + } + + + /** Composer of a project that has a lock, which the questions about the installed packages need; null for one without. */ + public static function forLockOf(ProjectPackages $project): ?self + { + return $project->rootPath !== null && is_file("$project->rootPath/composer.lock") + ? new self($project->rootPath, $project->rootName) + : null; + } + + + /** The installed packages of the lock refusing the version of the target, as `composer why-not --locked` says. */ + public function findBlockers(Target $target): Blockers + { + if (!is_file("$this->root/composer.lock")) { + return new Blockers($target, unknown: 'the project has no `composer.lock` to ask'); + } + + try { + // why-not exits with 1 where something refuses the version + $output = $this->run(['why-not', '--locked', $target->package, $target->version], self::Timeout, accepted: 1); + } catch (ComposerException $e) { + return new Blockers($target, unknown: $e->getMessage()); + } + + return self::parseBlockers($target, $output, $this->rootName); + } + + + /** + * The packages the output of `composer why-not` lists as refusing the version, the project itself left out; unknown + * where the output is no answer of why-not, which exits with 1 as a Composer that failed does. + * @internal + */ + public static function parseBlockers(Target $target, string $output, ?string $rootName): Blockers + { + $blockers = []; + $answered = str_contains($output, 'There is no installed package depending on'); + foreach (preg_split('~\R~', $output) ?: [] as $line) { + if (!preg_match(self::BlockerPattern, trim($line), $m)) { + continue; + } + + $answered = true; + // the project and the target itself, whose versions refusing the PHP Composer runs on refuse no target + if ($m[1] !== $rootName && $m[1] !== $target->package) { + $blockers[] = new Blocker($m[1], $m[2], $m[3] === 'conflicts' ? "conflicts with $m[4] $m[5]" : $m[5]); + } + } + + return $answered + ? new Blockers($target, $blockers) + : new Blockers($target, unknown: 'Composer gave no answer: ' . (self::findLastLine($output) ?? 'no output')); + } + + + /** + * What raising the constraints moves the installed packages to, as the dry run of the update says, which needs the + * network. + * @param array $constraints package => constraint + */ + public function findMoves(array $constraints): Moves + { + try { + return new Moves(self::parseMoves($this->previewRequire($constraints))); + } catch (ComposerException $e) { + return new Moves(unknown: $e->getMessage()); + } + } + + + /** + * The packages the operations of an update move from one version to another. + * @param list $operations as `parseOperations()` reads them + * @return list + */ + public static function parseMoves(array $operations): array + { + $moves = []; + foreach ($operations as $operation) { + if (preg_match('~^- (?:Upgrading|Downgrading) (\S+) \((\S+) => (\S+)\)~', $operation, $m)) { + $moves[] = new Move($m[1], $m[2], $m[3]); + } + } + + return $moves; + } + + + /** + * What the raise would do to the installed packages, changing nothing: the operations of the update, none without + * `$update`. The dry run is of copies of `composer.json` and the lock beside them, `config.platform.php` raised where + * the raise raises it, so that it resolves what the raise will, the platform alone among it. + * @param array $constraints package => constraint + * @return list as `- Upgrading nette/utils (v3.2.10 => v4.0.11)` + * @throws ComposerException + */ + public function previewRequire(array $constraints, bool $update = true, ?string $platform = null): array + { + $data = json_decode((string) @file_get_contents("$this->root/composer.json"), associative: true); // @ none is told below + if (!is_array($data)) { + throw new ComposerException("The project has no `composer.json` Composer reads in `$this->root`."); + } elseif ($platform !== null) { + $data['config']['platform']['php'] = $platform; + } + + // beside the original, so that the vendor directory and the paths it names are what they are for it + $copy = "$this->root/.dresscode-preview-" . bin2hex(random_bytes(6)); + try { + FileSystem::write("$copy.json", json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR)); + if (is_file("$this->root/composer.lock")) { + FileSystem::copy("$this->root/composer.lock", "$copy.lock"); + } + + $arguments = $constraints === [] + ? ['update', '--lock', '--dry-run'] + : self::buildRequire($constraints, $update, dryRun: true); + return self::parseOperations($this->run($arguments, self::UpdateTimeout, env: ['COMPOSER' => "$copy.json"])); + } finally { + @unlink("$copy.json"); // @ may not have been written + @unlink("$copy.lock"); // @ the project may have no lock + } + } + + + /** + * Writes the constraints into `composer.json` and updates the packages they move to the lowest versions they allow, + * which the code is written for and whose `@deprecated` the run reads, those they depend on changed as little as + * the update needs; without `$update` only `composer.json` changes, and `config.platform.php` is raised first where + * given. + * @param array $constraints package => constraint + * @throws ComposerException + */ + public function require(array $constraints, bool $update = true, ?string $platform = null): void + { + if ($platform !== null) { + $this->run(['config', 'platform.php', $platform], self::Timeout); + } + + if ($constraints !== []) { + $this->run(self::buildRequire($constraints, $update), self::UpdateTimeout); + } elseif ($update) { // the platform alone, which the lock is to say it was resolved for + $this->run(['update', '--lock'], self::UpdateTimeout); + } + } + + + /** + * What updating every package to the newest version the constraints allow would do, changing nothing. + * @return list as `- Upgrading nette/utils (v4.0.0 => v4.0.11)` + * @throws ComposerException + */ + public function previewUpdate(): array + { + return self::parseOperations($this->run(['update', '--dry-run'], self::UpdateTimeout)); + } + + + /** + * Updates every package to the newest version the constraints allow. + * @throws ComposerException + */ + public function update(): void + { + $this->run(['update'], self::UpdateTimeout); + } + + + /** + * Installs the packages the lock says. + * @throws ComposerException + */ + public function install(): void + { + $this->run(['install'], self::UpdateTimeout); + } + + + /** + * Requires the packages at the versions Composer chooses and installs them, the way `composer require` does. + * @param list $packages + * @throws ComposerException + */ + public function add(array $packages, bool $dev = false): void + { + $this->run(['require', ...$dev ? ['--dev'] : [], ...$packages], self::UpdateTimeout); + } + + + /** + * The operations on packages the output of an update lists, each once, though Composer writes it among the + * operations of the lock and again among those of the installation. + * @return list as `- Upgrading nette/utils (v3.2.10 => v4.0.11)` + */ + public static function parseOperations(string $output): array + { + $lines = array_map(trim(...), preg_split('~\R~', $output) ?: []); + return array_values(array_unique(preg_grep('~^- (Upgrading|Downgrading|Installing|Removing) ~', $lines) ?: [])); + } + + + /** + * The arguments of `composer require` writing the constraints, with the update or without it. + * @param array $constraints + * @return list + */ + public static function buildRequire(array $constraints, bool $update, bool $dryRun = false): array + { + return [ + 'require', + ...array_map(fn(string $package, string $constraint) => "$package:$constraint", array_keys($constraints), $constraints), + ...$update ? ['-W', '--prefer-lowest', '--minimal-changes'] : ['--no-update'], + ...$dryRun ? ['--dry-run'] : [], + ]; + } + + + /** + * What Composer wrote on both streams. + * @param list $arguments + * @param array $env + * @throws ComposerException where it does not end in time, crashes or exits with a code above the one accepted + */ + private function run(array $arguments, int $timeout, int $accepted = 0, array $env = []): string + { + $binary = getenv('COMPOSER_BINARY'); + $composer = $binary ? [...WorkerPool::buildPhpCommand() ?? [PHP_BINARY], $binary] : ['composer']; + $command = [...$composer, ...$arguments, '--no-ansi', '--no-interaction']; + [$exit, $output] = ProcessRunner::run($command, $this->root, $timeout, env: $env); + if ($exit === null || $exit < 0 || $exit > $accepted) { // a crash ends with a negative code, by a signal or on Windows + $log = $this->keepLog($command, $timeout, $exit, $output); + throw new ComposerException(($exit === null + ? "Composer did not answer within $timeout s" + : 'Composer failed: ' . (self::findLastLine($output) ?? "exit code $exit")) + . ($log === null ? '' : "; its whole output is in `$log`")); + } + + return $output; + } + + + /** + * Writes the command, its exit and all it wrote into a file of the temporary directory, as the message keeps only + * the last line; null where the file cannot be written. + * @param list $command + */ + private function keepLog(array $command, int $timeout, ?int $exit, string $output): ?string + { + $file = sys_get_temp_dir() . '/dresscode-composer-' . date('Ymd-His') . '-' . substr(hash('xxh128', $output), 0, 8) . '.log'; + $head = 'command: ' . implode(' ', $command) . "\ndirectory: $this->root\n" + . ($exit === null ? "timeout: $timeout s, not answered\n" : "exit code: $exit\n"); + return @file_put_contents($file, "$head\n$output") === false ? null : FileSystem::platformSlashes($file); // @ the temporary directory may refuse it + } + + + private static function findLastLine(string $output): ?string + { + $lines = array_filter(array_map(trim(...), preg_split('~\R~', $output) ?: [])); + return $lines === [] ? null : end($lines); + } +} diff --git a/src/Upgrade/ComposerJournal.php b/src/Upgrade/ComposerJournal.php new file mode 100644 index 0000000000..4f39af9dab --- /dev/null +++ b/src/Upgrade/ComposerJournal.php @@ -0,0 +1,195 @@ +readIndex() !== null) { + return; + } + + $before = []; + foreach (self::Files as $name) { + $text = @file_get_contents("$root/$name"); // @ a file the project does not have + if ($text !== false) { + Helpers::replaceFile("$this->dir/$name", $text); + } + + $before[$name] = $text !== false; + } + + $this->writeIndex(['step' => $step, 'before' => $before, 'after' => self::hashFiles($root)]); + } + + + /** Keeps what the raise left, which a file must still be for `restore()` to write it back. */ + public function recordAfter(string $root): void + { + $index = $this->readIndex(); + if ($index !== null) { + $this->writeIndex(['after' => self::hashFiles($root)] + $index); + } + } + + + /** The step whose raise the journal goes back before; null where it keeps nothing. */ + public function findStep(): ?int + { + return $this->readIndex()['step'] ?? null; + } + + + /** + * The files the raise changed. + * @return list + */ + public function findChanged(): array + { + $index = $this->readIndex(); + return $index === null + ? [] + : array_values(array_filter( + self::Files, + fn(string $name) => $this->hashKept($name, $index['before'][$name] ?? false) !== ($index['after'][$name] ?? null), + )); + } + + + /** Whether files were written back with a lock beside them, whose packages are still to be installed. */ + public function isAwaitingInstall(): bool + { + return $this->readIndex()['awaitingInstall'] ?? false; + } + + + /** Says that the packages of the lock written back are installed. */ + public function markInstalled(): void + { + $index = $this->readIndex(); + if ($index !== null) { + $this->writeIndex(['awaitingInstall' => false] + $index); + } + } + + + /** + * Writes the files back as they were before the raise, but a file changed after the raise, which is left as it is + * and stays kept, so that it can be put back once resolved; a file written back is what the raise left from then on. + * A dry run only says which files it would write back and which it would leave. + * @return array{list, array} the files written back, those left => why + */ + public function restore(string $root, bool $dryRun = false): array + { + $index = $this->readIndex(); + if ($index === null) { + return [[], []]; + } + + $restored = $left = []; + foreach (self::Files as $name) { + $kept = $index['before'][$name] ?? false; + $current = self::hashFile("$root/$name"); + if ($current === $this->hashKept($name, $kept)) { + continue; + } elseif ($current !== ($index['after'][$name] ?? null)) { + $left[$name] = "The file changed after the raise of step {$index['step']}, so it is not written back."; + } elseif ($dryRun) { + $restored[] = $name; + } elseif ($kept) { + Helpers::replaceFile("$root/$name", FileSystem::read("$this->dir/$name")); + $restored[] = $name; + } else { + FileSystem::delete("$root/$name"); + $restored[] = $name; + } + } + + if (!$dryRun && $restored !== []) { + foreach ($restored as $name) { + $index['after'][$name] = self::hashFile("$root/$name"); + } + + $index['awaitingInstall'] = is_file("$root/composer.lock"); + $this->writeIndex($index); + } + + return [$restored, $left]; + } + + + public function forget(): void + { + FileSystem::delete($this->dir); + } + + + private function hashKept(string $name, bool $kept): ?string + { + return $kept ? self::hashFile("$this->dir/$name") : null; + } + + + /** @return array */ + private static function hashFiles(string $root): array + { + return array_combine(self::Files, array_map(fn(string $name) => self::hashFile("$root/$name"), self::Files)); + } + + + private static function hashFile(string $file): ?string + { + $text = @file_get_contents($file); // @ a file that does not exist has no hash + return $text === false ? null : hash('xxh128', $text); + } + + + /** @return ?array{step: int, before: array, after: array, awaitingInstall?: bool} */ + private function readIndex(): ?array + { + $index = json_decode((string) @file_get_contents("$this->dir/index.json"), associative: true); // @ no journal is kept + return is_array($index) && is_int($index['step'] ?? null) && is_array($index['before'] ?? null) && is_array($index['after'] ?? null) + ? [ + 'step' => $index['step'], + 'before' => array_map(fn($kept) => $kept === true, $index['before']), + 'after' => array_map(fn($hash) => is_string($hash) ? $hash : null, $index['after']), + 'awaitingInstall' => ($index['awaitingInstall'] ?? false) === true, + ] + : null; + } + + + /** @param array{step: int, before: array, after: array, awaitingInstall?: bool} $index */ + private function writeIndex(array $index): void + { + Helpers::replaceFile("$this->dir/index.json", json_encode($index, JSON_THROW_ON_ERROR)); + } +} diff --git a/src/Upgrade/ComposerStep.php b/src/Upgrade/ComposerStep.php new file mode 100644 index 0000000000..b60f7db5b8 --- /dev/null +++ b/src/Upgrade/ComposerStep.php @@ -0,0 +1,86 @@ + package of `require` => the constraint written */ + public array $require, + /** the packages updated too, not only `composer.json` */ + public bool $update = true, + /** the version `config.platform.php` is raised to beside the constraint of PHP, where the project sets it lower */ + public ?string $platform = null, + public bool $skip = false, + ) { + } + + + public function formatCommands(): array + { + $commands = $this->platform === null ? [] : ["composer config platform.php $this->platform"]; + if ($this->require !== []) { + $arguments = Composer::buildRequire($this->require, $this->update); + $commands[] = 'composer ' + . implode(' ', array_map(fn(string $argument) => str_contains($argument, ':') ? "\"$argument\"" : $argument, $arguments)); + } elseif ($this->update) { // the platform alone, which the lock is to say it was resolved for + $commands[] = 'composer update --lock'; + } + + return $commands; + } + + + /** + * Whether the project has the step done: `composer.json` requires every package of the step with a lower bound the + * step reaches, allowing the newest version the step names, `^8.4` and `~8.4.0` raising `^8.1` to `^8.4` and + * `^3.2 || ^4.0` widening `^3.2`, and for a step that updates, the versions installed and locked are ones the step + * allows, for PHP the platform the project sets, which reaches the one the step raises it to. + * @phpstan-impure + */ + public function isDoneIn(ProjectPackages $project): bool + { + $locked = $this->update ? $project->readLockedVersions() : null; + return ($this->platform === null || version_compare($project->platformPhp ?? '0', $this->platform, '>=')) + && array_all($this->require, function (string $constraint, string $package) use ($project, $locked): bool { + $required = $project->required[$package] ?? null; + $lowests = array_map( + fn(string $part) => Versions::findLowestVersion($part) ?? '0', + Versions::splitAlternatives($constraint), + ); + usort($lowests, fn(string $a, string $b) => version_compare($a, $b)); + // false for a package missing, null for nothing to compare, as the version of a branch without an alias + $installed = match (true) { + $package === PackageDiscovery::Php => $project->platformPhp, + !isset($project->installed[$package]) => false, + default => $project->installed[$package]['version'], + }; + $lock = match (true) { + $locked === null || $package === PackageDiscovery::Php => null, + !array_key_exists($package, $locked) => false, + default => $locked[$package], + }; + return $required !== null + && version_compare(Versions::findLowestVersion($required) ?? '0', $lowests[0] ?? '0', '>=') + && Versions::isSubset((string) end($lowests), $required) + && (!$this->update + || (($installed === null || ($installed !== false && Versions::isSubset($installed, $constraint))) + && ($lock === null || ($lock !== false && Versions::isSubset($lock, $constraint))))); + }); + } +} diff --git a/src/Upgrade/Constraints.php b/src/Upgrade/Constraints.php new file mode 100644 index 0000000000..77fc159a61 --- /dev/null +++ b/src/Upgrade/Constraints.php @@ -0,0 +1,153 @@ + $targets + * @return array package => constraint + */ + public function raise(array $targets): array + { + $require = []; + foreach ($targets as $target) { + $constraint = $this->project->required[$target->package] ?? null; + $lowest = $constraint === null ? null : Versions::findLowestVersion($constraint); + if ($lowest === null || version_compare($lowest, $target->version, '<')) { + $require[$target->package] = self::raiseConstraint(trim((string) $constraint), $target->version); + } + } + + return $require; + } + + + /** + * The constraint raised to the version in the shape the project writes it, its upper bounds kept: a part of `||` the + * version is past dropped, and the lower bound of a part allowing it raised, `>=8.4` for `>=8.1`, `^8.4` for a caret + * or a bare version, `>=8.4 <8.5` for `>=8.1 <8.5`; where the version is past every part, the last raised the same + * way, `~8.4.0` for `~8.1.0`, and a caret for one with an upper bound of its own. + */ + public static function raiseConstraint(string $constraint, string $version): string + { + $parts = Versions::splitAlternatives($constraint); + $raised = []; + foreach ($parts as $part) { + if (version_compare(Versions::findLowestVersion($part) ?? '0', $version, '>=')) { + $raised[] = $part; + } elseif (Versions::isSubset($version, $part)) { + $raised[] = self::rewriteLowerBound($part, $version); + } + } + + $last = end($parts); + return match (true) { + $raised !== [] => implode(' || ', $raised), + $last === false || self::findUpperBound($last) !== null => "^$version", + default => self::rewriteLowerBound($last, $version), + }; + } + + + /** The upper bound of its own the constraint raised to the version passes, `<8.4` of `>=8.1 <8.4` raised to 8.4. */ + public static function findPassedUpperBound(string $constraint, string $version): ?string + { + $parts = Versions::splitAlternatives($constraint); + $last = end($parts); + return $last === false || array_any($parts, fn(string $part) => Versions::isSubset($version, $part) + || version_compare(Versions::findLowestVersion($part) ?? '0', $version, '>=')) + ? null + : self::findUpperBound($last); + } + + + /** + * The part of a constraint with its lower bound replaced by the version, its upper bound kept: each operator with its + * version, `>= 8.1` as `>=8.1`, and a range of a hyphen with its end. + */ + private static function rewriteLowerBound(string $part, string $version): string + { + $part = (string) preg_replace('~(<=|>=|<|>|!=|==|=|\^|\~)\s+(?=v?\d)~', '$1', trim($part)); + if (preg_match(self::HyphenRange, $part, $m)) { + return "$version - $m[2]"; + } + + $tokens = array_map(fn(string $token) => match (true) { + str_starts_with($token, '<'), str_starts_with($token, '!=') => $token, + str_starts_with($token, '>') => ">=$version", + (bool) preg_match('~^\~\s*v?(\d+(?:\.\d+)*)$~', $token, $m) + => '~' . implode('.', array_pad(explode('.', $version), substr_count($m[1], '.') + 1, '0')), + default => "^$version", + }, preg_split('~\s*,\s*|\s+~', trim($part), flags: PREG_SPLIT_NO_EMPTY) ?: []); + return implode(str_contains($part, ',') ? ', ' : ' ', $tokens); + } + + + private static function findUpperBound(string $part): ?string + { + return match (true) { + (bool) preg_match(self::HyphenRange, trim($part), $m) => $m[2], + (bool) preg_match('~<=?\s*v?\d[\w.-]*~', $part, $m) => $m[0], + default => null, + }; + } + + + /** + * The constraints the targets widen, `^3.2 || ^4.0` for `^3.2`; nothing for a target they allow. + * @param list $targets + * @return array package => constraint + */ + public function widen(array $targets): array + { + $require = []; + foreach ($targets as $target) { + $constraint = $this->project->required[$target->package] ?? null; + if ($constraint !== null && !Versions::isSubset($target->version, $constraint)) { + $require[$target->package] = "$constraint || ^$target->version"; + } + } + + return $require; + } + + + /** + * The version of PHP `config.platform.php` is raised to, where `composer.json` sets it below the target, which + * Composer would otherwise resolve the packages for. + * @param list $targets + */ + public function raisePlatform(array $targets): ?string + { + $platform = $this->project->platformPhp; + $target = array_find($targets, fn(Target $target) => $target->package === PackageDiscovery::Php); + return $platform !== null && $target !== null && version_compare($platform, $target->version, '<') + ? $target->version + : null; + } +} diff --git a/src/Upgrade/DataPackageInstallation.php b/src/Upgrade/DataPackageInstallation.php new file mode 100644 index 0000000000..d477988bdd --- /dev/null +++ b/src/Upgrade/DataPackageInstallation.php @@ -0,0 +1,57 @@ + */ + public array $packages, + /** the directory of the `composer.json` they go into; null for an installation Composer cannot add to, a phar */ + public ?string $directory, + public bool $intoProject, + ) { + } + + + /** What the project needs installed; null where DressCode has every package of upgrading data it needs. */ + public static function find(string $root, string $cacheDir): ?self + { + $project = ProjectPackages::read($root); + $missing = PackageDiscovery::findMissingDataPackages($project, DataPackageCatalogue::load($cacheDir)); + if ($missing === []) { + return null; + } + + $intoProject = $project->has('dresscode/dresscode'); + return new self($missing, $intoProject ? $root : PackageDiscovery::findInstallationRoot(), $intoProject); + } + + + /** The command of Composer that installs them, as a user would type it. */ + public function formatCommand(): string + { + $command = ['composer', 'require', ...$this->intoProject ? ['--dev'] : [], "--working-dir=$this->directory", ...$this->packages]; + return implode(' ', array_map(fn(string $arg) => str_contains($arg, ' ') ? "\"$arg\"" : $arg, $command)); + } + + + /** @throws ComposerException */ + public function install(): void + { + new Composer((string) $this->directory)->add($this->packages, dev: $this->intoProject); + } +} diff --git a/src/Upgrade/DependencyStep.php b/src/Upgrade/DependencyStep.php new file mode 100644 index 0000000000..fbadb7b99a --- /dev/null +++ b/src/Upgrade/DependencyStep.php @@ -0,0 +1,22 @@ + + */ + function formatCommands(): array; +} diff --git a/src/Upgrade/Estimate.php b/src/Upgrade/Estimate.php new file mode 100644 index 0000000000..a10cc23ca6 --- /dev/null +++ b/src/Upgrade/Estimate.php @@ -0,0 +1,70 @@ + */ + public array $targets, + /** @var list those of the jump first, each phase by its count of places, the largest first */ + public array $topics, + /** the files checked */ + public int $files, + public BlindSpots $blindSpots, + /** @var list one for every target, where the project has a lock */ + public array $blockers, + /** @var array> a package of upgrading data DressCode lacks => the libraries of the project it is about */ + public array $missingData, + /** @var array library => the newest version its upgrading data know of */ + public array $knownVersions, + /** the run measured what the namespaces declare and resolved the names for certain, the configuration saying nothing */ + public bool $namesMeasured, + /** the run had the types of the code */ + public bool $types, + /** @var list what the user should be told about the run */ + public array $warnings, + /** what raising the constraints to the targets moves, null where Composer was not asked, offline or without a lock */ + public ?Moves $moves = null, + /** @var array the files the check could not process, whose places are not counted => why */ + public array $unprocessed = [], + /** @var list the paths within the configured ones it was narrowed to, relative to the root; none for all */ + public array $paths = [], + /** measured for the plan of a library, which widens its constraints and so moves no installed package */ + public bool $library = false, + ) { + } + + + /** Whether the estimate saw everything it was to: every file processed, the upgrading data there, Composer asked. */ + public function isComplete(): bool + { + return $this->unprocessed === [] + && $this->missingData === [] + && array_all($this->blockers, fn(Blockers $blockers) => $blockers->unknown === null); + } + + + /** + * The topics of the phase, of one set or of any. + * @return list + */ + public function findTopics(Phase $phase, ?string $set = null): array + { + return array_values(array_filter( + $this->topics, + fn(Topic $topic) => $topic->phase === $phase && ($set === null || $topic->set === $set), + )); + } +} diff --git a/src/Upgrade/Estimator.php b/src/Upgrade/Estimator.php new file mode 100644 index 0000000000..1390332c70 --- /dev/null +++ b/src/Upgrade/Estimator.php @@ -0,0 +1,377 @@ + + */ + public function proposeTargets(bool $phpOnly = false): array + { + $factory = new RunnerFactory; + $project = $factory->readProjectPackages($this->project->config, $this->project->root); + $known = PackageDiscovery::discover($project)->findKnownVersions(); + $php = [Target::php($known[PackageDiscovery::Php] ?? Config::DefaultPhpVersion)]; + $today = Versions::findLowestVersion($factory->getPhpTarget($this->project->config, $this->project->root)[0]); + if ($today !== null && version_compare($today, '8.0', '<')) { + unset($known[PackageDiscovery::Php]); + $php = []; + } + + $targets = []; + foreach ($phpOnly ? [] : $known as $library => $version) { + $lowest = $project->findVersion($library); + if ($lowest === null || version_compare($version, $lowest, '>')) { + $targets[] = new Target($library, $version); + } + } + + return $targets ?: $php; + } + + + /** + * @param list $targets + * @param list $paths the files and directories measured within the configured paths, those paths where empty + * @throws ConfigurationException + */ + public function estimate(array $targets, array $paths = []): Estimate + { + $versions = Target::collectVersions($targets); + $this->onProgress?->__invoke('looking for files'); + $discovered = $this->project->discoverPackages($versions); + $plugins = $discovered->findDataPlugins(); + // the project as it is today, narrowed to nothing, which tells what runs before the raise, and whose runner finds the files + $todayRun = new UpgradeCheck($this->project->createLayer($plugins, $this->types), [], self::Sets); + [$todayFactory, $today] = $todayRun->resolve($this->project->config, $this->project->root); + $runner = $todayFactory->createRunner($today, cache: false); + $configured = $this->project->config->paths; + $scope = $paths ? array_map($runner->files->relativize(...), $runner->files->narrowPaths($paths, $configured)) : $configured; + $found = $this->project->findUpgradeFiles($scope); + $files = $found->files; + + $this->onProgress?->__invoke('reading the declarations of the namespaces'); + // those of the whole scope, which a call within the paths named may reach + $names = $this->project->resolveNames($paths ? null : $files); + $warnings = $names->warning === null ? [] : [$names->warning]; + if (version_compare($today->resolvedConfig->phpVersion, '8.0', '<')) { + $warnings[] = 'Upgrading to PHP 8.0 is not covered; fixes of PHP 8 constructs stay off for 7.x.'; + } + + $run = new UpgradeCheck( + $this->project->createLayer( + $plugins, + $this->types, + $versions, + $names->declarations, + [self::Unseen => ['classNameString' => 'reported', 'dynamicAccess' => 'reported']], + ), + [...self::Fixes, self::Unseen, ...$discovered->findReachingPackages()], + self::Sets, + $this->project->configFile === null ? $this->project->config : null, + ); + [$factory, $resolution] = $run->resolve($this->project->config, $this->project->root); + $this->onProgress?->__invoke('checking ' . count($files) . ' files'); + $collected = new CollectingReporter; + $result = $factory->createRunner($resolution, cache: false) + ->run($files, false, $collected, $this->createWorkers?->__invoke($run, count($files))); + [$topics, $unseen] = self::collectTopics($collected->violations, $resolution, $today, $targets); + $packages = ProjectPackages::read($this->project->root); + $composer = Composer::forLockOf($packages); + + return new Estimate( + targets: $targets, + topics: $topics, + files: count($files), + blindSpots: new BlindSpots( + $unseen[UnseenReferencesRule::ClassNameString] ?? 0, + $unseen[UnseenReferencesRule::DynamicAccess] ?? 0, + $this->countOtherFiles($runner, $scope), + count($found->generated), + ), + blockers: $composer === null ? [] : $this->findBlockers($composer, $targets), + missingData: $this->findMissingData($packages), + knownVersions: $discovered->findKnownVersions(), + namesMeasured: $names->declarations !== null, + types: $resolution->resolvedConfig->typeAnalysis !== null, + warnings: [...array_keys($resolution->warnings), ...$warnings], + moves: $composer === null || $this->offline || $this->library ? null : $this->findMoves($composer, $packages, $targets), + unprocessed: self::collectUnprocessed($result), + paths: $paths ? $scope : [], + library: $this->library, + ); + } + + + /** + * The topics of the places the check found, the jump first and each phase by its count of places, and the places of + * what the upgrade cannot see by their decision. + * @param array> $violations the path => what the file violates + * @param list $targets + * @return array{list, array} + */ + private static function collectTopics(array $violations, ResolvedProject $resolution, ResolvedProject $today, array $targets): array + { + $sets = array_map(fn(string $set) => array_flip($resolution->expandName($set)->paths), array_combine(self::Sets, self::Sets)); + $topics = $unseen = []; + foreach ($violations as $path => $list) { + foreach ($list as $violation) { + if (str_starts_with($violation->decision, self::Unseen . '.')) { + $unseen[$violation->decision] = ($unseen[$violation->decision] ?? 0) + 1; + continue; + } + + $phase = self::findPhase($violation, $today); + $library = $violation->source->library ?? self::findLibrary($violation->decision, $resolution); + $name = $library ?? $violation->decision; + $key = "$name|$phase->value"; + $topics[$key] ??= [ + 'name' => $name, + 'set' => self::findSet($violation, $sets), + 'phase' => $phase, + // a decision of no library is made by the target, where there is only one + 'constraint' => self::findConstraint( + $library ?? (count($targets) === 1 ? $targets[0]->package : null), + $phase, + $targets, + $today, + ), + 'files' => [], + 'places' => array_fill_keys(array_column(Fixability::cases(), 'value'), 0), + ]; + $topics[$key]['files'][$path] = true; + $topics[$key]['places'][Fixability::of($violation)->value]++; + } + } + + $topics = array_map( + fn(array $topic) => new Topic( + $topic['name'], + $topic['set'], + $topic['phase'], + count($topic['files']), + $topic['places'], + $topic['constraint'], + ), + array_values($topics), + ); + usort($topics, fn(Topic $a, Topic $b) => [$b->phase === Phase::Jump, $b->countPlaces(), $a->name] + <=> [$a->phase === Phase::Jump, $a->countPlaces(), $b->name]); + return [$topics, $unseen]; + } + + + /** + * What the fixes of a topic of the library are right on: its constraint of today in the bridge, and in the jump the one + * the target raises it to, as the plan writes it. + * @param list $targets + */ + private static function findConstraint(?string $library, Phase $phase, array $targets, ResolvedProject $today): ?string + { + $required = $library === null ? null : $today->projectPackages->required[$library] ?? null; + $target = array_find($targets, fn(Target $target) => $target->package === $library); + return match ($phase) { + Phase::Bridge => $required, + Phase::Jump => $target === null ? null : Constraints::raiseConstraint(trim((string) $required), $target->version), + }; + } + + + /** + * The files the check could not process, by why. + * @return array + */ + private static function collectUnprocessed(RunResult $result): array + { + $failed = []; + foreach ($result->files as $summary) { + if ($summary->syntaxError !== null || $summary->failure !== null) { + $failed[$summary->path] = $summary->failure ?? "Syntax error: $summary->syntaxError"; + } + } + + return $failed; + } + + + /** + * The library whose upgrading data alone fill the map of the decision, which a place of a rule that does not say + * which entry it reports belongs to; null for a decision no map of such data fills. + */ + private static function findLibrary(string $decision, ResolvedProject $resolution): ?string + { + $values = $resolution->resolvedConfig->values; + $value = $values->has($decision) ? $values->get($decision) : null; + if (!$value?->domain instanceof Map || $value->isKept()) { + return null; + } + + $libraries = array_unique(array_map( + fn(string $key) => $values->getEntryOrigin($decision, $key)?->library, + array_keys($value->getEntries()), + )); + return count($libraries) === 1 ? reset($libraries) : null; + } + + + /** + * The phase of a place: an entry of upgrading data by the version its fix is right from against the lowest version the + * project allows today, any other place by whether its decision runs for the project as it is today, which one the + * data of a newer version turn on does not. + */ + private static function findPhase(Violation $violation, ResolvedProject $today): Phase + { + $source = $violation->source; + if ($source?->library !== null && $source->since !== null) { + $lowest = $today->projectPackages->findVersion($source->library); + return $lowest !== null && version_compare($lowest, $source->from ?? $source->since, '>=') ? Phase::Bridge : Phase::Jump; + } + + $decision = $today->resolvedConfig->decisions[$violation->decision] ?? null; + return $decision === null || ($decision->inactive !== null && $decision->inactive !== InactiveReason::OnlyOverride) + ? Phase::Jump + : Phase::Bridge; + } + + + /** + * The set of a place: the first whose decisions its decision is one of, and `deprecations`, which lays them, for an + * entry of upgrading data. + * @param array> $sets set => its decisions as keys + */ + private static function findSet(Violation $violation, array $sets): string + { + return $violation->source === null + ? array_find_key($sets, fn(array $paths) => isset($paths[$violation->decision])) ?? self::Sets[0] + : self::Sets[0]; + } + + + /** + * The files of the scope no rule reads that an upgrade may have to change as well, a template or a configuration, by + * their extension. + * @param list $scope + * @return array extension => count + */ + private function countOtherFiles(Runner $runner, array $scope): array + { + $masks = array_values(array_map( + fn(string $extension) => "*.$extension", + array_diff(self::OtherExtensions, $this->project->config->fileExtensions), + )); + $counts = []; + foreach ($scope as $path) { + $path = Helpers::toAbsolutePath($path, $this->project->root); + foreach (is_dir($path) ? Finder::findFiles($masks)->from($path) : [] as $file) { + $file = Helpers::canonicalizePath($file->getPathname()); + if (!$runner->files->excludes($file, $this->project->config->paths)) { + $extension = strtolower(pathinfo($file, PATHINFO_EXTENSION)); + $counts[$extension] = ($counts[$extension] ?? 0) + 1; + } + } + } + + ksort($counts); + return $counts; + } + + + /** + * What the lock of the project holds that refuses each target. + * @param list $targets + * @return list + */ + private function findBlockers(Composer $composer, array $targets): array + { + $this->onProgress?->__invoke('asking Composer what the lock refuses'); + return array_map($composer->findBlockers(...), $targets); + } + + + /** + * What raising the constraints to the targets as the plan raises them moves, as the dry run of Composer says, which + * needs the network. + * @param list $targets + */ + private function findMoves(Composer $composer, ProjectPackages $packages, array $targets): Moves + { + $this->onProgress?->__invoke('asking Composer what the update moves'); + $constraints = new Constraints($packages)->raise($targets); + return $constraints === [] ? new Moves : $composer->findMoves($constraints); + } + + + /** + * The packages of upgrading data about a library the project requires, which neither the project nor DressCode has. + * @return array> package => the libraries of the project it is about + */ + private function findMissingData(ProjectPackages $project): array + { + $catalogue = DataPackageCatalogue::load($this->project->getCacheDir(), $this->offline); + $missing = []; + foreach (PackageDiscovery::findMissingDataPackages($project, $catalogue) as $package) { + $missing[$package] = array_values(array_filter( + array_keys($project->required), + fn(string $library) => PackageDiscovery::isAbout($catalogue[$package], $library), + )); + } + + return $missing; + } +} diff --git a/src/Upgrade/FixStep.php b/src/Upgrade/FixStep.php new file mode 100644 index 0000000000..874e91180e --- /dev/null +++ b/src/Upgrade/FixStep.php @@ -0,0 +1,24 @@ + as `--only` takes them, each made and committed apart */ + public array $topics, + public bool $skip = false, + ) { + } +} diff --git a/src/Upgrade/Git.php b/src/Upgrade/Git.php new file mode 100644 index 0000000000..2004c88fc0 --- /dev/null +++ b/src/Upgrade/Git.php @@ -0,0 +1,159 @@ +run(['rev-parse', '--absolute-git-dir'], errors: false); + return $exit === 0 && !$this->ignoresRoot() ? trim($output) : null; + } + + + /** + * Whether the tracked files have changes, the files given aside. + * @param list $except relative to the root + */ + public function readStatus(array $except = []): WorkingTree + { + $excludes = array_map(fn(string $path) => ":(exclude,literal)$path", $except); + [$exit, $status] = $this->run(['status', '--porcelain', '--untracked-files=no', '--', '.', ...$excludes]); + return match (true) { + $exit !== 0, $this->ignoresRoot() => WorkingTree::Unavailable, + trim($status) === '' => WorkingTree::Clean, + default => WorkingTree::Dirty, + }; + } + + + /** + * The files of those given that git tracks or would add, those it ignores aside. + * @param list $paths relative to the root + * @return list + * @throws GitException + */ + public function listUnignored(array $paths): array + { + $arguments = ['ls-files', '-z', '--cached', '--others', '--exclude-standard', '--', ...self::toPathspecs($paths)]; + $output = $this->runOrThrow($arguments, errors: false); + return array_values(array_intersect($paths, explode("\0", $output))); + } + + + /** + * Commits the files with the texts given through an index of its own, so that the working tree stays as it is and the + * index changes only in those files, which it then takes as committed; the hooks of the repository run as for any + * commit. + * @param array $files relative to the root => text + * @throws GitException where git refuses, a hook of the repository among the reasons + */ + public function commit(array $files, string $subject, string $body): void + { + $pathspecs = self::toPathspecs(array_map(strval(...), array_keys($files))); + $index = sys_get_temp_dir() . '/dresscode-index-' . bin2hex(random_bytes(8)); + $env = ['GIT_INDEX_FILE' => $index]; + try { + if ($this->run(['rev-parse', '--verify', '--quiet', 'HEAD'])[0] === 0) { + $this->runOrThrow(['read-tree', 'HEAD'], env: $env); + } + + // a file keeps the mode it has, and its text is cleaned by the attributes as `git add` would clean it; the index + // names it from the top of the repository, which may lie above the root + $modes = []; + $staged = $this->runOrThrow(['ls-files', '--stage', '--full-name', '-z', '--', ...$pathspecs], env: $env, errors: false); + foreach (array_filter(explode("\0", $staged)) as $entry) { + [$meta, $name] = explode("\t", $entry, 2) + [1 => '']; + $modes[$name] = explode(' ', $meta)[0]; + } + + $prefix = trim($this->runOrThrow(['rev-parse', '--show-prefix'], errors: false)); + $entries = ''; + foreach ($files as $path => $text) { + $name = FileSystem::unixSlashes(FileSystem::normalizePath($prefix . $path)); + $blob = trim($this->runOrThrow(['hash-object', '-w', '--stdin', "--path=$path"], $text, errors: false)); + $entries .= ($modes[$name] ?? '100644') . " $blob\t$name\0"; + } + + $this->runOrThrow(['update-index', '-z', '--index-info'], input: $entries, env: $env); + $this->runOrThrow(['commit', '--quiet', '-m', $subject, '-m', $body], env: $env); + } finally { + @unlink($index); // @ git may not have written it + @unlink("$index.lock"); // @ left only by a git that failed + } + + $this->runOrThrow(['reset', '--quiet', '--', ...$pathspecs]); + } + + + /** Whether the repository git finds above ignores the root, which then lies in no repository of its own. */ + private function ignoresRoot(): bool + { + return $this->run(['check-ignore', '--quiet', '.'])[0] === 0; + } + + + /** + * @param list $paths + * @return list + */ + private static function toPathspecs(array $paths): array + { + return array_map(fn(string $path) => ":(literal)$path", $paths); + } + + + /** + * The output of git, and where it fails the reason, which only an output with the errors tells. + * @param list $arguments + * @param array $env + * @throws GitException + */ + private function runOrThrow(array $arguments, ?string $input = null, array $env = [], bool $errors = true): string + { + [$exit, $output] = $this->run($arguments, $input, $env, $errors); + if ($exit !== 0) { + $lines = array_filter(array_map(trim(...), explode("\n", $output))); + $reason = end($lines) ?: ($exit === null ? 'it did not end in time' : "exit code $exit"); + throw new GitException("`git $arguments[0]` failed: $reason"); + } + + return $output; + } + + + /** + * @param list $arguments + * @param array $env + * @return array{?int, string} + */ + private function run(array $arguments, ?string $input = null, array $env = [], bool $errors = true): array + { + return ProcessRunner::run(['git', ...$arguments], $this->root, self::Timeout, $input, $errors, $env); + } +} diff --git a/src/Upgrade/ManualStep.php b/src/Upgrade/ManualStep.php new file mode 100644 index 0000000000..53a1377c89 --- /dev/null +++ b/src/Upgrade/ManualStep.php @@ -0,0 +1,30 @@ +target->package} {$this->target->version}"; + } +} diff --git a/src/Upgrade/Move.php b/src/Upgrade/Move.php new file mode 100644 index 0000000000..c1effbfa65 --- /dev/null +++ b/src/Upgrade/Move.php @@ -0,0 +1,67 @@ +from), self::splitVersion($this->to)]; + return $to[0] !== $from[0] || ($to[0] === 0 && $to[1] !== $from[1]); + } + + + /** + * Whether the upgrading data reach the minor version the package moves to, `4.2` of `v4.2.3`, by the newest version + * they know of each library; data of its major version that stop below it, up to `4.1`, do not. + * @param array $knownVersions library => the newest version its data know + */ + public function isKnown(array $knownVersions): bool + { + [$major, $minor] = self::splitVersion($this->to); + $known = $knownVersions[$this->package] ?? null; + return $known !== null && version_compare($known, "$major.$minor", '>='); + } + + + /** + * Whether the upgrading data reach into the major version the package moves to, or the minor one below 1.0, if + * perhaps not up to the version itself. + * @param array $knownVersions library => the newest version its data know + */ + public function isSeriesKnown(array $knownVersions): bool + { + [$major, $minor] = self::splitVersion($this->to); + $known = $knownVersions[$this->package] ?? null; + return $known !== null && version_compare($known, $major === 0 ? "0.$minor" : "$major.0", '>='); + } + + + /** @return array{int, int} the major and the minor number of a version as Composer writes it, `v3.2.10` */ + private static function splitVersion(string $version): array + { + preg_match('~^v?(\d+)(?:\.(\d+))?~', $version, $m); + return [(int) ($m[1] ?? 0), (int) ($m[2] ?? 0)]; + } +} diff --git a/src/Upgrade/Moves.php b/src/Upgrade/Moves.php new file mode 100644 index 0000000000..a79542acc8 --- /dev/null +++ b/src/Upgrade/Moves.php @@ -0,0 +1,35 @@ + */ + public array $packages = [], + /** why Composer gave no answer, null where it gave one */ + public ?string $unknown = null, + ) { + } + + + /** + * The moves across a major version, where a package may break its API. + * @return list + */ + public function findMajor(): array + { + return array_values(array_filter($this->packages, fn(Move $move) => $move->isMajor())); + } +} diff --git a/src/Upgrade/NameResolution.php b/src/Upgrade/NameResolution.php new file mode 100644 index 0000000000..7740578432 --- /dev/null +++ b/src/Upgrade/NameResolution.php @@ -0,0 +1,27 @@ + $constraints package => constraint + * @return list + * @throws ComposerException + */ + function previewRequire(array $constraints, bool $update = true, ?string $platform = null): array; + + /** + * Raises the constraints and updates what they move. + * @param array $constraints package => constraint + * @throws ComposerException + */ + function require(array $constraints, bool $update = true, ?string $platform = null): void; + + /** + * What updating the packages to the newest versions the constraints allow would change. + * @return list + * @throws ComposerException + */ + function previewUpdate(): array; + + /** @throws ComposerException */ + function update(): void; + + /** @throws ComposerException */ + function install(): void; +} diff --git a/src/Upgrade/Plan.php b/src/Upgrade/Plan.php new file mode 100644 index 0000000000..a1027f753b --- /dev/null +++ b/src/Upgrade/Plan.php @@ -0,0 +1,96 @@ + */ + public array $targets, + /** @var list */ + public array $steps, + /** the version of DressCode that made the plan */ + public string $toolVersion, + /** @var array package of upgrading data => its version, `php` for the data DressCode ships */ + public array $dataVersions = [], + /** the command testing the whole project, `{junit}` standing for the file it writes its results to */ + public ?string $testCommand = null, + /** the command testing what is quick to test, after every step */ + public ?string $quickTestCommand = null, + /** @var list the paths within the configured ones the fixes are narrowed to, relative to the root; none for all */ + public array $paths = [], + /** @var list the files the estimate could not process, whose places no step counts on, relative to the root */ + public array $unestimated = [], + /** @var array> a package of upgrading data the estimate lacked => the libraries it is about */ + public array $missingData = [], + ) { + } + + + /** Whether the plan was made with what is given, the version of DressCode and those of the upgrading data. */ + public function isMadeWith(Provenance $provenance): bool + { + return $this->toolVersion === $provenance->tool && $this->dataVersions === $provenance->data; + } + + + /** + * The commands of the tests the plan gives, the whole suite first. + * @return list + */ + public function listTestCommands(): array + { + return array_values(array_filter([$this->testCommand, $this->quickTestCommand])); + } + + + /** The command testing after a step: the whole suite where `$whole`, else the quicker one, each standing in for the other. */ + public function selectTestCommand(bool $whole): ?string + { + return $whole ? $this->testCommand ?? $this->quickTestCommand : $this->quickTestCommand ?? $this->testCommand; + } + + + /** + * The steps the run makes, those the user left out aside, by their number from 1. + * @return array + */ + public function findSteps(): array + { + $steps = []; + foreach ($this->steps as $index => $step) { + if (!$step->skip) { + $steps[$index + 1] = $step; + } + } + + return $steps; + } + + + /** + * The step raising the lower bounds that the project has not made yet, before which the code shows no task of the + * steps after it; null where none is due. + */ + public function findDueRaise(ProjectPackages $packages): ?int + { + return array_find_key( + $this->findSteps(), + fn(Step $step) => $step instanceof ComposerStep && $step->update && $step->require !== [] && !$step->isDoneIn($packages), + ); + } +} diff --git a/src/Upgrade/PlanBuilder.php b/src/Upgrade/PlanBuilder.php new file mode 100644 index 0000000000..ccebd3214e --- /dev/null +++ b/src/Upgrade/PlanBuilder.php @@ -0,0 +1,109 @@ +library; + $constraints = new Constraints($this->project); + $steps = []; + foreach ($estimate->blockers as $blockers) { + if ($blockers->packages !== []) { + $steps[] = new ManualStep( + 'make way for ' + . $blockers->target->format() + . ': ' + . implode(', ', array_map(fn(Blocker $blocker) => $blocker->package, $blockers->packages)), + $blockers->target, + ); + } elseif ($blockers->unknown !== null) { // not knowing what refuses the target is no knowing that nothing does + $steps[] = new ManualStep("make way for {$blockers->target->format()}, which Composer could not tell", $blockers->target); + } + } + + $steps[] = self::createFix('works on the versions allowed today', $estimate->findTopics(Phase::Bridge, 'deprecations')); + $require = $library ? $constraints->widen($estimate->targets) : $constraints->raise($estimate->targets); + // a platform below the target is raised even where composer.json requires the target already + $platform = $library ? null : $constraints->raisePlatform($estimate->targets); + if ($require !== [] || $platform !== null) { + $versions = Target::collectVersions($estimate->targets); + $changes = []; + foreach ($require as $package => $constraint) { + $bound = $library ? null : Constraints::findPassedUpperBound($this->project->required[$package] ?? '', $versions[$package]); + $changes[] = "$package to $constraint" . ($bound === null ? '' : " past its upper bound $bound"); + } + + if ($platform !== null) { + $changes[] = "config.platform.php to $platform"; + } + + $steps[] = new ComposerStep( + ($library ? 'widen ' : 'raise ') . implode(', ', $changes), + $require, + update: !$library, + platform: $platform, + ); + } + + if (!$library) { + $steps[] = self::createFix('needs the targets', $estimate->findTopics(Phase::Jump, 'deprecations')); + $steps[] = self::createFix('code for the versions given up', [ + ...$estimate->findTopics(Phase::Bridge, 'cleanup'), + ...$estimate->findTopics(Phase::Jump, 'cleanup'), + ]); + // the raise installs the lowest versions, which the code is written for, and the application runs the newest + if ($require !== []) { + $steps[] = new UpdateStep('update to the newest versions'); + } + } + + $steps[] = self::createFix('what the targets offer', [ + ...$estimate->findTopics(Phase::Bridge, 'modernizations'), + ...$library ? [] : $estimate->findTopics(Phase::Jump, 'modernizations'), + ], skip: true); + + $provenance = Provenance::current($this->project); + return new Plan( + $estimate->targets, + array_values(array_filter($steps)), + $provenance->tool, + $provenance->data, + $testCommand, + $quickTestCommand, + $estimate->paths, + array_keys($estimate->unprocessed), + $estimate->missingData, + ); + } + + + /** @param list $topics */ + private static function createFix(string $title, array $topics, bool $skip = false): ?FixStep + { + $names = array_values(array_unique(array_map(fn(Topic $topic) => $topic->name, $topics))); + return $names === [] ? null : new FixStep($title, $names, $skip); + } +} diff --git a/src/Upgrade/PlanFile.php b/src/Upgrade/PlanFile.php new file mode 100644 index 0000000000..a8ad9bed3f --- /dev/null +++ b/src/Upgrade/PlanFile.php @@ -0,0 +1,301 @@ + its kind, the word of the file */ + private const Kinds = [ + FixStep::class => 'fix', + ComposerStep::class => 'composer', + UpdateStep::class => 'update', + ManualStep::class => 'manual', + ]; + + /** the keys of a plan */ + private const Keys = ['version', 'toolVersion', 'dataVersions', 'targets', 'paths', 'tests', 'estimate', 'steps']; + + /** the keys of a step that its kind takes, beside `title`, `kind` and `skip` */ + private const StepKeys = ['fix' => ['topics'], 'composer' => ['require', 'update', 'platform'], 'update' => [], 'manual' => ['target']]; + + + /** Whether the project in the root has a saved plan. */ + public static function exists(string $root): bool + { + return is_file("$root/" . self::Name); + } + + + /** The identity of the saved plan, a hash of its text, by which a tool tells one plan from another; null without one. */ + public static function identify(string $root): ?string + { + $text = @file_get_contents("$root/" . self::Name); // @ the plan may not be saved + return $text === false ? null : substr(hash('xxh128', $text), 0, 16); + } + + + /** + * The saved plan of the project in the root. + * @throws ConfigurationException for a file that is no plan + */ + public static function read(string $root): Plan + { + $file = "$root/" . self::Name; + try { + $data = Neon::decode(FileSystem::read($file)); + } catch (NeonException|IOException $e) { + throw new ConfigurationException("The plan `$file` cannot be read: {$e->getMessage()}", previous: $e); + } + + $fail = fn(string $what) => throw new ConfigurationException("The plan `$file`: $what."); + if (!is_array($data)) { + $fail('a map of `version`, `targets` and `steps` is expected'); + } elseif (($data['version'] ?? null) !== self::Version) { + $fail('`version: ' . self::Version . '` is expected, the plan of another version of DressCode is made anew'); + } elseif (($unknown = array_diff(array_keys($data), self::Keys)) !== []) { + $fail('`' . reset($unknown) . '` is no key of a plan'); + } + + $targets = []; + foreach (self::readMap($data['targets'] ?? [], 'targets', $fail) as $package => $version) { + if (!Target::isPackageName($package)) { + $fail("`targets.$package` must be `php` or a package as `vendor/name`"); + } elseif (!Versions::isVersion($version)) { + $fail("`targets.$package` must be a version, as `'8.4'`"); + } + + $targets[] = new Target($package, $version); + } + + $tests = self::readMap($data['tests'] ?? [], 'tests', $fail); + if (($unknown = array_diff(array_keys($tests), ['command', 'quick'])) !== []) { + $fail('`tests.' . reset($unknown) . '` is no key of `tests`, which takes `command` and `quick`'); + } + + foreach ($tests as $key => $command) { + if (!TestResults::hasJunitPlaceholder($command)) { + $fail("`tests.$key` must be a command writing its JUnit report where `{junit}` stands"); + } + } + + $estimate = $data['estimate'] ?? []; + if (!is_array($estimate) || ($unknown = array_diff(array_keys($estimate), ['unprocessed', 'missingData'])) !== []) { + $fail(is_array($estimate) + ? '`estimate.' . reset($unknown) . '` is no key of `estimate`, which takes `unprocessed` and `missingData`' + : '`estimate` must be a map'); + } + + $missingData = []; + $missing = $estimate['missingData'] ?? []; + foreach (is_array($missing) ? $missing : $fail('`estimate.missingData` must be a map of lists') as $package => $libraries) { + $missingData[(string) $package] = self::readList($libraries, "estimate.missingData.$package", $fail); + } + + $steps = $data['steps'] ?? []; + if (!is_array($steps) || !array_is_list($steps)) { + $fail('`steps` must be a list'); + } + + foreach ($steps as $index => $step) { + $steps[$index] = self::readStep($step, 'steps.' . ($index + 1), $targets, $fail); + } + + if ($targets === [] || $steps === []) { + $fail('`targets` and `steps` are expected'); + } + + return new Plan( + $targets, + $steps, + self::readString($data['toolVersion'] ?? '', 'toolVersion', $fail), + self::readMap($data['dataVersions'] ?? [], 'dataVersions', $fail), + $tests['command'] ?? null, + $tests['quick'] ?? null, + self::readList($data['paths'] ?? [], 'paths', $fail), + self::readList($estimate['unprocessed'] ?? [], 'estimate.unprocessed', $fail), + $missingData, + ); + } + + + /** Saves the plan into the root of its project. */ + public static function write(Plan $plan, string $root): void + { + $steps = array_map(fn(Step $step) => [...self::encodeStep($step), ...$step->skip ? ['skip' => true] : []], $plan->steps); + $data = array_filter([ + 'version' => self::Version, + 'toolVersion' => $plan->toolVersion, + 'dataVersions' => $plan->dataVersions, + 'targets' => Target::collectVersions($plan->targets), + 'paths' => $plan->paths, + 'tests' => array_filter(['command' => $plan->testCommand, 'quick' => $plan->quickTestCommand]), + 'estimate' => array_filter(['unprocessed' => $plan->unestimated, 'missingData' => $plan->missingData]), + 'steps' => $steps, + ], fn($value) => $value !== []); + $header = '# dresscode upgrade: the plan for ' . implode(', ', array_map(fn(Target $target) => $target->format(), $plan->targets)) + . "; set `skip: true` to leave a step out, and `dresscode upgrade run` runs what is left\n\n"; + Helpers::replaceFile("$root/" . self::Name, $header . Neon::encode($data, blockMode: true)); + } + + + /** + * The step as the plan file writes it, `skip` aside. + * @return array + */ + public static function encodeStep(Step $step): array + { + return [ + 'title' => $step->title, + 'kind' => self::Kinds[$step::class], + ...match (true) { + $step instanceof FixStep => ['topics' => $step->topics], + $step instanceof ComposerStep => [ + 'require' => $step->require, + ...$step->update ? [] : ['update' => false], + ...$step->platform === null ? [] : ['platform' => $step->platform], + ], + $step instanceof ManualStep => ['target' => $step->target->package], + default => [], + }, + ]; + } + + + /** + * @param list $targets those of the plan, one of which a manual step makes way for + * @param \Closure(string): never $fail + */ + private static function readStep(mixed $step, string $at, array $targets, \Closure $fail): Step + { + $kind = is_array($step) ? $step['kind'] ?? null : null; + if (!is_string($kind) || !isset(self::StepKeys[$kind])) { + $fail("`$at` must give its `kind`, `fix`, `composer`, `update` or `manual`"); + } elseif (($unknown = array_diff(array_keys($step), ['title', 'kind', 'skip', ...self::StepKeys[$kind]])) !== []) { + $fail("`$at." . reset($unknown) . "` is no key of a step of the kind `$kind`"); + } + + $title = self::readString($step['title'] ?? $kind, "$at.title", $fail); + $skip = self::readBool($step['skip'] ?? false, "$at.skip", $fail); + return match ($kind) { + 'fix' => new FixStep( + $title, + self::readList($step['topics'] ?? [], "$at.topics", $fail) ?: $fail("`$at.topics` must name the topics the step fixes"), + $skip, + ), + 'composer' => new ComposerStep( + $title, + self::readConstraints( + $step['require'] ?? [], + "$at.require", + $fail, + required: !isset($step['platform']), + ), + self::readBool($step['update'] ?? true, "$at.update", $fail), + isset($step['platform']) ? self::readVersion($step['platform'], "$at.platform", $fail) : null, + $skip, + ), + 'update' => new UpdateStep($title, $skip), + default => new ManualStep( + $title, + array_find($targets, fn(Target $target) => $target->package === ($step['target'] ?? null)) + ?? $fail("`$at.target` must name a package of `targets`"), + $skip, + ), + }; + } + + + /** + * @param \Closure(string): never $fail + * @return array package => constraint + */ + private static function readConstraints(mixed $value, string $at, \Closure $fail, bool $required): array + { + $require = self::readMap($value, $at, $fail); + if ($require === [] && $required) { + $fail("`$at` must give the constraints the step writes, or the step its `platform`"); + } + + foreach ($require as $package => $constraint) { + if (!Target::isPackageName($package)) { + $fail("`$at.$package` must be `php` or a package as `vendor/name`"); + } elseif (!Versions::isConstraint($constraint)) { + $fail("`$at.$package` must be a constraint Composer reads, as `^8.4`"); + } + } + + return $require; + } + + + /** + * @param \Closure(string): never $fail + * @return list + */ + private static function readList(mixed $value, string $at, \Closure $fail): array + { + return is_array($value) && array_is_list($value) && array_all($value, fn($item) => is_string($item)) + ? $value + : $fail("`$at` must be a list of strings"); + } + + + /** + * @param \Closure(string): never $fail + * @return array + */ + private static function readMap(mixed $value, string $at, \Closure $fail): array + { + return is_array($value) && array_all($value, fn($item, $key) => is_string($key) && is_string($item)) + ? $value + : $fail("`$at` must be a map of strings, a version quoted as `'8.4'`"); + } + + + /** @param \Closure(string): never $fail */ + private static function readVersion(mixed $value, string $at, \Closure $fail): string + { + return is_string($value) && Versions::isVersion($value) ? $value : $fail("`$at` must be a version, as `'8.4'`"); + } + + + /** @param \Closure(string): never $fail */ + private static function readString(mixed $value, string $at, \Closure $fail): string + { + return is_string($value) ? $value : $fail("`$at` must be a string"); + } + + + /** @param \Closure(string): never $fail */ + private static function readBool(mixed $value, string $at, \Closure $fail): bool + { + return is_bool($value) ? $value : $fail("`$at` must be `true` or `false`"); + } +} diff --git a/src/Upgrade/PlanRunner.php b/src/Upgrade/PlanRunner.php new file mode 100644 index 0000000000..a7c51336d2 --- /dev/null +++ b/src/Upgrade/PlanRunner.php @@ -0,0 +1,619 @@ +configFile = $project->configFile ?? throw new ConfigurationException( + 'The upgrade rewrites the code in the style the configuration of the project keeps, and the project has none; write it with `dresscode init` first.', + ); + $this->state = new RunState($project); + $this->git = $git ?? new Git($project->root); + $this->composer = $composer ?? Composer::forProject($project->root); + $this->tests = $tests ?? new ProcessTestRunner; + } + + + /** Whether the tracked files of the working tree have changes of their own, which the changes of a run mix with. */ + public function hasOwnChanges(): bool + { + return $this->git->readStatus([PlanFile::Name]) === WorkingTree::Dirty; + } + + + /** + * Runs the steps the plan does not leave out, or with `$singleStep` that one alone; a manual step passes once + * Composer says nothing of the lock refuses its target, and a step of Composer that is not done yet is made once + * `$approve` agrees to what Composer says it changes; a raise stops a run of the whole plan, which `$resumed` goes on + * after in a process that loads what the raise installed. Where a run was interrupted in a step, it runs nothing + * unless `$discard` says to go on from the files as they are. + * @param ?\Closure(DependencyStep, list): bool $approve told the step and the operations of Composer it makes + * @throws ConfigurationException + */ + public function run( + Plan $plan, + ?int $singleStep = null, + ?\Closure $approve = null, + bool $discard = false, + ?RunOutcome $resumed = null, + ): RunOutcome + { + $warnings = []; + $outcome = $this->state->runExclusively(function () use ($plan, $singleStep, $approve, $discard, $resumed, &$warnings) { + return $this->runSteps($plan, $singleStep, $approve, $discard, $resumed, $warnings); + }); + return $warnings === [] ? $outcome : $outcome->withWarnings($warnings); + } + + + /** + * @param ?\Closure(DependencyStep, list): bool $approve + * @param list $warnings what the run tells the user beside its outcome, filled as it goes + * @throws ConfigurationException + */ + private function runSteps( + Plan $plan, + ?int $singleStep, + ?\Closure $approve, + bool $discard, + ?RunOutcome $resumed, + array &$warnings, + ): RunOutcome + { + $steps = $plan->findSteps(); + if ($singleStep !== null && !isset($steps[$singleStep])) { + throw new ConfigurationException(isset($plan->steps[$singleStep - 1]) + ? "Step $singleStep of the plan is left out with `skip: true`, so it is not run." + : "The plan has no step $singleStep; it has " . count($plan->steps) . '.'); + } + + // a step that left files it could not process is committed once a later run makes it whole + $uncommitted = $this->commit ? $this->findUncommitted($steps, $discard) : null; + $status = $this->commit + ? $this->git->readStatus([PlanFile::Name, ...$uncommitted?->listOwnFiles($this->project->root) ?? []]) + : null; + if ($status === WorkingTree::Unavailable) { + throw new ConfigurationException('`--commit` commits into the git repository of the project, and git finds none there that tracks it, or refuses to tell its status.'); + } elseif ($status === WorkingTree::Dirty) { + throw new ConfigurationException('A commit of a topic takes the files it changed whole, and the working tree has changes of its own; commit or stash them first.'); + } + + $snapshots = $this->state->snapshots; + foreach ($snapshots->findInterrupted() as $number => $files) { + if (!$discard) { + return new RunOutcome(RunStop::Interrupted, $number, interrupted: $files); + } + + $snapshots->drop($number); + } + + $baselines = []; + foreach ($plan->listTestCommands() as $command) { + $baselines[$command] = $this->findBaseline($command); + if ($baselines[$command]->crash !== null) { + $crash = "the tests of `$command` do not run before the first step, as {$baselines[$command]->crash}"; + return new RunOutcome(RunStop::Tests, null, crash: $crash); + } + } + + $satisfiedRequirements = $this->project->measureSatisfiedRequirements(); + $names = $this->project->resolveNames(); + $declarations = $names->declarations; + if ($names->warning !== null) { + $warnings[] = $names->warning; + } + + $lastFixStep = array_key_last(array_filter($steps, fn(Step $step) => $step instanceof FixStep)); + $applied = $resumed->applied ?? []; + $tasks = $resumed->tasks ?? []; + $followsRaise = $resumed !== null; + // the step of Composer whose raise no tests have run after yet, which the journal keeps across the runs + $untestedRaise = $resumed->step ?? $this->state->journal->findStep(); + $testBaseline = null; // what the last tests were compared with + $lastTaskStep = max([0, ...array_keys(array_filter($applied, fn(array $topics) => array_intersect_key($tasks, $topics) !== []))]); + foreach ($steps as $number => $step) { + if (($singleStep !== null && $number !== $singleStep) || $number <= ($resumed->step ?? 0)) { + continue; + } elseif ($step instanceof ManualStep) { + $blockers = $this->findBlockers($number, $step); + if ($blockers !== null) { + return new RunOutcome(RunStop::Manual, $number, $applied, $tasks, blockers: $blockers); + } + + continue; + + } elseif ($step instanceof DependencyStep) { + try { + // whether every package is the newest the constraints allow only Composer tells + $changes = $step instanceof UpdateStep ? $this->composer->previewUpdate() : null; + $due = $changes === null + ? $step instanceof ComposerStep && !$step->isDoneIn(ProjectPackages::read($this->project->root)) + : $changes !== []; + $done = $due ? $this->runComposerStep($number, $step, $approve, $changes) : null; + } catch (ComposerException $e) { + $done = $e->getMessage(); + } catch (CommitException $e) { + return new RunOutcome( + RunStop::Commit, + $number, + $applied, + $tasks, + raisedFiles: $this->state->journal->findChanged(), + commitFailure: $e->getMessage(), + ); + } + + if ($done !== null) { + if ($done !== true) { + return new RunOutcome( + RunStop::Composer, + $number, + $applied, + $tasks, + raisedFiles: $this->state->journal->findChanged(), + composerFailure: $done ?: null, + ); + } + + $untestedRaise = $number; + // what the raise installed is loaded anew for what runs after it, the check at the end of the plan among it + if ($singleStep === null) { + return new RunOutcome(RunStop::Raised, $number, $applied, $tasks); + } + } + + $followsRaise = true; + continue; + + } elseif (!$step instanceof FixStep) { + continue; + } + + $result = $this->fixStep($number, $step, $plan->paths, $satisfiedRequirements, $declarations); + $warnings = array_values(array_unique([...$warnings, ...$result->warnings])); + $unprocessed = $result->unprocessed; + + // the whole suite after the jump and after the last step, the quick one after the others + $command = $plan->selectTestCommand(whole: $followsRaise || $number === $lastFixStep); + if ($command !== null) { + $this->onProgress?->__invoke("step $number, running the tests"); + $testBaseline = $baselines[$command]; + $untestedRaise = null; + $failure = $this->runTests($command, $testBaseline); + if ($failure !== null) { + $unprocessed += $snapshots->restore($number, $this->project->root); + return new RunOutcome( + RunStop::Tests, + $number, + $applied, + $tasks, + $failure->newFailures, + $unprocessed, + crash: $failure->crash, + baseline: $testBaseline, + raisedFiles: $this->state->journal->findChanged(), + ); + } + } + + // a step its tests sent back applied nothing + $applied[$number] = array_map(array_keys(...), $result->written); + $snapshots->drop($number); + if ($followsRaise) { // the raise holds once a step after it is done + $this->state->journal->forget(); + } + + try { + if ($this->commit) { + $this->commitStep($number, $step, $result->written, array_keys($unprocessed), $uncommitted); + } + } catch (CommitException $e) { + return new RunOutcome( + RunStop::Commit, + $number, + $applied, + array_filter([...$tasks, ...$result->tasks]), + commitFailure: $e->getMessage(), + ); + } + + $tasks = array_filter([...$tasks, ...$result->tasks]); // the last fix of a topic tells what it leaves + $lastTaskStep = array_filter($result->tasks) === [] ? $lastTaskStep : $number; + if ($unprocessed !== []) { + return new RunOutcome(RunStop::Unprocessed, $number, $applied, $tasks, unprocessed: $unprocessed, baseline: $testBaseline); + } elseif ($followsRaise && $lastTaskStep === $number) { + return new RunOutcome(RunStop::Tasks, $number, $applied, $tasks, baseline: $testBaseline); + } + + $followsRaise = false; + } + + // a raise no fix followed is tested after it all the same, the whole suite + $command = $plan->selectTestCommand(whole: true); + if ($untestedRaise !== null && $command !== null) { + $this->onProgress?->__invoke("step $untestedRaise, running the tests"); + $testBaseline = $baselines[$command]; + $failure = $this->runTests($command, $testBaseline); + if ($failure !== null) { + return new RunOutcome( + RunStop::Tests, + $untestedRaise, + $applied, + $tasks, + $failure->newFailures, + crash: $failure->crash, + baseline: $testBaseline, + raisedFiles: $this->state->journal->findChanged(), + ); + } + + $this->state->journal->forget(); + } + + if ($tasks !== []) { // a plan is done once nothing of it is left for a human + return new RunOutcome(RunStop::Tasks, $lastTaskStep, $applied, $tasks, baseline: $testBaseline); + } elseif ($singleStep === null) { + // and once the targets find nothing in the whole scope, which the estimate the plan was made from may have missed + $this->onProgress?->__invoke('checking the code against the targets'); + $check = $this->runTopic('deprecations', $satisfiedRequirements, $declarations, $plan->paths); + if ($check->unprocessed !== []) { + return new RunOutcome(RunStop::Unprocessed, null, $applied, unprocessed: $check->unprocessed, baseline: $testBaseline); + } elseif ($check->changed !== [] || $check->tasks !== []) { + return new RunOutcome( + RunStop::Remaining, + null, + $applied, + array_filter(['deprecations' => $check->tasks]), + baseline: $testBaseline, + remaining: array_keys($check->changed), + ); + } + + // a place put off without a reason is no more done than one left, as `upgrade tasks` says + $postponed = Postponement::findIn($this->project, $plan->paths); + if ($postponed !== []) { + return new RunOutcome(RunStop::Tasks, null, $applied, baseline: $testBaseline, postponed: $postponed); + } + + $this->state->remove(); + } + + return new RunOutcome(RunStop::Done, null, $applied, $tasks, baseline: $testBaseline); + } + + + /** + * The step a run left uncommitted, which the plan must still have under its number, unless told to forget it. + * @param array $steps + * @throws ConfigurationException + */ + private function findUncommitted(array $steps, bool $discard): ?UncommittedStep + { + $uncommitted = $this->state->findUncommitted(); + $step = $uncommitted === null ? null : $steps[$uncommitted->step] ?? null; + if ($uncommitted === null || ($step !== null && UncommittedStep::identify($step) === $uncommitted->identity)) { + return $uncommitted; + } elseif (!$discard) { + throw new ConfigurationException("The plan changed since a run left step $uncommitted->step uncommitted, waiting for files it could not process; commit what it changed yourself, and `upgrade run --discard` forgets it."); + } + + $this->state->forgetUncommitted(); + return null; + } + + + /** What refuses the target of the manual step, or why Composer could not tell; null where nothing does. */ + private function findBlockers(int $number, ManualStep $step): ?Blockers + { + $this->onProgress?->__invoke("step $number, asking Composer what refuses {$step->target->format()}"); + $blockers = $this->composer->findBlockers($step->target); + return $blockers->isClear() ? null : $blockers; + } + + + /** + * Whether the step was made, once `$approve` agreed to what Composer says it changes, the files of Composer kept as + * they were before, and with commits the raise committed. + * @param ?\Closure(DependencyStep, list): bool $approve + * @param ?list $changes what Composer said the step changes, where it was asked already + * @throws ComposerException + */ + private function runComposerStep(int $number, DependencyStep $step, ?\Closure $approve, ?array $changes): bool + { + if ($approve === null) { + return false; + } + + $changes ??= $step instanceof ComposerStep ? $this->composer->previewRequire($step->require, $step->update, $step->platform) : []; + if (!$approve($step, $changes)) { + return false; + } + + $root = $this->project->root; + $composerRoot = $this->project->findComposerRoot(); + $journal = $this->state->journal; + $journal->recordBefore($number, $composerRoot); + try { + if ($step instanceof ComposerStep) { + $this->composer->require($step->require, $step->update, $step->platform); + } else { + $this->composer->update(); + } + } finally { + $journal->recordAfter($composerRoot); + } + + $raised = !$step instanceof ComposerStep || $step->isDoneIn(ProjectPackages::read($root)); + + if ($journal->findChanged() === []) { + $journal->forget(); + } + + if (!$raised) { + return false; + } elseif ($this->commit) { + try { + // the files of Composer as git names them from the root, which may lie below them + $up = str_repeat('../', substr_count(substr($root, strlen($composerRoot)), '/')); + $paths = $this->git->listUnignored(["{$up}composer.json", "{$up}composer.lock"]); + if ($paths !== []) { + $files = array_combine($paths, array_map(fn(string $path) => FileSystem::read("$root/$path"), $paths)); + $this->git->commit($files, "upgrade: $step->title", "DressCode-Upgrade-Step: $number"); + } + } catch (GitException $e) { + throw new CommitException("{$e->getMessage()}; the raise of step $number is left uncommitted.", previous: $e); + } + } + + return true; + } + + + /** + * Fixes the topics of the step one by one and writes what each changes. + * @param list $paths + * @param list $satisfied + */ + private function fixStep(int $number, FixStep $step, array $paths, array $satisfied, ?NamespaceDeclarations $declarations): StepResult + { + $written = $unprocessed = $tasks = $warnings = []; + foreach ($step->topics as $topic) { + $this->onProgress?->__invoke("step $number, fixing $topic"); + $reporter = $this->runTopic($topic, $satisfied, $declarations, $paths); + [$written[$topic], $unwritten] = $this->writeTopic($number, $reporter); + $unprocessed += $reporter->unprocessed + $unwritten; + $tasks[$topic] = $reporter->tasks; + $warnings = [...$warnings, ...$reporter->warnings]; + } + + return new StepResult($written, $unprocessed, $tasks, $warnings); + } + + + /** Runs the tests and compares them with the baseline; null where they pass. */ + private function runTests(string $command, TestResults $baseline): ?TestFailure + { + $results = $this->tests->run($command, $this->project->root); + $failures = $results->findNewFailures($baseline); + return $failures === [] && $results->crash === null ? null : new TestFailure($failures, $results->crash); + } + + + /** + * The results of the command of the tests before the first step, run once and kept for the runs that follow, each + * command its own; results whose command crashed are not kept. + */ + private function findBaseline(string $command): TestResults + { + $baseline = $this->state->findBaseline($command); + if ($baseline === null) { + $this->onProgress?->__invoke('running the tests before the first step'); + $baseline = $this->tests->run($command, $this->project->root); + if ($baseline->crash !== null) { + return $baseline; + } + + $this->state->saveBaseline($command, $baseline); + } + + return $baseline; + } + + + /** + * What the fixes of the steps the plan does not leave out leave for a human in the code as it is now, and what the + * check of the whole scope at the end of a run leaves besides, under `deprecations`, and the files they cannot + * process, changing nothing; a task confirmed by a suppression or the baseline is done, and so is not among them. + * @return array{array>, array} topic => its tasks, and file => why + * @throws ConfigurationException + */ + public function findTasks(Plan $plan): array + { + $satisfied = $this->project->measureSatisfiedRequirements(); + $declarations = $this->project->resolveNames()->declarations; + $tasks = $unprocessed = $found = []; + foreach ($plan->findSteps() as $step) { + foreach ($step instanceof FixStep ? $step->topics : [] as $topic) { + $this->onProgress?->__invoke("looking at $topic"); + $reporter = $this->runTopic($topic, $satisfied, $declarations, $plan->paths); + $tasks[$topic] = $reporter->tasks; + $unprocessed += $reporter->unprocessed; + foreach ($reporter->tasks as $task) { + $found[self::identifyTask($task)] = true; + } + } + } + + $this->onProgress?->__invoke('checking the whole scope'); + $check = $this->runTopic('deprecations', $satisfied, $declarations, $plan->paths); + $tasks['deprecations'] = array_values(array_filter($check->tasks, fn(Task $task) => !isset($found[self::identifyTask($task)]))); + $unprocessed += $check->unprocessed; + return [array_filter($tasks), $unprocessed]; + } + + + /** The place and the message of the task, the same for a topic and for the check of the whole scope finding it. */ + private static function identifyTask(Task $task): string + { + $violation = $task->violation; + return implode("\0", [$task->path, $violation->line, $violation->decision, $violation->message]); + } + + + /** + * Runs the topic over the project as it is, writing nothing, the names resolved for certain with what the namespaces + * declare where they were measured, as the estimate resolves them. + * @param list $satisfied the requirements of the style the code satisfies + * @param list $paths within the configured ones, all of them where empty + */ + private function runTopic(string $topic, array $satisfied, ?NamespaceDeclarations $declarations, array $paths): TopicReporter + { + $project = $this->project; + $layer = $project->createLayer($project->discoverPackages()->findDataPlugins(), $this->types, declarations: $declarations); + [$factory, $resolution] = new UpgradeCheck($layer, [$topic, ...$satisfied], Estimator::Sets)->resolve( + $project->config, $project->root, + ); + $runner = $factory->createRunner($resolution, cache: false, configFile: $this->configFile); + $reporter = new TopicReporter(array_keys($resolution->warnings)); + $runner->run($project->findUpgradeFiles($paths)->files, false, $reporter); + return $reporter; + } + + + /** + * Writes what the fix of the topic changes, each file kept as it was before the step first, and leaves a file changed + * since the fix read it as it is. + * @return array{array, array} the files written => their text, those not => why + */ + private function writeTopic(int $step, TopicReporter $reporter): array + { + $written = $unwritten = []; + foreach ($reporter->changed as $path => [$before, $after]) { + $file = Helpers::toAbsolutePath($path, $this->project->root); + if (@file_get_contents($file) !== $before) { // @ a file deleted since is changed too + $unwritten[$path] = 'The file changed while it was being fixed, so it was not written.'; + continue; + } + + $this->state->snapshots->record($step, $path, $before, $after); + if (!Helpers::writeFile($file, $after)) { + $unwritten[$path] = 'The file cannot be written.'; + continue; + } + + $written[$path] = $after; + } + + return [$written, $unwritten]; + } + + + /** + * Commits each topic of a step that processed every file, together with what the run before wrote in it and left + * uncommitted, and otherwise keeps the step as uncommitted for the run that processes the rest. + * @param array> $written topic => the files its fix wrote => their text + * @param list $unprocessed + * @throws ConfigurationException where git refuses a commit + */ + private function commitStep(int $number, FixStep $step, array $written, array $unprocessed, ?UncommittedStep $uncommitted): void + { + foreach ($uncommitted?->step === $number ? $uncommitted->topics : [] as $topic => $paths) { + foreach ($paths as $path) { + $file = Helpers::toAbsolutePath($path, $this->project->root); + if (!isset($written[$topic][$path]) && is_file($file)) { + $written[$topic][$path] = FileSystem::read($file); + } + } + } + + $texts = array_merge(...array_values($written)); // the text a later topic wrote last + if ($unprocessed !== []) { + $this->state->saveUncommitted(new UncommittedStep( + $number, + UncommittedStep::identify($step), + array_map(array_keys(...), $written), + $unprocessed, + array_map(fn(string $text) => hash('xxh128', $text), $texts), + )); + return; + } + + // the commits are of the texts the tests passed over, which a file changed since is not + $changed = array_keys(array_filter( + $texts, + fn(string $text, string $path) => @file_get_contents(Helpers::toAbsolutePath($path, $this->project->root)) !== $text, // @ a file deleted since is changed too + ARRAY_FILTER_USE_BOTH, + )); + if ($changed !== []) { + throw new CommitException('`' . implode('`, `', $changed) . "` changed after step $number wrote it, so the step is left uncommitted in the working tree; commit it yourself."); + } + + $this->commitTopics($number, $written); + $this->state->forgetUncommitted(); + } + + + /** + * Commits each topic of the step with the files it changed as the topic left them, which a later topic of the step + * may have changed again, and leaves the working tree as the last topic left it. + * @param array> $written topic => the files its fix wrote => their text + * @throws ConfigurationException where git refuses a commit + */ + private function commitTopics(int $step, array $written): void + { + $committed = []; + foreach (array_filter($written) as $topic => $files) { + try { + $this->git->commit($files, "upgrade: $topic", "DressCode-Upgrade-Step: $step"); + } catch (GitException $e) { + throw new CommitException( + "{$e->getMessage()}; what step $step changed is left uncommitted in the working tree" + . ($committed === [] ? '.' : ', but for the topics committed before: ' . implode(', ', $committed) . '.'), + previous: $e, + ); + } + + $committed[] = $topic; + } + } +} diff --git a/src/Upgrade/PlanStatus.php b/src/Upgrade/PlanStatus.php new file mode 100644 index 0000000000..52fc1fddde --- /dev/null +++ b/src/Upgrade/PlanStatus.php @@ -0,0 +1,81 @@ + number of the step => what is known of it */ + public array $steps, + /** @var array> step => the files a run interrupted in it may have rewritten */ + public array $interrupted, + /** the step whose raise the journal can go back before; null where it keeps none */ + public ?int $raisedStep, + /** @var list the files of Composer that raise changed and are not put back yet */ + public array $raisedFiles, + /** the files of Composer were put back, and the packages of the lock are still to be installed */ + public bool $awaitingInstall, + /** the step a run with `--commit` left uncommitted; null where none */ + public ?int $uncommittedStep, + /** @var array command of the tests => when its baseline ran, null where it has none yet */ + public array $baselines, + ) { + } + + + /** Reads the plan against the project and what a run keeps, asking Composer only what the lock refuses. */ + public static function read(Plan $plan, Project $project): self + { + $state = new RunState($project); + $packages = ProjectPackages::read($project->root); + $composer = Composer::forProject($project->root); + $steps = []; + foreach ($plan->steps as $index => $step) { + $steps[$index + 1] = match (true) { + $step->skip => StepStatus::Skipped, + $step instanceof ComposerStep => $step->isDoneIn($packages) ? StepStatus::Done : StepStatus::Due, + $step instanceof ManualStep => self::findManualStatus($step, $composer), + default => StepStatus::Unknown, + }; + } + + $baselines = []; + foreach ($plan->listTestCommands() as $command) { + $baselines[$command] = $state->findBaseline($command)?->time; + } + + return new self( + $steps, + $state->snapshots->findInterrupted(), + $state->journal->findStep(), + $state->journal->findChanged(), + $state->journal->isAwaitingInstall(), + $state->findUncommitted()?->step, + $baselines, + ); + } + + + private static function findManualStatus(ManualStep $step, PackageManager $composer): StepStatus + { + $blockers = $composer->findBlockers($step->target); + return match (true) { + $blockers->unknown !== null => StepStatus::Unknown, + $blockers->isClear() => StepStatus::Done, + default => StepStatus::Due, + }; + } +} diff --git a/src/Upgrade/Postponement.php b/src/Upgrade/Postponement.php new file mode 100644 index 0000000000..603024f679 --- /dev/null +++ b/src/Upgrade/Postponement.php @@ -0,0 +1,72 @@ + $paths + * @return list + * @throws ConfigurationException + */ + public static function findIn(Project $project, array $paths = []): array + { + $found = []; + foreach ($project->findUpgradeFiles($paths)->files as $path) { + $code = FileSystem::read(Helpers::toAbsolutePath($path, $project->root)); + foreach (@\PhpToken::tokenize($code) as $token) { // @ the lexer warns of the code, which is the check's to report + $directive = $token->is([T_COMMENT, T_DOC_COMMENT]) ? Suppression::findDirective($token->text) : null; + if ( + $directive !== null + && $directive['kind'] === 'ignore' + && str_starts_with($directive['text'], 'dresscode:') + && $directive['reason'] === '' + && self::namesUpgrade($directive['names']) + ) { + $line = $token->line + substr_count($token->text, "\n", 0, $directive['offset']); + $found[] = new self($path, $line, $directive['text']); + } + } + } + + return $found; + } + + + /** Whether a name of the list is about an upgrade: a decision of upgrading, a package of upgrading data, a library, PHP. */ + private static function namesUpgrade(string $names): bool + { + return array_any( + preg_split('~[,\s]+~', $names, -1, PREG_SPLIT_NO_EMPTY) ?: [], + fn(string $name) => str_starts_with($name, 'upgrading') + || str_starts_with($name, 'upgrade-') + || $name === 'php' + || str_starts_with($name, 'php.') + || str_contains($name, '/'), + ); + } +} diff --git a/src/Upgrade/ProcessTestRunner.php b/src/Upgrade/ProcessTestRunner.php new file mode 100644 index 0000000000..b3768e6105 --- /dev/null +++ b/src/Upgrade/ProcessTestRunner.php @@ -0,0 +1,45 @@ + 'the command of the tests did not end within ' . self::Timeout . ' s', + $results === null => 'the command of the tests wrote no JUnit report where `' . TestResults::Placeholder . '` stands', + $results->tests === [] => 'the report of the tests holds no test', + $exit === 0, in_array($exit, self::FailingExitCodes, true) && $results->countNotPassed() > 0 => null, + default => "the command of the tests ended with exit code $exit" . ($lines === [] ? '' : ': ' . end($lines)), + }; + return new TestResults($results->tests ?? [], $crash, time()); + } +} diff --git a/src/Upgrade/Project.php b/src/Upgrade/Project.php new file mode 100644 index 0000000000..2eccb3c5ee --- /dev/null +++ b/src/Upgrade/Project.php @@ -0,0 +1,205 @@ +rootPath === null) { + throw new ConfigurationException('There is nothing to upgrade: the directory has no configuration of DressCode and no `composer.json`.'); + } + + $scope = Scope::fromProject($root, null); + $config = new Config(paths: $scope->listPaths(), excludePaths: array_keys($scope->listExcludePaths())); + } + + return new self($config, $root, $configFile, $commandLine); + } + + + /** + * The packages of upgrading data that reach the project, with the versions of the targets where given. + * @param array $targets package => version + */ + public function discoverPackages(array $targets = []): PackageDiscovery + { + return PackageDiscovery::discover( + new RunnerFactory()->readProjectPackages($this->config, $this->root, commandLine: new Config(targets: $targets)), + ); + } + + + /** + * The layer an upgrade lays over the configuration: the command line, the plugins of the packages of upgrading data, + * the targets, the types, and where they were measured in every file the names resolved for certain with what the + * namespaces declare. + * @param list $plugins + * @param array $targets package => version + * @param array $decisions path => value, over those of the command line + */ + public function createLayer( + array $plugins, + bool $types, + array $targets = [], + ?NamespaceDeclarations $declarations = null, + array $decisions = [], + ): Config + { + $commandLine = $this->commandLine; + $certain = $declarations !== null; + $tree = $commandLine->decisions ?? []; + foreach ($decisions as $path => $value) { + $tree = Helpers::placeValue($tree, $path, $value); + } + + return new Config( + use: [...$commandLine->plugins ?? [], ...$commandLine->use ?? [], ...$plugins], + targets: $targets, + namespaces: $certain ? ['functions' => $declarations->functions, 'constants' => $declarations->constants] : [], + nameResolution: $certain ? 'certain' : null, + fixRisky: $commandLine->fixRisky ?? [], + severity: $commandLine->severity ?? [], + typeAnalysis: $types ? 'phpstan' : null, + decisions: $tree, + ); + } + + + /** + * How the names are resolved where the configuration says nothing of them: for certain with what the namespaces of + * the scope declare, or of the files of it given, unless a file cannot be read or does not parse. + * @param ?list $files relative to the root + */ + public function resolveNames(?array $files = null): NameResolution + { + if ($this->config->nameResolution !== null) { + return new NameResolution; + } + + $declarations = NamespaceDeclarations::collect($this->root, $files ?? $this->findFiles()); + return $declarations->unparsed === [] + ? new NameResolution($declarations) + : new NameResolution(warning: 'The names are not resolved for certain: ' . count($declarations->unparsed) . ' of the files cannot be read or do not parse.'); + } + + + /** + * The files of the scope of the configuration, or of the paths within it, relative to the root. + * @param list $paths all the configured ones where empty + * @return list + * @throws ConfigurationException + */ + private function findFiles(array $paths = []): array + { + $factory = new RunnerFactory; + return $factory->createFileFinder($factory->resolve($this->config, $this->root, $this->commandLine)) + ->findFiles($paths ?: $this->config->paths, configured: $this->config->paths); + } + + + /** + * The files the estimate and a run of its plan check, within the paths given or all the configured ones, + * those a generator wrote left out, which the estimate counts apart. + * @param list $paths relative to the root + * @throws ConfigurationException + */ + public function findUpgradeFiles(array $paths = []): UpgradeFiles + { + return UpgradeFiles::fromScope($this->root, $this->findFiles($paths)); + } + + + /** + * The style a rewrite keeps: the decisions the configuration file makes, the types left out, less each one the code + * violates anywhere, whatever its severity; none without a configuration file. + * @return list + * @throws ConfigurationException + */ + public function measureSatisfiedRequirements(): array + { + if ($this->configFile === null) { + return []; + } + + try { + $factory = new RunnerFactory(phpstanInstalled: false); + $resolution = $factory->resolve($this->config, $this->root, $this->commandLine); + } catch (ConfigurationException) { // a decision of the project needs the types, so the check takes them + $factory = new RunnerFactory; + $resolution = $factory->resolve($this->config, $this->root, $this->commandLine); + } + + $runner = $factory->createRunner($resolution, configFile: $this->configFile); + $collected = new CollectingReporter; + $runner->run($runner->files->findFiles($this->config->paths, configured: $this->config->paths), false, $collected); + $violated = []; + foreach ($collected->violations as $violations) { + foreach ($violations as $violation) { + $violated[$violation->decision] = true; + } + } + + $satisfied = []; + foreach ($resolution->resolvedConfig->decisions as $path => $decision) { + if ( + $decision->inactive === null + && $decision->decision->isRequirement() + && !$decision->value->isKept() + && !isset($violated[$path]) + ) { + $satisfied[] = $path; + } + } + + return $satisfied; + } + + + /** The directory of the `composer.json` of the project, the root or one above it; the root where there is none. */ + public function findComposerRoot(): string + { + return ProjectPackages::read($this->root)->rootPath ?? $this->root; + } + + + public function getCacheDir(): string + { + return RunnerFactory::resolveCacheDir($this->config, $this->root); + } +} diff --git a/src/Upgrade/Provenance.php b/src/Upgrade/Provenance.php new file mode 100644 index 0000000000..e6e20d6630 --- /dev/null +++ b/src/Upgrade/Provenance.php @@ -0,0 +1,47 @@ + package of upgrading data => its version, `php` for the data DressCode ships */ + public array $data, + ) { + } + + + /** What a plan made now is made with, the upgrading data the project and DressCode have; those of PHP travel with DressCode. */ + public static function current(ProjectPackages $project): self + { + $versions = [PackageDiscovery::Php => Application::Version]; + foreach ($project->installed as $package => $installed) { + if (isset($installed['extra']['dresscode']['upgrading-dir'])) { + $versions[$package] = $installed['version'] ?? 'dev'; + } + } + + foreach (array_keys(PackageDiscovery::findInstalledDataPackages()) as $package) { + $versions[$package] ??= InstalledVersions::getPrettyVersion($package) ?? 'dev'; + } + + ksort($versions); + return new self(Application::Version, $versions); + } +} diff --git a/src/Upgrade/Restoration.php b/src/Upgrade/Restoration.php new file mode 100644 index 0000000000..be8a8fa4a5 --- /dev/null +++ b/src/Upgrade/Restoration.php @@ -0,0 +1,28 @@ + the files written back, relative to the root, those of Composer by their names */ + public array $restored, + /** @var array the files left as they are => why */ + public array $left, + /** the packages of the lock are installed after the files of Composer went back */ + public bool $installs, + /** why `composer install` failed; null where it did not run or did not fail */ + public ?string $installFailure = null, + ) { + } +} diff --git a/src/Upgrade/RunOutcome.php b/src/Upgrade/RunOutcome.php new file mode 100644 index 0000000000..7636c03510 --- /dev/null +++ b/src/Upgrade/RunOutcome.php @@ -0,0 +1,120 @@ +>> step => topic => the files its fix changed, relative to the root */ + public array $applied = [], + /** @var array> topic => what its last fix left */ + public array $tasks = [], + /** @var list the tests failing after the step that passed before, none where they wrote no results */ + public array $newFailures = [], + /** @var array the files the step could not fix, write or write back, relative to the root => why */ + public array $unprocessed = [], + /** what refuses the target of the manual step the run stopped at */ + public ?Blockers $blockers = null, + /** @var list the files the interrupted step may have rewritten, relative to the root */ + public array $interrupted = [], + /** how the command of the tests crashed after the step though none of its tests failed */ + public ?string $crash = null, + /** the results before the first step the last tests of the run were compared with; null where none ran */ + public ?TestResults $baseline = null, + /** @var list the files of Composer a raise changed, which `upgrade abort` puts back */ + public array $raisedFiles = [], + /** @var list the files the targets still find something in that a fix changes and no step of the plan did */ + public array $remaining = [], + /** @var list the comments that put a place of the upgrade off without a reason, as `upgrade tasks` lists them */ + public array $postponed = [], + /** @var list what the run tells the user, an analysis that went without or upgrading data it lacked among it */ + public array $warnings = [], + /** why Composer could not raise the constraints of the step the run stopped at; null where it was not asked or did */ + public ?string $composerFailure = null, + /** why what the step changed is left uncommitted; null where it was committed or was not to be */ + public ?string $commitFailure = null, + ) { + } + + + /** + * 0 when the run is done, 1 when it leaves work for a human (tasks, tests that newly fail, what no step fixed, an + * interrupted run to put back or discard), 2 when it is incomplete, as files went unprocessed, a commit was refused or + * the tests do not run before the first step, 4 when it waits for a step outside DressCode. + */ + public function getExitCode(): int + { + return match ($this->stop) { + RunStop::Done => 0, + RunStop::Tests => $this->step === null && $this->crash !== null ? 2 : 1, + RunStop::Tasks, RunStop::Remaining, RunStop::Interrupted => 1, + RunStop::Unprocessed, RunStop::Commit => 2, + RunStop::Composer, RunStop::Raised, RunStop::Manual => 4, + }; + } + + + /** @param list $warnings */ + public function withWarnings(array $warnings): self + { + return new self(...['warnings' => array_values(array_unique([...$this->warnings, ...$warnings]))] + get_object_vars($this)); + } + + + /** + * A run stopped after a raise as the run that goes on after it reads it in another process. + * @param array $data as `toArray()` made it + */ + public static function fromArray(array $data): self + { + $applied = $tasks = []; + foreach (is_array($data['applied'] ?? null) ? $data['applied'] : [] as $step => $topics) { + foreach (is_array($topics) ? $topics : [] as $topic => $files) { + $applied[(int) $step][(string) $topic] = array_values(array_map(strval(...), (array) $files)); + } + } + + foreach (is_array($data['tasks'] ?? null) ? $data['tasks'] : [] as $topic => $list) { + $paths = array_map(strval(...), array_column((array) $list, 'path')); + $violations = WorkerCodec::decodeViolations(array_column((array) $list, 'violation')); + $tasks[(string) $topic] = array_map(fn(string $path, $violation) => new Task($path, $violation), $paths, $violations); + } + + return new self(RunStop::Raised, is_int($data['step'] ?? null) ? $data['step'] : null, $applied, $tasks); + } + + + /** + * What a run that goes on after the raise needs of this one: where it stopped, what the fixes changed and what they + * left. + * @return array + */ + public function toArray(): array + { + return [ + 'step' => $this->step, + 'applied' => $this->applied, + 'tasks' => array_map(fn(array $list) => array_map(fn(Task $task) => [ + 'path' => $task->path, + 'violation' => WorkerCodec::encodeViolation($task->violation), + ], $list), $this->tasks), + ]; + } +} diff --git a/src/Upgrade/RunState.php b/src/Upgrade/RunState.php new file mode 100644 index 0000000000..f427549923 --- /dev/null +++ b/src/Upgrade/RunState.php @@ -0,0 +1,172 @@ +root)->findDirectory(); + $name = substr(hash('xxh128', $project->root), 0, 16); + $this->directory = $gitDir === null ? $project->getCacheDir() . "/upgrade/$name" : "$gitDir/dresscode-upgrade/$name"; + $this->durable = $gitDir !== null; + $this->snapshots = new Snapshots("$this->directory/snapshots"); + $this->journal = new ComposerJournal("$this->directory/composer"); + } + + + /** + * Does the work holding the lock of the project, which another run of the plan or a plan being saved holds meanwhile. + * @template T + * @param \Closure(): T $work + * @return T + * @throws ConfigurationException where another process holds it + */ + public function runExclusively(\Closure $work): mixed + { + FileSystem::createDir(dirname($this->directory)); + $handle = FileSystem::open("$this->directory.lock", 'c'); + if (!flock($handle, LOCK_EX | LOCK_NB)) { + fclose($handle); + throw new ConfigurationException('Another run of the upgrade works in the project right now; wait until it ends.'); + } + + try { + return $work(); + } finally { + fclose($handle); + } + } + + + /** + * Puts back what a run keeps to go back, holding the lock of the project: the files of the steps it did not finish + * and those of Composer a raise changed, the packages of the lock installed then; a dry run only says what it would. + * @param ?\Closure(string): void $onProgress told what is being done + * @throws ConfigurationException where another process holds the lock + */ + public function restore(Project $project, PackageManager $composer, bool $dryRun = false, ?\Closure $onProgress = null): Restoration + { + return $this->runExclusively(function () use ($project, $composer, $dryRun, $onProgress): Restoration { + $restored = $left = []; + foreach ($this->snapshots->findInterrupted() as $step => $files) { + $left += $this->snapshots->restore($step, $project->root, $dryRun); + $restored = [...$restored, ...array_diff($files, array_keys($left))]; + } + + // the journal is forgotten only once nothing is left of it and what it put back is installed, so that a + // conflict or a failed install can be gone back over + $composerRoot = $project->findComposerRoot(); + [$composerFiles, $composerLeft] = $this->journal->restore($composerRoot, $dryRun); + $installs = $dryRun + ? ($composerFiles !== [] || $this->journal->isAwaitingInstall()) && is_file("$composerRoot/composer.lock") + : $this->journal->isAwaitingInstall(); + $failure = null; + if ($installs && !$dryRun) { + $onProgress?->__invoke('Composer, installing the packages of the lock'); + try { + $composer->install(); + $this->journal->markInstalled(); + } catch (ComposerException $e) { + $failure = $e->getMessage(); + } + } + + if (!$dryRun && $composerLeft === [] && !$this->journal->isAwaitingInstall()) { + $this->journal->forget(); + } + + return new Restoration([...$restored, ...$composerFiles], $left + $composerLeft, $installs, $failure); + }); + } + + + /** The results the command of the tests gave before the first step; null where it has not run yet. */ + public function findBaseline(string $command): ?TestResults + { + return TestResults::fromFile($this->getBaselineFile($command)); + } + + + public function saveBaseline(string $command, TestResults $results): void + { + $results->save($this->getBaselineFile($command)); + } + + + public function findUncommitted(): ?UncommittedStep + { + $file = "$this->directory/uncommitted.json"; + $data = is_file($file) ? json_decode(FileSystem::read($file), associative: true) : null; + if (!is_array($data) || !is_int($data['step'] ?? null)) { + return null; + } + + $strings = fn(mixed $list) => array_values(array_filter((array) $list, is_string(...))); + $topics = []; + foreach ((array) ($data['topics'] ?? []) as $topic => $paths) { + $topics[(string) $topic] = $strings($paths); + } + + $hashes = array_filter((array) ($data['hashes'] ?? []), is_string(...)); + return new UncommittedStep( + $data['step'], + is_string($data['identity'] ?? null) ? $data['identity'] : '', + $topics, + $strings($data['unprocessed'] ?? []), + array_combine(array_map(strval(...), array_keys($hashes)), $hashes), + ); + } + + + public function saveUncommitted(UncommittedStep $step): void + { + Helpers::replaceFile("$this->directory/uncommitted.json", json_encode((array) $step, JSON_THROW_ON_ERROR)); + } + + + public function forgetUncommitted(): void + { + FileSystem::delete("$this->directory/uncommitted.json"); + } + + + /** Forgets everything, once the plan is done or another one is saved. */ + public function remove(): void + { + FileSystem::delete($this->directory); + } + + + private function getBaselineFile(string $command): string + { + return "$this->directory/tests-baseline-" . substr(hash('xxh128', $command), 0, 16) . '.json'; + } +} diff --git a/src/Upgrade/Snapshots.php b/src/Upgrade/Snapshots.php new file mode 100644 index 0000000000..b52bdd5af4 --- /dev/null +++ b/src/Upgrade/Snapshots.php @@ -0,0 +1,130 @@ +readIndex($step) ?? throw $this->createUnreadable($step); + if (!isset($index[$path])) { + $index[$path] = ['name' => hash('xxh128', $path)]; + Helpers::replaceFile("$this->dir/$step/" . $index[$path]['name'], $before); + } + + $index[$path]['written'] = hash('xxh128', $after); + Helpers::replaceFile("$this->dir/$step/index.json", json_encode($index, JSON_THROW_ON_ERROR)); + } + + + /** + * Writes the files of the step back as they were before it and forgets them, but those changed since the step wrote + * them, which are left as they are and whose text before the step stays kept; a file still as it was before, which + * a run interrupted before writing it leaves, is only forgotten. A dry run only says which files it would leave. + * @return array the files left as they are, relative to the root => why + */ + public function restore(int $step, string $root, bool $dryRun = false): array + { + $index = $this->readIndex($step) ?? throw $this->createUnreadable($step); + $left = []; + foreach ($index as $path => ['name' => $name, 'written' => $written]) { + $file = Helpers::toAbsolutePath($path, $root); + $current = @file_get_contents($file); // @ a file deleted since is changed too + $before = FileSystem::read("$this->dir/$step/$name"); + if ($current !== $before && hash('xxh128', (string) $current) !== $written) { + $left[$path] = "The file changed after step $step wrote it, so it is not written back; its text before the step is kept in `$this->dir/$step/$name`."; + } elseif ($dryRun) { + continue; + } elseif ($current !== $before && !Helpers::writeFile($file, $before)) { + $left[$path] = "The file cannot be written, so it is not written back; its text before the step is kept in `$this->dir/$step/$name`."; + } else { + FileSystem::delete("$this->dir/$step/$name"); + unset($index[$path]); + } + } + + if ($dryRun) { + return $left; + } elseif ($index === []) { + $this->drop($step); + } else { + Helpers::replaceFile("$this->dir/$step/index.json", json_encode($index, JSON_THROW_ON_ERROR)); + } + + return $left; + } + + + /** Forgets the files of the step, once it passed its tests. */ + public function drop(int $step): void + { + FileSystem::delete("$this->dir/$step"); + } + + + /** + * The files of the steps a run left without passing or going back entirely, as one interrupted does; none where the + * snapshots of the step cannot be read. + * @return array> step => its files relative to the root + */ + public function findInterrupted(): array + { + $steps = []; + foreach (glob("$this->dir/*/index.json") ?: [] as $file) { + $step = (int) basename(dirname($file)); + $steps[$step] = array_keys($this->readIndex($step) ?? []); + } + + ksort($steps); + return $steps; + } + + + /** @return ?array file relative to the root => its snapshot; null where unreadable */ + private function readIndex(int $step): ?array + { + $file = "$this->dir/$step/index.json"; + if (!is_file($file)) { + return []; + } + + $index = json_decode((string) @file_get_contents($file), associative: true); // @ the failure is told by the result + return is_array($index) + && array_all( + $index, + fn($entry) => is_array($entry) && is_string($entry['name'] ?? null) && is_string($entry['written'] ?? null), + ) + ? $index + : null; + } + + + private function createUnreadable(int $step): \RuntimeException + { + return new \RuntimeException("The snapshots of step $step in `$this->dir/$step` cannot be read; take the files of the step back with git, or `dresscode upgrade run --discard` drops them."); + } +} diff --git a/src/Upgrade/Step.php b/src/Upgrade/Step.php new file mode 100644 index 0000000000..f41bbccb1b --- /dev/null +++ b/src/Upgrade/Step.php @@ -0,0 +1,21 @@ +> topic => the files it wrote => their text */ + public array $written, + /** @var array the files the step could not process => why */ + public array $unprocessed, + /** @var array> topic => its manual tasks */ + public array $tasks, + /** @var list */ + public array $warnings, + ) { + } +} diff --git a/src/Upgrade/Target.php b/src/Upgrade/Target.php new file mode 100644 index 0000000000..7aeb74f608 --- /dev/null +++ b/src/Upgrade/Target.php @@ -0,0 +1,56 @@ + $targets + * @return array package => version + */ + public static function collectVersions(array $targets): array + { + return array_combine(array_column($targets, 'package'), array_column($targets, 'version')); + } + + + /** The target as a message says it, `php 8.4`, `nette/application 4.0`. */ + public function format(): string + { + return "$this->package $this->version"; + } +} diff --git a/src/Upgrade/Task.php b/src/Upgrade/Task.php new file mode 100644 index 0000000000..996317ccdb --- /dev/null +++ b/src/Upgrade/Task.php @@ -0,0 +1,26 @@ + the tests failing newly, none where the command gave no results */ + public array $newFailures, + /** how the command crashed */ + public ?string $crash, + ) { + } +} diff --git a/src/Upgrade/TestResults.php b/src/Upgrade/TestResults.php new file mode 100644 index 0000000000..cbfb05561f --- /dev/null +++ b/src/Upgrade/TestResults.php @@ -0,0 +1,121 @@ + the identity of a test => how it ended */ + public array $tests, + /** why the results are not to be trusted: the command crashed, did not end in time or wrote no report of tests */ + public ?string $crash = null, + /** when the tests ran, a Unix timestamp; null for results read from a report */ + public ?int $time = null, + ) { + } + + + /** Whether the command writes its results where the JUnit file it is given stands. */ + public static function hasJunitPlaceholder(string $command): bool + { + return str_contains($command, self::Placeholder); + } + + + /** + * The results the JUnit report holds, a test repeated under one identity passing only where every one passed; null + * for a text that is no report. + */ + public static function fromJunit(string $xml, string $root): ?self + { + $document = @simplexml_load_string($xml); // @ a broken file is no report + if ($document === false || !in_array($document->getName(), ['testsuites', 'testsuite'], true)) { + return null; + } + + $tests = []; + $rank = array_flip(array_column(TestStatus::cases(), 'value')); + foreach ($document->xpath('//testcase') ?: [] as $case) { + $class = str_replace(['\\', strtr($root, '\\', '/') . '/'], ['/', ''], (string) $case['classname']); + $id = "$class::{$case['name']}"; + $status = match (true) { + isset($case->error) => TestStatus::Error, + isset($case->failure) => TestStatus::Failed, + isset($case->skipped) => TestStatus::Skipped, + default => TestStatus::Passed, + }; + $tests[$id] = isset($tests[$id]) && $rank[$tests[$id]->value] > $rank[$status->value] ? $tests[$id] : $status; + } + + return new self($tests); + } + + + /** The results a run kept; null where there are none, or of a shape no longer read. */ + public static function fromFile(string $file): ?self + { + $tests = is_file($file) ? json_decode(FileSystem::read($file), associative: true) : null; + $tests = is_array($tests) ? array_map(fn($status) => is_string($status) ? TestStatus::tryFrom($status) : null, $tests) : [null]; + return in_array(null, $tests, true) ? null : new self($tests, time: (int) filemtime($file)); + } + + + public function save(string $file): void + { + Helpers::replaceFile( + $file, + json_encode(array_map(fn(TestStatus $status) => $status->value, $this->tests), JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR), + ); + } + + + /** + * The tests not passing now that passed in the baseline or were not there, each said how it ended where it did not + * just fail, and those of the baseline that passed and are gone. + * @return list + */ + public function findNewFailures(self $baseline): array + { + $failures = []; + foreach ($this->tests as $test => $status) { + if ($status !== TestStatus::Passed && ($baseline->tests[$test] ?? TestStatus::Passed) === TestStatus::Passed) { + $failures[] = $test . ($status === TestStatus::Failed ? '' : " ($status->value)"); + } + } + + $passed = array_filter($baseline->tests, fn(TestStatus $status) => $status === TestStatus::Passed); + foreach (array_keys(array_diff_key($passed, $this->tests)) as $test) { + $failures[] = "$test (gone)"; + } + + return $failures; + } + + + /** How many of the tests did not pass: failed, threw or were skipped. */ + public function countNotPassed(): int + { + return count(array_filter($this->tests, fn(TestStatus $status) => $status !== TestStatus::Passed)); + } +} diff --git a/src/Upgrade/TestRunner.php b/src/Upgrade/TestRunner.php new file mode 100644 index 0000000000..104693eca0 --- /dev/null +++ b/src/Upgrade/TestRunner.php @@ -0,0 +1,19 @@ +, int> the places by what the run can do about them, every case in its order */ + public array $places, + /** what its fixes are right on: the constraint of today for the bridge, the raised one for the jump; null where unknown */ + public ?string $constraint = null, + ) { + } + + + /** The places, or those the run can do the given thing about. */ + public function countPlaces(?Fixability $fixability = null): int + { + return $fixability === null ? array_sum($this->places) : $this->places[$fixability->value]; + } +} diff --git a/src/Upgrade/TopicReporter.php b/src/Upgrade/TopicReporter.php new file mode 100644 index 0000000000..599304b7d4 --- /dev/null +++ b/src/Upgrade/TopicReporter.php @@ -0,0 +1,64 @@ + the files the fix changes, relative to the root => the text before and after */ + public private(set) array $changed = []; + + /** @var list */ + public private(set) array $tasks = []; + + /** @var array the files the fix could not process, relative to the root => why */ + public private(set) array $unprocessed = []; + + + public function __construct( + /** @var list what the configuration of the fix and its run tell the user, the analyses that went without among it */ + public private(set) array $warnings = [], + ) { + } + + + public function start(RunInfo $run): void + { + } + + + public function reportFile(FileResult $result): void + { + if ($result->syntaxError !== null || $result->failure !== null) { + $this->unprocessed[$result->path] = $result->failure ?? "Syntax error: $result->syntaxError"; + return; + } elseif ($result->changed && $result->output !== null) { + $this->changed[$result->path] = [$result->code, $result->output]; + } + + foreach ($result->remaining as $violation) { + if (!$violation->fixable || $violation->refused) { + $this->tasks[] = new Task($result->path, $violation); + } + } + } + + + public function finish(RunResult $result): void + { + $this->warnings = array_values(array_unique([...$this->warnings, ...$result->warnings])); + } +} diff --git a/src/Upgrade/UncommittedStep.php b/src/Upgrade/UncommittedStep.php new file mode 100644 index 0000000000..ef0b7157c6 --- /dev/null +++ b/src/Upgrade/UncommittedStep.php @@ -0,0 +1,52 @@ +> topic => the files its fix wrote, relative to the root */ + public array $topics, + /** @var list the files the step could not process, relative to the root */ + public array $unprocessed, + /** @var array a file the step wrote => the hash of the text it wrote last */ + public array $hashes = [], + ) { + } + + + /** What the step does, its title and whether it is left out aside. */ + public static function identify(Step $step): string + { + return hash('xxh128', serialize([$step::class, array_diff_key(get_object_vars($step), ['title' => true, 'skip' => true])])); + } + + + /** + * The files whose changes are the step's: those it could not process, which the user is to change, and those it wrote + * that nobody changed since; a file it wrote that changed is a change of the working tree of its own. + * @return list + */ + public function listOwnFiles(string $root): array + { + $written = array_filter( + array_unique(array_merge(...array_values($this->topics))), + fn(string $path) => hash('xxh128', (string) @file_get_contents("$root/$path")) === ($this->hashes[$path] ?? null), // @ a file deleted since is changed + ); + return [...array_values($written), ...$this->unprocessed]; + } +} diff --git a/src/Upgrade/UpdateStep.php b/src/Upgrade/UpdateStep.php new file mode 100644 index 0000000000..a3d5aa4f5d --- /dev/null +++ b/src/Upgrade/UpdateStep.php @@ -0,0 +1,29 @@ + the names the check is narrowed to, null for none, an empty list running nothing */ + public ?array $only, + /** @var list the sets laid over the presets the configuration uses and beneath its own decisions */ + public array $laid, + /** the scope of a project without a configuration file, which a worker would not find; null for one with it */ + public ?Config $scope = null, + ) { + } + + + /** @param array{layer: array, only: ?list, laid: list, scope: ?array{paths: list, excludePaths: list}} $data as `toArray()` gave it */ + private static function fromArray(array $data): self + { + return new self( + new Config(...$data['layer']), + $data['only'], + $data['laid'], + $data['scope'] === null ? null : new Config(...$data['scope']), + ); + } + + + public static function read(string $file): self + { + return self::fromArray(json_decode(FileSystem::read($file), associative: true, flags: JSON_THROW_ON_ERROR)); + } + + + /** + * The project of the check, without the types where the layer asks for none. + * @return array{RunnerFactory, ResolvedProject} + * @throws ConfigurationException + */ + public function resolve(Config $config, string $root): array + { + $factory = new RunnerFactory(withoutTypes: $this->layer->typeAnalysis === null); + return [$factory, $factory->resolve($this->scope ?? $config, $root, $this->layer, $this->only, laid: $this->laid)]; + } + + + /** @return array{layer: array, only: ?list, laid: list, scope: ?array{paths: list, excludePaths: list}} */ + public function toArray(): array + { + $layer = $this->layer; + return [ + 'layer' => [ + 'use' => [...$layer->plugins, ...$layer->use], + 'targets' => $layer->targets, + 'namespaces' => $layer->namespaces, + 'nameResolution' => $layer->nameResolution, + 'fixRisky' => $layer->fixRisky, + 'severity' => $layer->severity, + 'typeAnalysis' => $layer->typeAnalysis, + 'decisions' => $layer->decisions, + ], + 'only' => $this->only, + 'laid' => $this->laid, + 'scope' => $this->scope === null ? null : ['paths' => $this->scope->paths, 'excludePaths' => $this->scope->excludePaths], + ]; + } + + + public function write(string $file): void + { + FileSystem::write($file, json_encode($this->toArray(), JSON_THROW_ON_ERROR)); + } +} diff --git a/src/Upgrade/UpgradeFiles.php b/src/Upgrade/UpgradeFiles.php new file mode 100644 index 0000000000..a75ae3ad1e --- /dev/null +++ b/src/Upgrade/UpgradeFiles.php @@ -0,0 +1,38 @@ + relative to the root */ + public array $files, + /** @var list relative to the root */ + public array $generated, + ) { + } + + + /** @param list $files the scope, relative to the root, or absolute when outside it */ + public static function fromScope(string $root, array $files): self + { + $generated = array_values(array_filter( + $files, + fn(string $file) => FileSample::isGenerated(Helpers::toAbsolutePath($file, $root)), + )); + return new self(array_values(array_diff($files, $generated)), $generated); + } +} diff --git a/src/Upgrade/VersionControl.php b/src/Upgrade/VersionControl.php new file mode 100644 index 0000000000..66445bb18c --- /dev/null +++ b/src/Upgrade/VersionControl.php @@ -0,0 +1,38 @@ + $except relative to the root + */ + function readStatus(array $except = []): WorkingTree; + + /** + * The files of those given that are tracked or would be added, the ignored ones aside. + * @param list $paths relative to the root + * @return list + * @throws GitException + */ + function listUnignored(array $paths): array; + + /** + * Commits the files with the texts given, the working tree staying as it is. + * @param array $files relative to the root => text + * @throws GitException + */ + function commit(array $files, string $subject, string $body): void; +} diff --git a/src/Upgrade/enums.php b/src/Upgrade/enums.php new file mode 100644 index 0000000000..827df37d0a --- /dev/null +++ b/src/Upgrade/enums.php @@ -0,0 +1,142 @@ +fixable, $violation->refused && $violation->risk === Risk::BehaviorChanges => self::Manual, + $violation->refused && $violation->risk === Risk::TypeUnknown => self::TypeUnknown, + $violation->refused && $violation->risk === Risk::NameUncertain => self::NameUncertain, + default => self::Automatic, + }; + } +} diff --git a/src/Upgrade/exceptions.php b/src/Upgrade/exceptions.php new file mode 100644 index 0000000000..d2651b8093 --- /dev/null +++ b/src/Upgrade/exceptions.php @@ -0,0 +1,35 @@ +readMap($path), $convert, fn(string $key) => $values->getEntryDecision($path, $key)); + return self::build( + $values->readMap($path), + $convert, + fn(string $key) => $values->getEntryDecision($path, $key), + fn(string $key) => $values->getEntryOrigin($path, $key), + ); } @@ -62,9 +68,10 @@ public static function fromEntries(array $entries, \Closure $convert, string $de * @param array $entries * @param ?\Closure(mixed, MemberPattern, string): V $convert * @param \Closure(string): string $decide the key as written => the decision its entry is reported under + * @param ?\Closure(string): ?Layer $findOrigin the key as written => the section of the upgrading data that laid it * @return self */ - private static function build(array $entries, ?\Closure $convert, \Closure $decide): self + private static function build(array $entries, ?\Closure $convert, \Closure $decide, ?\Closure $findOrigin = null): self { $byName = []; foreach ($entries as $key => $value) { @@ -77,6 +84,7 @@ private static function build(array $entries, ?\Closure $convert, \Closure $deci $pattern, $convert === null ? $value : $convert($value, $pattern, (string) $key), $decide((string) $key), + $findOrigin === null ? null : $findOrigin((string) $key), ); } diff --git a/src/Upgrading/MemberMapEntry.php b/src/Upgrading/MemberMapEntry.php index 8c435ef65e..92ad6fc580 100644 --- a/src/Upgrading/MemberMapEntry.php +++ b/src/Upgrading/MemberMapEntry.php @@ -7,10 +7,12 @@ namespace DressCode\Upgrading; +use DressCode\Config\Layer; + /** - * An entry of a map of members: its key, what the rule keeps of its value, and the decision a use of it is reported - * under, the map itself or the requirement that laid the upgrading data holding it. + * An entry of a map of members: its key, what the rule keeps of its value, the decision a use of it is reported + * under, the map itself or the requirement that laid the upgrading data holding it, and the section of those data. * @template T */ final readonly class MemberMapEntry @@ -21,6 +23,8 @@ public function __construct( /** @var T */ public mixed $value, public string $decision, + /** the section of the upgrading data of a package that laid the entry, null where the project wrote it */ + public ?Layer $origin = null, ) { } } diff --git a/src/Values.php b/src/Values.php index b5dc621a87..37a92c6b00 100644 --- a/src/Values.php +++ b/src/Values.php @@ -96,27 +96,21 @@ public function findWithdrawnNames(string $path): array /** - * The keys of the entries of a map the upgrading data of a package laid, not a layer of the project. - * @return array + * The decision an entry of a map is reported under: the requirement that laid the upgrading data holding it, the + * map itself otherwise. */ - public function findPackageEntries(string $path): array + public function getEntryDecision(string $path, string $key): string { - $value = $this->get($path); - return $value->content === null || $value->isKept() - ? [] - : array_map(fn() => true, array_filter($value->getEntries(), fn(Value $entry) => $entry->origin?->kind === LayerKind::Package)); + return $this->getEntryOrigin($path, $key)->decision ?? $path; } - /** - * The decision an entry of a map is reported under: the requirement that laid the upgrading data holding it, the - * map itself otherwise. - */ - public function getEntryDecision(string $path, string $key): string + /** The section of the upgrading data of a package that laid the entry of a map, null where the project wrote it. */ + public function getEntryOrigin(string $path, string $key): ?Config\Layer { $value = $this->get($path); $origin = $value->content === null || $value->isKept() ? null : ($value->getEntries()[$key] ?? null)?->origin; - return $origin->decision ?? $path; + return $origin?->kind === LayerKind::Package ? $origin : null; } diff --git a/src/Violation.php b/src/Violation.php index abc7a740aa..6b7b11b077 100644 --- a/src/Violation.php +++ b/src/Violation.php @@ -59,6 +59,11 @@ public function __construct( * leaves too, code a fix wrote taking the lines of the code beside it; null where the fixed text was read anew */ public ?array $originalLines = null, + /** + * the section of the upgrading data of a package whose entry the occurrence is of, null where the project wrote + * the entry or the rule reads no map + */ + public ?Config\Layer $source = null, ) { if ($risk === null && ($refused || $because !== null)) { throw new \InvalidArgumentException("Violation of `$decision`: `refused` and `because` belong to a risky violation, but no risk is given."); diff --git a/tests/DressCode/Analyses/PhpDoc.phpt b/tests/DressCode/Analyses/PhpDoc.phpt index c4c0bcfe29..891d52bbd0 100644 --- a/tests/DressCode/Analyses/PhpDoc.phpt +++ b/tests/DressCode/Analyses/PhpDoc.phpt @@ -25,13 +25,14 @@ function docComments(FileNode $file): array } -test('parse and read', function () { - $file = (new Parser)->parse("\n */\nfunction f(\$a) {}"); +test('every parse gives a tree of its own, and only of a doc comment', function () { + $file = (new Parser)->parse("\n */\nfunction f(\$a) {}"); $phpDoc = new PhpDoc; - $node = $phpDoc->parse(docComments($file)[0]); - Assert::same('Does things.', (string) $node->children[0]); - Assert::count(1, $node->getParamTagValues()); + $trivia = docComments($file)[0]; + $node = $phpDoc->parse($trivia); Assert::same('list', (string) $node->getReturnTagValues()[0]->type); + $node->children = []; + Assert::same('Does things.', (string) $phpDoc->parse($trivia)->children[0]); Assert::exception(fn() => $phpDoc->parse(new Trivia(Trivia::Comment, '// x')), InvalidArgumentException::class, 'Not a doc comment.'); }); diff --git a/tests/DressCode/Analyses/Types.phpt b/tests/DressCode/Analyses/Types.phpt index 0557352bce..8ca01eb7fd 100644 --- a/tests/DressCode/Analyses/Types.phpt +++ b/tests/DressCode/Analyses/Types.phpt @@ -640,7 +640,8 @@ test('a class the pass moved down has its types, while the disk still has it hig $file = (new Parser)->parse(sprintf($code, "use Acme\\Shop\\Order;\n")); $types = new Analyses\Types($file, $path, $phpstan); - Assert::notNull($types->findMemberAccess($file->find(MethodCallNode::class)[0])); + $access = $types->findMemberAccess($file->find(MethodCallNode::class)[0]); + Assert::same([['App\Sheet'], 'log', true], [$access?->classes, $access?->name, $access?->declared]); Assert::null($types->failure); }); @@ -654,7 +655,8 @@ test('an anonymous class has its types, while the disk still has a shorter text' $file = (new Parser)->parse(sprintf($code, str_repeat('x', 60))); $types = new Analyses\Types($file, $path, $phpstan); - Assert::notNull($types->findMemberAccess($file->find(MethodCallNode::class)[0])); + $access = $types->findMemberAccess($file->find(MethodCallNode::class)[0]); + Assert::same(['log', true], [$access?->name, $access?->declared]); Assert::null($types->failure); }); diff --git a/tests/DressCode/Config.phpt b/tests/DressCode/Config.phpt index 7099029a40..34412cb385 100644 --- a/tests/DressCode/Config.phpt +++ b/tests/DressCode/Config.phpt @@ -6,6 +6,15 @@ use Tester\Assert; require __DIR__ . '/../bootstrap.php'; +final class ConfigTestPlugin implements DressCode\Plugin +{ + public function getManifest(): DressCode\PluginManifest + { + return new DressCode\PluginManifest; + } +} + + #[DressCode\RuleInfo(DressCode\Stage::Structure)] final class ConfigTestRule extends NodeRule { @@ -16,50 +25,18 @@ final class ConfigTestRule extends NodeRule } -test('defaults', function () { - $config = new Config; - Assert::same([], $config->use); - Assert::same([], $config->plugins); - Assert::same([], $config->rules); - Assert::same([], $config->targets); - Assert::same(['functions' => [], 'constants' => []], $config->namespaces); - Assert::null($config->nameResolution); - Assert::same([], $config->fixRisky); - Assert::same([], $config->severity); - Assert::same([], $config->overrides); - Assert::same([], $config->paths); - Assert::same(['vendor', 'node_modules', 'temp', 'tmp', 'log', '.*'], $config->excludePaths); - Assert::same(['php'], $config->fileExtensions); - Assert::null($config->skipWhen); - Assert::null($config->baseline); - Assert::null($config->cacheDir); - Assert::same([], $config->analyses); - Assert::null($config->typeAnalysis); +test('a plugin in use is set apart from the presets, given as an instance or as its class', function () { + $plugin = new ConfigTestPlugin; + $config = new Config(use: ['a/b', $plugin, ConfigTestPlugin::class, 'c/d']); + Assert::same(['a/b', 'c/d'], $config->use); + Assert::same([$plugin, ConfigTestPlugin::class], $config->plugins); }); -test('every key is a named argument', function () { - $override = new Override(['tests'], new Profile(use: ['x/y'])); +test('a rule is given by its class, or with the factory that builds it', function () { $factory = fn() => new ConfigTestRule; - $config = new Config( - use: ['a/b'], - rules: [ConfigTestRule::class], - targets: ['php' => '8.2'], - overrides: [$override], - paths: ['src'], - fileExtensions: ['php', 'phpt'], - skipWhen: fn(string $content, string $path) => $path === 'skip.php', - baseline: 'baseline.json', - ); - Assert::same(['a/b'], $config->use); - Assert::same([ConfigTestRule::class => null], $config->rules); + Assert::same([ConfigTestRule::class => null], new Config(rules: [ConfigTestRule::class])->rules); Assert::same([ConfigTestRule::class => $factory], new Config(rules: [ConfigTestRule::class => $factory])->getRuleFactories()); - Assert::same('8.2', $config->targets['php'] ?? null); - Assert::same([$override], $config->overrides); - Assert::same(['src'], $config->paths); - Assert::same(['php', 'phpt'], $config->fileExtensions); - Assert::true(($config->skipWhen ?? throw new LogicException)('', 'skip.php')); - Assert::same('baseline.json', $config->baseline); }); diff --git a/tests/DressCode/Config/Catalogue.phpt b/tests/DressCode/Config/Catalogue.phpt index a152799e78..f6e6118a21 100644 --- a/tests/DressCode/Config/Catalogue.phpt +++ b/tests/DressCode/Config/Catalogue.phpt @@ -3,7 +3,7 @@ use DressCode\Analyses\IndentationPlan; use DressCode\Config\{Catalogue, CorePlugin}; use DressCode\{ConfigurationException, Decision, DecisionKind, Domain, ImportStyle, NodeRule, RuleInfo, Stage}; -use DressCode\Domains\{Count, Names, Shapes}; +use DressCode\Domains\{Count, Map, Names, Shapes, Words}; use Tester\Assert; require __DIR__ . '/../../bootstrap.php'; @@ -402,6 +402,24 @@ test('a rule has some decision, a decision one declaration, and no path is both }); +test('a word several decisions share comes from the lexicon, in its meaning', function () { + $decision = fn(string $path, Domain $domain) => new Decision($path, $domain, 'Something is written'); + Assert::same( + [ + 'spacing.a wide: shared by several decisions and no word of the lexicon', + 'spacing.b wide: shared by several decisions and no word of the lexicon', + 'spacing.c required: its gloss does not begin with `always there`', + ], + Catalogue::findLexiconProblems([ + $decision('spacing.a', new Words(['wide' => 'with room', 'own' => 'its own word'])), + $decision('spacing.b', new Map(new Words(['wide' => 'with room']))), + $decision('spacing.c', new Words(['required' => 'mandatory'])), + $decision('spacing.d', new Words(['required' => 'always there, once'])), + ]), + ); +}); + + test('the export is the decisions as data, versioned', function () { $export = new Catalogue([TrailingIfRule::class, CallRule::class])->toArray(); Assert::same(Catalogue::Version, $export['version']); diff --git a/tests/DressCode/Config/ConfigResolver.phpt b/tests/DressCode/Config/ConfigResolver.phpt index 7043c1b316..482f547a0f 100644 --- a/tests/DressCode/Config/ConfigResolver.phpt +++ b/tests/DressCode/Config/ConfigResolver.phpt @@ -463,7 +463,9 @@ test('--only keeps what it names of what the configuration comes to, and turns n fn(ResolvedRule $rule) => $rule->class, createResolver()->resolve(new Config(use: ['nette']), '8.3', only: ['dresscode/types'])->getActiveRules(), ); - Assert::true($section !== [] && $section !== $preset); + Assert::same([DressCode\Rules\Types\TypeNotationRule::class], $section); + Assert::contains(DressCode\Rules\Types\TypeNotationRule::class, $preset); + Assert::contains(DressCode\Rules\PhpDoc\PhpdocTypeNotationRule::class, $preset); Assert::exception( fn() => createResolver()->resolve(new Config(use: ['nette']), '8.3', only: ['nothing.*']), ConfigurationException::class, @@ -790,7 +792,8 @@ test('what the namespaces declare adds up over the layers, and only the configur $certain = $resolver->resolve(new Config(nameResolution: 'certain'), Config::DefaultPhpVersion); Assert::true($certain->toNamespacedSymbols()->complete); Assert::true($certain->toNamespacedSymbols()->hasConstant('Fw\VERSION')); - Assert::notSame($uncertain->toArray(), $certain->toArray()); + Assert::same('uncertain', $uncertain->toArray()['namespaces'][2]); + Assert::same('certain', $certain->toArray()['namespaces'][2]); // a certain resolution turns on the guard of its lists, which nothing turns off, the fixes resting on the lists $guard = DressCode\Rules\Namespaces\NoUnlistedNamespacedDeclarationsRule::class; @@ -1027,7 +1030,7 @@ test('errors', function () { Assert::exception( fn() => resolve(new Config(decisions: projectDecisions(['none']))), ConfigurationException::class, - '%a%`project.none`%a%', + 'Key `project.none` is unknown.', ); Assert::exception( fn() => resolve(new Config(use: ['test/broken'])), diff --git a/tests/DressCode/Config/DataPackageCatalogue.phpt b/tests/DressCode/Config/DataPackageCatalogue.phpt new file mode 100644 index 0000000000..5446a004a0 --- /dev/null +++ b/tests/DressCode/Config/DataPackageCatalogue.phpt @@ -0,0 +1,28 @@ + ['nette/', 'latte/latte']], DataPackageCatalogue::load($dir)); + clearstatcache(); + Assert::same($time, filemtime("$dir/data-packages.json")); // asking Packagist would have written it again +}); + + +test('offline, what is remembered is read however old it is', function () { + $dir = createTempDir('data-catalogue-offline'); + FileSystem::write("$dir/data-packages.json", '{"dresscode/upgrade-nette": ["nette/"]}'); + touch("$dir/data-packages.json", $time = time() - 10 * 86_400); + Assert::same(['dresscode/upgrade-nette' => ['nette/']], DataPackageCatalogue::load($dir, offline: true)); + clearstatcache(); + Assert::same($time, filemtime("$dir/data-packages.json")); + Assert::same([], DataPackageCatalogue::load(createTempDir('data-catalogue-empty'), offline: true)); +}); diff --git a/tests/DressCode/Config/DecisionResolver.phpt b/tests/DressCode/Config/DecisionResolver.phpt index b062d09201..c34b907062 100644 --- a/tests/DressCode/Config/DecisionResolver.phpt +++ b/tests/DressCode/Config/DecisionResolver.phpt @@ -366,7 +366,7 @@ test( Assert::exception( fn() => $resolver->checkLayer(['qualification' => ['globalClass' => null]], $file), ConfigurationException::class, - '%a%`qualification.globalClass`%a%', + 'Key `qualification.globalClass` does not take `null`; write `bare`, `imported`, `backslashed` or `keep`.', ); $commandLine = new Layer(LayerKind::CommandLine); @@ -383,12 +383,12 @@ test( Assert::exception( fn() => $resolver->checkLayer(['qualification' => ['renamed' => null]], $commandLine), ConfigurationException::class, - '%a%`qualification.renamed`%a%', + 'Key `qualification.renamed` does not take `null`; write a map of names or `keep`.', ); Assert::exception( fn() => $resolver->checkLayer(['mistakes' => ['debugOutputFunctions' => null]], $commandLine), ConfigurationException::class, - '%a%`mistakes.debugOutputFunctions`%a%', + 'Key `mistakes.debugOutputFunctions` does not take `null`; write a list of names.', ); }, ); diff --git a/tests/DressCode/Config/Loader.phpt b/tests/DressCode/Config/Loader.phpt index e172aa7197..9932ab64d3 100644 --- a/tests/DressCode/Config/Loader.phpt +++ b/tests/DressCode/Config/Loader.phpt @@ -322,13 +322,11 @@ test('the types of the code come from phpstan or from nowhere', function () { }); -test('a rule of the project is named by its class, and what the namespaces declare is a map', function () { +test('what the namespaces declare is a map', function () { $config = Loader::loadFile(FileMock::create(<<<'XX' - rules: [LoaderRule] namespaces: functions: [App\helper] XX, 'neon')); - Assert::same([LoaderRule::class => null], $config->rules); Assert::same(['functions' => ['App\helper'], 'constants' => []], $config->namespaces); }); diff --git a/tests/DressCode/Config/PackageDiscovery.phpt b/tests/DressCode/Config/PackageDiscovery.phpt index 7a77641b03..80cc47b459 100644 --- a/tests/DressCode/Config/PackageDiscovery.phpt +++ b/tests/DressCode/Config/PackageDiscovery.phpt @@ -158,6 +158,16 @@ test('a section above the lowest version says nothing, an entry right from a ver $data->maps, ); Assert::same(['4.0', '5.0'], $data->unreached); + Assert::same( + [ + ['3.0', null, ['replacedClasses' => ['Acme\Lib\Old' => 'Acme\Lib\Renamed']]], + ['4.0', '3.0', ['replacedFunctions' => ['Acme\Lib\old_helper' => 'Acme\Lib\helper']]], + ], + array_map( + fn(array $layer) => [$layer[0]->since, $layer[0]->from, $layer[1]], + $data->buildDecisions(fn(string $map) => $map), + ), + ); }); @@ -276,8 +286,8 @@ test('a package the project requires itself is measured by the lowest version it $runner->processCode("$root/f.php", "output, ); Assert::same([ - 'The configuration names package `acme/ghost` in `targets`, but it is not installed; skipped.' => null, - 'The configuration names package `app/project` in `targets`, but that is the project itself, whose code is any version of it; skipped.' => null, + 'Package `acme/ghost` is named in `targets`, but it is not installed; skipped.' => null, + 'Package `app/project` is named in `targets`, but that is the project itself, whose code is any version of it; skipped.' => null, ], $resolution->warnings); }); @@ -548,7 +558,7 @@ test('what a package says lies under the maps of the project where it says upgra ); $layers = $resolution->resolvedConfig->decisions['upgrading.api.replacedClasses']->layers; Assert::same( - ['upgrading/upgrading.neon of acme/lib', 'the configuration'], + ['upgrading/upgrading.neon of acme/lib, since 3.0', 'the configuration'], array_map(fn($layer) => $layer->origin?->describe(), $layers), ); @@ -624,3 +634,49 @@ test( ); }, ); + + +test('the upgrading data installed beside DressCode serves a project without it, and what its libraries miss is named', function () { + $root = project( + 'data-beside', + ['nette/utils' => ['4.0.0.0', []], 'dibi/dibi' => ['5.0.0.0', []], 'symfony/console' => ['7.0.0.0', []]], + [], + ['require' => ['nette/utils' => '^4.0', 'dibi/dibi' => '^5.0']], + ); + $data = createTempDir('data-package'); + FileSystem::write( + "$data/composer.json", + json_encode(['name' => 'dresscode/upgrade-nette', 'extra' => ['dresscode' => ['upgrading-dir' => 'upgrading']]]), + ); + FileSystem::write( + "$data/upgrading/utils.neon", + "package: nette/utils\n\nsince 4.0:\n\treplacedClasses:\n\t\tNette\\Old: Nette\\Renamed\n", + ); + $project = ProjectPackages::read($root); + + // a library the project requires itself, as the package says it is about, whereas symfony/console comes with another + $catalogue = [ + 'dresscode/upgrade-nette' => ['nette/', 'latte/latte'], + 'dresscode/upgrade-deegee' => ['dibi/dibi'], + 'dresscode/upgrade-symfony' => ['symfony/console'], + ]; + Assert::same( + ['dresscode/upgrade-nette', 'dresscode/upgrade-deegee'], + PackageDiscovery::findMissingDataPackages($project, $catalogue, []), + ); + Assert::same( + ['dresscode/upgrade-deegee'], + PackageDiscovery::findMissingDataPackages($project, $catalogue, ['dresscode/upgrade-nette' => $data]), + ); + Assert::same( + ['upgrading/utils.neon of dresscode/upgrade-nette'], + array_map( + fn($data) => $data->layer->describe(), + PackageDiscovery::discover($project, ['dresscode/upgrade-nette' => $data])->upgradingData, + ), + ); + + // a project with none of their libraries misses nothing + $other = ProjectPackages::read(project('data-none', ['acme/lib' => ['1.0.0.0', []]], [], ['require' => ['acme/lib' => '^1.0']])); + Assert::same([], PackageDiscovery::findMissingDataPackages($other, $catalogue, [])); +}); diff --git a/tests/DressCode/Config/PluginRegistry.phpt b/tests/DressCode/Config/PluginRegistry.phpt index 7affba4a5f..edf5091774 100644 --- a/tests/DressCode/Config/PluginRegistry.phpt +++ b/tests/DressCode/Config/PluginRegistry.phpt @@ -95,7 +95,6 @@ test('a rule is known by its class, once however often it is registered', functi $registry->registerRule(RuleOne::class); Assert::same($count + 1, count($registry->rules)); Assert::same(RuleOne::class, $registry->rules[$count]); - Assert::same('dresscode/nette', $registry->findPreset('nette')); }); @@ -211,6 +210,7 @@ test('presets', function () { $registry->registerPreset('test/preset', $file); Assert::same('dresscode/perCs', $registry->resolvePreset('dresscode/perCs')); Assert::same('dresscode/perCs', $registry->resolvePreset('perCs')); + Assert::same('dresscode/nette', $registry->findPreset('nette')); Assert::same('test/preset', $registry->resolvePreset('test/preset')); Assert::same([ 'dresscode/perCs', 'dresscode/psr12', 'dresscode/nette', 'dresscode/symfony', 'dresscode/laravel', 'dresscode/cleanup', diff --git a/tests/DressCode/Config/ProjectPackages.phpt b/tests/DressCode/Config/ProjectPackages.phpt index ab37d97ab7..9e835417ee 100644 --- a/tests/DressCode/Config/ProjectPackages.phpt +++ b/tests/DressCode/Config/ProjectPackages.phpt @@ -154,6 +154,11 @@ test('the packages installed newer than the oldest version the project supports, ['name' => 'acme/transitive', 'version_normalized' => '5.1.0.0', 'install-path' => '../acme/transitive'], ]], JSON_THROW_ON_ERROR)); + $project = ProjectPackages::read($root); + Assert::same( + ['acme/older' => ['3.3', '3.1'], 'acme/patch' => ['3.3.5', '3.3'], 'acme/branch' => ['2.4.9999999.9999999', '2.0']], + $project->findNewerInstalled(), + ); Assert::same( [ "$root/vendor/acme/older", @@ -162,7 +167,7 @@ test('the packages installed newer than the oldest version the project supports, "$root/vendor/acme/any", "$root/vendor/acme/transitive", ], - ProjectPackages::read($root)->findPathsAheadOfSupport(), + $project->findPathsAheadOfSupport(), ); }); @@ -225,14 +230,6 @@ test('the extensions of PHPStan a project has, with the configuration files its }); -test('a project without packages has none', function () { - $project = new ProjectPackages; - Assert::null($project->rootPath); - Assert::false($project->has('acme/lib')); - Assert::null($project->findVersion('acme/lib')); -}); - - test('a requirement is met where every version the code is written for satisfies it', function () { $root = createTempDir('project-packages-requirement'); FileSystem::write("$root/composer.json", json_encode([ diff --git a/tests/DressCode/Config/RunnerFactory.phpt b/tests/DressCode/Config/RunnerFactory.phpt index 7e3f8a007a..e39943abc2 100644 --- a/tests/DressCode/Config/RunnerFactory.phpt +++ b/tests/DressCode/Config/RunnerFactory.phpt @@ -4,9 +4,9 @@ use Composer\InstalledVersions; use DressCode\{ CodeWriter, Config, ConfigurationException, Decision, Domain, NodeRule, Override, Plugin, PluginManifest, Profile, RuleContext, RuleInfo, Stage, }; -use DressCode\Config\{ComposerJson, PhpVersionSource, RunnerFactory}; +use DressCode\Config\{ComposerJson, PhpVersionSource, RunnerFactory, UpgradingData}; use DressCode\Engine\{Baseline, Runner, TypeAnalysisStatus}; -use DressCode\Reporters\NullReporter; +use DressCode\Reporters\{CollectingReporter, NullReporter}; use DressCode\Rules\ControlFlow\MatchForSwitchRule; use Nette\Utils\FileSystem; use PhpSyntax\{Node, Token}; @@ -325,10 +325,11 @@ test('a rule of a plugin is built by the factory of its manifest, anew for every overrides: [new Override(['tests'], new Profile(targets: ['php' => '8.4']))], decisions: ['dependent' => ['variables' => 'forbidden']], ); - $result = buildRunner($config, $root)->run(['a.php', 'tests/b.php'], false, new NullReporter); + $collected = new CollectingReporter; + buildRunner($config, $root)->run(['a.php', 'tests/b.php'], false, $collected); Assert::same( ['A variable, served.', 'A variable, served.'], - array_map(fn($file) => $file->violations[0]->message, $result->files), + array_map(fn(array $violations) => $violations[0]->message, array_values($collected->violations)), ); Assert::count(2, $plugin->built); Assert::notSame($plugin->built[0], $plugin->built[1]); @@ -486,10 +487,11 @@ test('a configuration of PHPStan it cannot start with is a warning of the run, a decisions: ['upgrading' => ['declarations' => ['deprecatedMember' => 'forbidden']]], ); $runner = $factory->createRunner($factory->resolve($config, $root), cache: false); - $result = $runner->run(['Check.php'], false, new NullReporter); + $collected = new CollectingReporter; + $result = $runner->run(['Check.php'], false, $collected); Assert::same(['5: upgrading.declarations.deprecatedMember'], array_map( fn($violation) => "$violation->line: $violation->decision", - $result->files[0]->violations, + $collected->violations['Check.php'], )); Assert::match( 'PHPStan could not start with the configuration of the project: %a%; the types go without it.', @@ -552,8 +554,9 @@ function findNullArguments(string $root): array typeAnalysis: 'phpstan', decisions: ['upgrading' => ['php' => ['nullArgument' => 'forbidden']]], ); - $result = $factory->createRunner($factory->resolve($config, $root), cache: false)->run(['Check.php'], false, new NullReporter); - return [array_map(fn($violation) => $violation->line, $result->files[0]->violations), $result->warnings]; + $collected = new CollectingReporter; + $result = $factory->createRunner($factory->resolve($config, $root), cache: false)->run(['Check.php'], false, $collected); + return [array_map(fn($violation) => $violation->line, $collected->violations['Check.php'] ?? []), $result->warnings]; } @@ -680,6 +683,8 @@ test('what the data of PHP say is reported under the requirement that lays them, Assert::same(['2: upgrading.php.deprecatedApi', '3: upgrading.api.forbiddenFunctions'], $decisions(null)); Assert::same(['2: upgrading.php.deprecatedApi'], $decisions('upgrading.php.deprecatedApi')); + // the package of the data stands for that requirement too, beside the maps it writes into, which the project's entries share + Assert::same(['2: upgrading.php.deprecatedApi', '3: upgrading.api.forbiddenFunctions'], $decisions('php')); }); @@ -718,6 +723,63 @@ test('every rule the data of PHP feed reports what they say under the requiremen }); +test('a violation of an entry of upgrading data names its section and the version its fix is right from', function () { + $root = createTempDir('data-source'); + $factory = new RunnerFactory(phpstanInstalled: false); + $upgrading = ['php' => ['deprecatedApi' => 'forbidden'], 'api' => ['forbiddenFunctions' => ['acme_retired' => 'gone']]]; + $config = new Config(targets: ['php' => '8.5'], decisions: ['upgrading' => $upgrading]); + $code = "createRunner($factory->resolve($config, $root), cache: false) + ->processCode("$root/Check.php", $code) + ->violations; + + // an entry the project wrote has none + Assert::same( + [['php.neon', 'php', '8.5', null], ['php.neon', 'php', '8.5', '8.0'], null], + array_map( + fn($violation) => $violation->source === null + ? null + : [$violation->source->name, $violation->source->library, $violation->source->since, $violation->source->from], + $violations, + ), + ); +}); + + +test('the targets of the command line cut the upgrading data before they are laid, over those of the configuration', function () { + $root = createTempDir('targets-command'); + file_put_contents("$root/composer.json", '{"require": {"php": "^8.0"}}'); + $code = <<<'XX' + setAccessible(true); + } + XX; + file_put_contents("$root/Check.php", $code); + $factory = new RunnerFactory; + $config = new Config(typeAnalysis: 'phpstan', decisions: ['upgrading' => ['php' => ['deprecatedApi' => 'forbidden']]]); + $run = function (?Config $commandLine) use ($factory, $config, $root, $code): array { + $resolution = $factory->resolve($config, $root, $commandLine); + $php = array_find(array_column($resolution->upgradingData, 0), fn(UpgradingData $data) => $data->package === 'php'); + $result = $factory->createRunner($resolution, cache: false)->processCode("$root/Check.php", $code); + return [ + $resolution->resolvedConfig->phpVersion, + $php?->unreached[0], + array_map(fn($violation) => $violation->fixable, $result->violations), + ]; + }; + + // what PHP 8.1 made a no-op the code that runs on 8.0 still needs, and it is removed once the command line moves it to 8.1 + Assert::same(['8.0', '8.1', []], $run(null)); + Assert::same(['8.1', '8.3', [true]], $run(new Config(targets: ['php' => '8.1']))); + + $resolution = $factory->resolve(new Config(targets: ['acme/mail' => '2.0']), $root, new Config(targets: ['acme/mail' => '3.0'])); + Assert::same(['acme/mail' => '3.0'], $resolution->resolvedConfig->packageTargets); +}); + + test('the command line asks for the types without a configuration that sets them, and PHPStan missing refuses the run', function () { $root = createTempDir('types-command'); $commandLine = new Config(use: ['deprecations'], typeAnalysis: 'phpstan'); @@ -842,7 +904,7 @@ test( Assert::exception( fn() => (new RunnerFactory)->resolve(new Config(decisions: ['plugin' => ['variables' => 'forbidden']]), "$fixtures/project"), ConfigurationException::class, - '%a%`plugin%a%', + 'Key `plugin` is unknown.', ); $root = createTempDir('runner-factory-plugins'); diff --git a/tests/DressCode/Config/UpgradingFile.phpt b/tests/DressCode/Config/UpgradingFile.phpt index 0277a72cc3..44f71e10dc 100644 --- a/tests/DressCode/Config/UpgradingFile.phpt +++ b/tests/DressCode/Config/UpgradingFile.phpt @@ -55,11 +55,15 @@ test('the sentence names the package and the version, PHP as PHP', function () { XX); $data = $upgrading->selectFor('>=8.5', new Layer(LayerKind::Package, 'php.neon', 'php')); + // every entry in the layer of its section, with the version its fix is right from Assert::same( [ - 'forbiddenFunctions' => ['socket_set_timeout' => 'since PHP 8.5'], - 'replacedCalls' => ['curl_close($handle)' => 'removed'], + ['php', '8.5', null, ['forbiddenFunctions' => ['socket_set_timeout' => 'since PHP 8.5']]], + ['php', '8.5', '8.0', ['replacedCalls' => ['curl_close($handle)' => 'removed']]], ], - $data->buildDecisions(fn(string $map) => $map), + array_map( + fn(array $layer) => [$layer[0]->library, $layer[0]->since, $layer[0]->from, $layer[1]], + $data->buildDecisions(fn(string $map) => $map), + ), ); }); diff --git a/tests/DressCode/Console/Application.helpers.php b/tests/DressCode/Console/Application.helpers.php index a4e0d6f287..eb99f63b2b 100644 --- a/tests/DressCode/Console/Application.helpers.php +++ b/tests/DressCode/Console/Application.helpers.php @@ -136,6 +136,7 @@ function createConsoleProject(): string /** * @param list $args * @return array{int, string, string} + * @phpstan-impure */ function runApp(string $root, array $args, string $stdin = '', bool $xdebug = false, bool $interactive = false): array { @@ -144,7 +145,8 @@ function runApp(string $root, array $args, string $stdin = '', bool $xdebug = fa $in = fopen('php://memory', 'w+') ?: throw new RuntimeException; fwrite($in, $stdin); rewind($in); - if (in_array($args[0] ?? null, ['check', 'fix', 'baseline'], strict: true) && !in_array('--jobs', $args, strict: true)) { + $runs = in_array($args[0] ?? null, ['check', 'fix', 'baseline'], strict: true) || array_slice($args, 0, 2) === ['upgrade', 'today']; + if ($runs && !in_array('--jobs', $args, strict: true)) { $args = [...$args, '--jobs', '1']; // the rules of this file do not exist in a worker process } diff --git a/tests/DressCode/Console/Application.phpt b/tests/DressCode/Console/Application.phpt index 733dda0373..9c17e2cddc 100644 --- a/tests/DressCode/Console/Application.phpt +++ b/tests/DressCode/Console/Application.phpt @@ -346,7 +346,7 @@ test('errors go to stderr with exit code 3', function () use ($root) { Assert::match('Error: Option `--set`: expects the value in NEON, `project.rename={` given:%A%', $err); [$code, , $err] = runApp($root, ['check', '--set', 'project.rename=off']); Assert::same(3, $code); - Assert::match('Error: %A%project.rename%A%', $err); + Assert::match('Error: The command line: Key `project.rename` does not take `off`; write `forbidden` or `keep`.', $err); [$code, , $err] = runApp($root, ['config', '--set', 'comments.firstColumn=required']); Assert::same(3, $code); Assert::same("Error: The command line: Key `comments.firstColumn` does not take `required`; write `forbidden` or `optional`.\n", $err); @@ -884,7 +884,6 @@ test('exit codes: a file that failed is 2, a mistake of the command line or of t " ['rename' => 'forbidden']], paths: ['src'], baseline: 1);\n", ); Assert::same(3, runApp($root, ['check', '--config', "$root/invalid.php", '--no-cache'])[0]); - Assert::same(3, runApp($root, ['check', '--nope'])[0]); [$code, , $err] = runApp($root, ['config', '--preset', '']); Assert::same(3, $code); Assert::match("Error: Option `--preset`: `use` names a preset or the path of a file, an empty string given.\n%A%", $err); @@ -947,20 +946,12 @@ test('a risky fix waits for the run to allow it, and is a violation until it is Assert::match("%A%\nREVIEWED no risky fixes to ask about\n", $out); file_put_contents("$root/src/r.php", " 'php', 'version' => '8.4']], $estimate['targets']); + Assert::same( + ['php jump ^8.4', 'php bridge ^8.0', 'upgrading.php.implicitNullable bridge ^8.0'], + array_map(fn(array $topic) => "$topic[name] $topic[phase] $topic[constraint]", $estimate['topics']), + ); + + // a run of the plan keeps the style of the configuration, which the project does not have + [$exit, , $err] = runApp($root, ['upgrade', 'run', 'php', '8.4', '--no-types', '--offline']); + Assert::same(3, $exit); + Assert::contains('and the project has none; write it with `dresscode init` first.', $err); + + // the paths named narrow the configured ones + file_put_contents("$root/src/Other.php", " 2, 'title' => 'raise php to ^8.4']], [$data['tasks'], $data['due']]); + // a file the fixes cannot process leaves the answer incomplete + file_put_contents("$root/src/Broken.php", " 1, 'topic' => 'php', 'files' => []]], array_slice($run['outcome']['applied'], 0, 1)); + Assert::same([], $run['outcome']['tasks']); + Assert::same('composer', $run['plan']['steps'][1]['kind']); + file_put_contents("$root/composer.json", '{"require": {"php": "^8.4"}}'); + [$exit, $out] = runApp($root, ['upgrade', 'run', '--no-types', '--no-color']); + Assert::same(1, $exit); + Assert::match(<<<'XX' + %A%Step 3 php left nothing to fix + Manual 1 task the fixes left + src/Code.php:5 Function `strftime()` is deprecated: since PHP 8.1. [upgrading.php.deprecatedApi] + `{` + `%a%strftime(%a%);` + `}` + Waiting step 3 leaves the manual tasks above: %a% + XX, $out); + // once the raise is made, the tasks of the steps after it show + [$exit, $out] = runApp($root, ['upgrade', 'tasks', '--no-types', '--no-color']); + Assert::same(1, $exit); + Assert::match( + "%A% src/Code.php:5 Function `strftime()` is deprecated: since PHP 8.1. %A%FOUND the plan leaves manual tasks\n", + $out, + ); + + // a task confirmed with a reason is done + $code = str_replace( + "\tstrftime", + "\t// dresscode:ignore upgrading.php.deprecatedApi -- no replacement yet\n\tstrftime", + FileSystem::read("$root/src/Code.php"), + ); + file_put_contents("$root/src/Code.php", $code); + [$exit, $out] = runApp($root, ['upgrade', 'run', '--no-types', '--no-color']); + Assert::same(0, $exit); + // the last step updated the packages to the newest versions, which nothing has to be said of then + Assert::match( + "%A%Step 3 php left nothing to fix\nUPGRADED 4 steps done, and the final check finds nothing more to upgrade, no tests run", + $out, + ); +}); + + +test('upgrade run --paths narrows the plan, whose run changes nothing outside them', function () { + $root = createTempDir('plan-paths'); + mkdir("$root/src"); + file_put_contents("$root/composer.json", '{"type": "project", "require": {"php": "^8.0"}}'); + file_put_contents("$root/dresscode.neon", "paths: [src]\ncacheDir: cache\n"); + $code = " runApp($root, ['upgrade', 'plan', 'php', '8.4', '--no-types', '--offline', '--no-color'])[1]; + Assert::contains( + "Mode library, `composer.json` gives no type, which Composer reads as `library`, and there is no `composer.lock`\n", + $plan(), + ); + file_put_contents("$root/composer.lock", '{"packages": []}'); + Assert::contains( + 'Mode application, `composer.json` gives no type, which Composer reads as `library`, yet the project has a `composer.lock` of its own, as an application has; `--library` plans it as a library', + $plan(), + ); + + // a terminal asks, Enter taking a library only where the type is written, as a run without one takes it + $ask = fn() => runApp($root, ['upgrade', 'plan', 'php', '8.4', '--no-types', '--offline', '--no-color'], "\n", interactive: true)[1]; + Assert::match('%A?%Plan it as a library, %a% [y/N]%A%Mode application, as you answered%A%', $ask()); + file_put_contents("$root/composer.json", '{"type": "library", "require": {"php": "^8.0"}}'); + Assert::match('%A?%Plan it as a library, %a% [Y/n]%A%Mode library, as you answered%A%', $ask()); + Assert::contains( + "Mode library, `composer.json` gives the type `library`, though the project has a `composer.lock` of its own; `--no-library` plans it as an application\n", + $plan(), + ); + + ProcessRunner::run(['git', 'init', '-q'], $root, 60); + file_put_contents("$root/.gitignore", "composer.lock\n"); + Assert::contains("Mode library, `composer.json` gives the type `library`, and its git ignores `composer.lock`\n", $plan()); + + file_put_contents("$root/composer.json", '{"type": "project", "require": {"php": "^8.0"}}'); + Assert::contains("Mode application, `composer.json` gives the type `project`\n", $plan()); +}); + + +test('upgrade plan --save refuses to forget a step a run did not finish, unless told to discard it', function () { + $root = createTempDir('plan-interrupted'); + mkdir("$root/src"); + file_put_contents("$root/composer.json", '{"type": "project", "require": {"php": "^8.0"}}'); + file_put_contents("$root/dresscode.neon", "paths: [src]\ncacheDir: cache\n"); + file_put_contents("$root/src/Code.php", "snapshots->record(1, 'src/Code.php', 'before', 'after'); + + [$exit, , $err] = runApp($root, ['upgrade', 'plan', 'php', '8.4', '--save', '--no-types', '--offline']); + Assert::same(3, $exit); + Assert::contains('Step 1 of a run did not finish and may have rewritten src/Code.php; saving a plan forgets what it kept', $err); + Assert::same(0, runApp($root, ['upgrade', 'plan', 'php', '8.4', '--save', '--discard', '--no-types', '--offline'])[0]); + Assert::same([], new DressCode\Upgrade\RunState($project)->snapshots->findInterrupted()); +}); + + +test('upgrade run goes on after a raise in a new process, which says how far the whole run got', function () { + $root = createTempDir('upgrade-rerun'); + mkdir("$root/src"); + file_put_contents("$root/composer.json", '{"type": "project", "require": {"php": "^8.0"}}'); + file_put_contents("$root/dresscode.neon", "paths: [src]\ncacheDir: cache\n"); + file_put_contents("$root/src/Code.php", " "$root/composer.php"], + ); + Assert::same(0, $exit, $out); + Assert::same(1, substr_count($out, 'Config ')); + Assert::match(<<<'XX' + %A%Step 1 upgrading.php.implicitNullable 1 file + Step 3 upgrading.php.implicitNullable left nothing to fix + UPGRADED %d% steps done, and the final check finds nothing more to upgrade, no tests run + %A% + XX, str_replace("\r", '', $out)); + + // embedded, the command line of the process is not its own to start again + file_put_contents("$root/composer.json", '{"type": "project", "require": {"php": "^8.0"}}'); + putenv("COMPOSER_BINARY=$root/composer.php"); + try { + [$exit, $out] = runApp($root, ['upgrade', 'run', '--yes', '--no-types', '--no-color']); + } finally { + putenv('COMPOSER_BINARY'); + } + + Assert::same(4, $exit); + Assert::contains( + 'Waiting step 2 raised the dependencies, which what runs after it loads anew: run `dresscode upgrade run` again', + $out, + ); +}); + + +test('upgrade abort puts back the files of a step a run did not finish, and says so where nothing is kept', function () { + $root = createTempDir('upgrade-abort'); + mkdir("$root/src"); + file_put_contents("$root/composer.json", '{"type": "project", "require": {"php": "^8.0"}}'); + file_put_contents("$root/dresscode.neon", "paths: [src]\ncacheDir: cache\n"); + file_put_contents("$root/src/Code.php", 'after'); + $project = new DressCode\Upgrade\Project(DressCode\Config\Loader::loadFile("$root/dresscode.neon"), $root, "$root/dresscode.neon"); + new DressCode\Upgrade\RunState($project)->snapshots->record(1, 'src/Code.php', 'before', 'after'); + + // the status and a dry run of abort say what a run keeps, changing nothing + $plan = new DressCode\Upgrade\Plan( + [new DressCode\Upgrade\Target('php', '8.4')], + [new DressCode\Upgrade\FixStep('bridge', ['php'])], + '1.0', + ); + DressCode\Upgrade\PlanFile::write($plan, $root); + [$exit, $out] = runApp($root, ['upgrade', 'status', '--no-color']); + Assert::same(0, $exit); + Assert::match(<<<'XX' + %A%Plan php 8.4 + 1 bridge what is left `upgrade run` fixes and `upgrade tasks` lists + Stopped step 1 did not finish and may have rewritten src/Code.php + Next `dresscode upgrade abort --dry-run` shows what `upgrade abort` puts back, or `dresscode upgrade run --discard` goes on from the code as it is + XX, $out); + [$exit, $out] = runApp($root, ['upgrade', 'abort', '--dry-run', '--no-color']); + Assert::same(0, $exit); + Assert::contains("Restorable src/Code.php\n", $out); + Assert::same('after', file_get_contents("$root/src/Code.php")); + + [$exit, $out] = runApp($root, ['upgrade', 'abort', '--no-color']); + Assert::same(0, $exit); + Assert::contains("Restored src/Code.php\n", $out); + Assert::same('before', file_get_contents("$root/src/Code.php")); + + [$exit, $out] = runApp($root, ['upgrade', 'abort', '--no-color']); + Assert::same(0, $exit); + Assert::contains("Restored nothing, as no run keeps anything to go back\n", $out); +}); + + +test('upgrade estimate --no-types measures without the types the configuration asks for', function () { + $root = createTempDir('estimate-no-types'); + mkdir("$root/src"); + file_put_contents("$root/src/Code.php", "=8.2"}}'); + file_put_contents("$root/src/a.php", $code); + file_put_contents("$root/src/fixtures/data.php", $code); + [$exit, $out] = runApp($root, ['upgrade', 'today', '--no-color']); + Assert::same(0, $exit); + Assert::same($upgraded, file_get_contents("$root/src/a.php")); + Assert::same($code, file_get_contents("$root/src/fixtures/data.php")); // the data of tests are no code + Assert::match( + "%A%Config none, using `deprecations`\n%A%Upgrading PHP alone, no installed library has upgrading data\n%A%Run `dresscode upgrade today` again: %a%\n", + $out, + ); + + // a file that does not parse may declare what the code calls, which the run says + file_put_contents("$root/src/broken.php", "=8.2"}}'); + file_put_contents("$root/dresscode.neon", "use: [nette]\npaths: [src]\n"); + foreach (['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'] as $name) { + file_put_contents("$root/src/$name.php", $code); + } + + [$exit] = runApp($root, ['upgrade', 'today', '--no-color', '--jobs', '2']); + Assert::same(0, $exit); + Assert::same($upgraded, file_get_contents("$root/src/a.php")); + Assert::same($upgraded, file_get_contents("$root/src/h.php")); + Assert::same(1, runApp($root, ['check', '--no-color'])[0]); +}); + + +test('upgrade today leaves out the files a generator wrote and says how many', function () { + $code = "=8.2"}}'); + file_put_contents("$root/dresscode.neon", "paths: [src]\n"); + file_put_contents("$root/src/a.php", $code); + file_put_contents("$root/src/generated.php", $generated); + + [$exit, $out] = runApp($root, ['upgrade', 'today', '--no-color']); + Assert::same(0, $exit); + Assert::same("=8.2"}}'); + file_put_contents("$root/dresscode.neon", "paths: [src]\nseverity:\n\tupgrading.php.deprecatedApi: warning\n"); + file_put_contents("$root/src/a.php", " $args */ + $run = fn(array $args = []) => runApp($root, array_values(['upgrade', 'today', '--no-color', '--no-cache', ...$args]))[0]; + Assert::same(0, $run()); + Assert::same(0, $run(['--max-warnings', '1'])); + Assert::same(1, $run(['--max-warnings', '0'])); +}); + + +test('upgrade today keeps what the project keeps, in an override too, the sets lying beneath its decisions', function () { + $code = "=8.2"}}'); + file_put_contents( + "$root/dresscode.neon", + "paths: [src]\noverrides:\n\t-\n\t\tpaths: [src/kept.php]\n\t\tupgrading: {api: {replacedCalls: {'curl_close(\$handle)': keep}}}\n", + ); + file_put_contents("$root/src/kept.php", $code); + file_put_contents("$root/src/upgraded.php", $code); + + [$exit, , $err] = runApp($root, ['upgrade', 'today', '--no-color']); + Assert::same(0, $exit); + Assert::same('', $err); + Assert::same($code, file_get_contents("$root/src/kept.php")); + Assert::same("=8.2", "acme/lib": "^3.0"}}'); + file_put_contents("$root/dresscode.neon", "paths: [src]\n"); + file_put_contents("$root/src/a.php", " [ + ['name' => 'acme/lib', 'version' => '3.2.0', 'version_normalized' => '3.2.0.0', 'install-path' => '../acme/lib'], + [ + 'name' => 'acme/tool', + 'version' => '1.0.0', + 'version_normalized' => '1.0.0.0', + 'install-path' => '../acme/tool', + 'extra' => ['dresscode' => ['upgrading-dir' => 'upgrading']], + ], + ]], JSON_THROW_ON_ERROR), + ); + + [, $out] = runApp($root, ['upgrade', 'today', '--no-color']); + Assert::match( + "%A%Upgrading `acme/tool`\nLowest `acme/lib` 3.2 installed, 3.0 required; `composer update --prefer-lowest` %a%\nUnbounded `acme/tool`: not required with a lower bound, %a%\n%A%", + $out, + ); +}); + + +test('upgrade today installs the upgrading data a library of the project needs only when asked, or with --yes', function () { + $root = createTempDir('upgrade-data'); + mkdir("$root/src"); + file_put_contents("$root/composer.json", '{"require": {"php": ">=8.2", "nette/utils": "^4.0"}}'); + file_put_contents("$root/dresscode.neon", "paths: [src]\ncacheDir: cache\n"); + file_put_contents("$root/src/a.php", $code = "=8.2", "acme/upgrade": "^1.0"}}'); + file_put_contents("$root/dresscode.neon", "paths: [src]\n"); + file_put_contents("$root/src/a.php", " [[ + 'name' => 'acme/upgrade', + 'version' => '1.0.0', + 'version_normalized' => '1.0.0.0', + 'install-path' => '../acme/upgrade', + 'extra' => ['dresscode' => ['plugin' => 'UpgradePlugin', 'upgrading-dir' => 'upgrading']], + ]]], JSON_THROW_ON_ERROR), + ); + + // one warning for the plugin, none for the map of its rule + Assert::same( + "Warning: Package `acme/upgrade` brings rules that run only where `use` names it, and in `dresscode upgrade`; skipped, with what its upgrading files set for them.\n", + runApp($root, ['check', '--no-color'])[2], + ); + foreach ([[], ['--only', 'acme/upgrade']] as $only) { + [, $out, $err] = runApp($root, ['upgrade', 'today', '--no-color', ...$only]); + Assert::same('', $err); + Assert::contains('A variable of the upgrade.', $out); + } +}); diff --git a/tests/DressCode/Console/Application.workers.phpt b/tests/DressCode/Console/Application.workers.phpt index 55d50f5087..0670a41e2a 100644 --- a/tests/DressCode/Console/Application.workers.phpt +++ b/tests/DressCode/Console/Application.workers.phpt @@ -1,5 +1,6 @@ ['keyword' => 'lowercase'],'file' => ['trailingWhitespace' => 'forbidden']]);\n", + ); + @mkdir("$root/profile"); // @ directory may already exist + for ($i = 0; $i < 8; $i++) { + file_put_contents("$root/profile/$i.php", " 0); + Assert::same(8, $profile['rules'][DressCode\Rules\Literals\BuiltinCasingRule::class]['mutating']); + Assert::true($profile['phases']['passes']['time'] >= array_sum(array_column($profile['rules'], 'time'))); + $count = [ + array_map(fn($entry) => [$entry['calls'], $entry['mutating']], $profile['rules']), + array_map(fn($entry) => $entry['calls'], $profile['claims']), + array_map( + fn($entry) => $entry['calls'], + array_intersect_key($profile['phases'], ['parse' => 0, 'passes' => 0, 'print' => 0, 'gaps' => 0]), + ), + ]; + array_walk($count, ksort(...)); // the tables are ordered by time, which differs between runs + $counts[] = $count; + } + + Assert::same($counts[0], $counts[1]); + if (findPhpCliBinary() !== null) { + Assert::count(2 + 1, json_decode(FileSystem::read("$root/profile-2.json"), associative: true)['peakMemory']); // the parent and two workers + } + + // writing a baseline is a run of check too, whether it ends with one or with code a fix would change + runApp($root, ['baseline', '--config', "$root/profile.php", '--profile', "$root/profile-baseline.json"]); + Assert::same(8, json_decode(FileSystem::read("$root/profile-baseline.json"), associative: true)['files']); +}); + + test('a worker has the settings of the process the ini file alone would not give it', function () use ($root) { // the configuration turns the rule on by a setting, which a worker has only when it is handed over file_put_contents( @@ -158,3 +214,29 @@ test('a baseline generated by workers is the one the single process writes, and Assert::same(" ['strictArgument' => 'required']]);\n", + ); + $config = ['--config', "$root/jobs.php", '--no-cache', '--jobs', '3']; + $write = function () use ($root, $code) { + file_put_contents("$root/jobs/a.php", $code); + file_put_contents("$root/jobs/b.php", $code); + }; + + $write(); + Assert::same(1, runApp($root, ['fix', ...$config, '--fix-risky=imports.unused'])[0]); + Assert::same($code, (string) file_get_contents("$root/jobs/a.php")); + Assert::same($code, (string) file_get_contents("$root/jobs/b.php")); + + $write(); + Assert::same(0, runApp($root, ['fix', ...$config, '--fix-risky=mistakes.strictArgument'])[0]); + Assert::same("rerun(['--version'])); + + // a command of its own names the script that carries its default configuration + Assert::exception( + fn() => new DressCode\Console\Application(defaultConfig: new DressCode\Config), + InvalidArgumentException::class, + 'A command of its own giving a default configuration names its script, %a%', + ); + + putenv('DRESSCODE_RERUN=1'); + try { + Assert::null(createRerunContext(STDOUT)->rerun(['--version'])); + } finally { + putenv('DRESSCODE_RERUN'); + } +}); diff --git a/tests/DressCode/Console/EstimatePrinter.phpt b/tests/DressCode/Console/EstimatePrinter.phpt new file mode 100644 index 0000000000..87add22843 --- /dev/null +++ b/tests/DressCode/Console/EstimatePrinter.phpt @@ -0,0 +1,159 @@ +print($console); + + Assert::contains("Composer acme/mail 4.0: refused by acme/shop v1.0.0 (^3.2)\n", $out); + Assert::contains("Composer php 8.4: nothing in the lock refuses it\n", $out); +}); + + +test('a group DressCode fixes whole says so, and an estimate that no run follows says it changed nothing', function () { + $topic = new Topic('acme/utils', 'deprecations', Phase::Jump, 1, ['automatic' => 2], '^4.0'); + $estimate = new Estimate([Target::php('8.4')], [$topic], 1, new BlindSpots, [], [], [], true, false, []); + $console = new Console(fopen('php://memory', 'w+') ?: throw new RuntimeException, ColorDepth::None, terminal: false); + $out = new EstimatePrinter($estimate)->print($console); + + Assert::contains('an estimate: nothing was changed', $out); + Assert::contains("Must change, 2 findings, all fixed by DressCode\n", $out); + Assert::contains('fixed by DressCode, once ^4.0 is installed', $out); + Assert::notContains('nothing was changed', new EstimatePrinter($estimate)->print($console, passive: false)); +}); + + +test('the libraries the data know are broken onto lines that keep the width of the output', function () { + $known = ['acme/application' => '3.3', 'acme/component-model' => '3.2', 'acme/http' => '3.4', 'acme/utils' => '4.1.5', 'php' => '8.6']; + $estimate = new Estimate([Target::php('8.4')], [], 1, new BlindSpots, [], [], $known, true, false, []); + $console = new Console(fopen('php://memory', 'w+') ?: throw new RuntimeException, ColorDepth::None, terminal: false); + $out = new EstimatePrinter($estimate)->print($console); + + Assert::contains( + "Rules for `acme/application` up to 3.3, `acme/component-model` up to 3.2, `acme/http` up to 3.4,\n" + . " `acme/utils` up to 4.1.5, `php` up to 8.6\n", + $out, + ); +}); + + +test('the major moves of the update are said under Versions, those the data do not reach marked, the data listing every move', function () { + $estimate = new Estimate( + [new Target('acme/utils', '4.0')], + [], + 1, + new BlindSpots, + [], + [], + ['acme/utils' => '4.1', 'acme/cache' => '2.1'], + true, + false, + [], + new Moves([ + new Move('acme/utils', 'v3.2.10', 'v4.0.11'), + new Move('acme/http', 'v3.1.0', 'v3.2.0'), + new Move('acme/schema', 'v1.3.0', 'v2.0.0'), + new Move('acme/cache', 'v1.4.0', 'v2.3.0'), + ]), + ); + $console = new Console(fopen('php://memory', 'w+') ?: throw new RuntimeException, ColorDepth::None, terminal: false); + $out = new EstimatePrinter($estimate)->print($console); + + Assert::contains( + "Versions `acme/utils` v3.2.10 => v4.0.11, `acme/schema` v1.3.0 => v2.0.0 (no data),\n `acme/cache` v1.4.0 => v2.3.0 (data up to 2.1)\n", + $out, + ); + Assert::same( + [ + ['package' => 'acme/utils', 'from' => 'v3.2.10', 'to' => 'v4.0.11', 'major' => true, 'data' => true, 'dataUpTo' => '4.1'], + ['package' => 'acme/http', 'from' => 'v3.1.0', 'to' => 'v3.2.0', 'major' => false, 'data' => false, 'dataUpTo' => null], + ['package' => 'acme/schema', 'from' => 'v1.3.0', 'to' => 'v2.0.0', 'major' => true, 'data' => false, 'dataUpTo' => null], + ['package' => 'acme/cache', 'from' => 'v1.4.0', 'to' => 'v2.3.0', 'major' => true, 'data' => false, 'dataUpTo' => '2.1'], + ], + new EstimatePrinter($estimate)->toArray()['moves']['packages'], + ); + + // with colors the printer draws its code itself, no backtick left for a second drawing + $colored = new Console(fopen('php://memory', 'w+') ?: throw new RuntimeException, ColorDepth::Ansi256, terminal: false); + $out = new EstimatePrinter($estimate)->print($colored); + Assert::contains("\e[", $out); + Assert::notContains('`', Nette\CommandLine\Ansi::strip($out)); +}); + + +test('the files the check could not process are said, their places not counted', function () { + $estimate = new Estimate( + [Target::php('8.4')], + [], + 2, + new BlindSpots, + [], + [], + [], + true, + false, + [], + unprocessed: ['src/Broken.php' => 'Syntax error: x'], + ); + $console = new Console(fopen('php://memory', 'w+') ?: throw new RuntimeException, ColorDepth::None, terminal: false); + + Assert::contains( + "Unverified 1 file the check could not process, whose findings are not counted: src/Broken.php\n", + new EstimatePrinter($estimate)->print($console), + ); + Assert::same([['file' => 'src/Broken.php', 'message' => 'Syntax error: x']], new EstimatePrinter($estimate)->toArray()['unverified']); +}); + + +test('the moves Composer could not say are unknown, with the reason', function () { + $estimate = new Estimate( + [new Target('acme/utils', '4.0')], + [], + 1, + new BlindSpots, + [], + [], + [], + true, + false, + [], + new Moves(unknown: 'Composer did not answer in time'), + ); + $console = new Console(fopen('php://memory', 'w+') ?: throw new RuntimeException, ColorDepth::None, terminal: false); + + Assert::contains("Versions unknown, Composer did not answer in time\n", new EstimatePrinter($estimate)->print($console)); +}); + + +test('a library widening its constraints moves nothing, which Composer is not asked about', function () { + $estimate = new Estimate([new Target('acme/utils', '4.0')], [], 1, new BlindSpots, [], [], [], true, false, [], library: true); + $console = new Console(fopen('php://memory', 'w+') ?: throw new RuntimeException, ColorDepth::None, terminal: false); + + Assert::contains( + "Versions nothing, a library widens its constraints with `--no-update`\n", + new EstimatePrinter($estimate)->print($console), + ); + Assert::true(new EstimatePrinter($estimate)->toArray()['library']); +}); diff --git a/tests/DressCode/Console/PlanPrinter.phpt b/tests/DressCode/Console/PlanPrinter.phpt new file mode 100644 index 0000000000..737ee6a4e3 --- /dev/null +++ b/tests/DressCode/Console/PlanPrinter.phpt @@ -0,0 +1,29 @@ + explode('Tests ', new PlanPrinter( + new Plan([], [], '1.0', testCommand: $test, quickTestCommand: $quick), + )->print($console))[1]; + + Assert::same("not run, no `--test-command` given\n", $tests(null, null)); + Assert::same("`vendor/bin/tester` after every step\n", $tests('vendor/bin/tester', null)); + Assert::same("`vendor/bin/tester unit` after every step\n", $tests(null, 'vendor/bin/tester unit')); + Assert::same( + "`vendor/bin/tester unit` after every step, `vendor/bin/tester` after a raise and the last one\n", + $tests('vendor/bin/tester', 'vendor/bin/tester unit'), + ); + + // with colors the printer draws its code itself, no backtick left for a second drawing + $colored = new Console(fopen('php://memory', 'w+') ?: throw new RuntimeException, ColorDepth::Ansi256, terminal: false); + $out = new PlanPrinter(new Plan([], [], '1.0', testCommand: 'vendor/bin/tester'))->print($colored); + Assert::notContains('`', Nette\CommandLine\Ansi::strip($out)); +}); diff --git a/tests/DressCode/Console/TasksPrinter.phpt b/tests/DressCode/Console/TasksPrinter.phpt new file mode 100644 index 0000000000..cf40ca8aa7 --- /dev/null +++ b/tests/DressCode/Console/TasksPrinter.phpt @@ -0,0 +1,82 @@ + [$task, $task], 'empty' => [], 'acme/lib' => [$task]], listed: 2)->print($console), + ); + Assert::contains(" src/A.php:1 Write it. [x.y]\n", new TasksPrinter(['php' => [$task, $task]], listed: 2)->print($console)); +}); + + +test('a task shows its line with the one above and the one below, as code, without the indentation they share', function () { + $root = createTempDir('tasks'); + mkdir("$root/src"); + file_put_contents( + "$root/src/Order.php", + " [$task]], root: $root)->print($console), + ); +}); + + +test('a place whose fix waits says what for, and the data keep the risk with its reason', function () { + $place = fn(string $decision, ?Risk $risk, ?string $because = null) => new Task( + 'src/Order.php', + new Violation( + $decision, + 'Write it anew.', + 3, + 1, + Severity::Error, + 'x', + fixable: $risk !== null, + risk: $risk, + refused: $risk !== null, + because: $because, + ), + ); + $printer = new TasksPrinter(['php' => [ + $place('upgrading.php.deprecatedApi', null), + $place('upgrading.syntax.match', Risk::BehaviorChanges, 'a case compares loosely'), + $place('upgrading.api.replacedMembers', Risk::TypeUnknown), + ]]); + $console = new Console(fopen('php://memory', 'w+') ?: throw new RuntimeException, ColorDepth::None, terminal: false); + + Assert::match( + <<<'XX' + Manual 3 tasks the fixes left + src/Order.php:3 Write it anew. [upgrading.php.deprecatedApi] + src/Order.php:3 Write it anew. [upgrading.syntax.match] + its fix is risky, as a case compares loosely; once you checked it, `fixRisky: [upgrading.syntax.match]` allows it + src/Order.php:3 Write it anew. [upgrading.api.replacedMembers] + its fix needs the type of the expression, which the analysis does not know; where the types are off, `--types` turns them on + + XX, + $printer->print($console), + ); + Assert::same( + [[false, null, null], [true, 'behaviorChanges', 'a case compares loosely'], [true, 'typeUnknown', null]], + array_map(fn(array $task) => [$task['fixable'], $task['risk'], $task['because']], $printer->toArray()['tasks']), + ); +}); diff --git a/tests/DressCode/Console/explain.phpt b/tests/DressCode/Console/explain.phpt index 0ef7cf26b4..8ff2f09c0b 100644 --- a/tests/DressCode/Console/explain.phpt +++ b/tests/DressCode/Console/explain.phpt @@ -35,7 +35,9 @@ test('every decision can be explained', function () use ($registry, $resolved) { $console->setColorDepth(ColorDepth::None); $printer = new ExplainPrinter($registry); foreach ($resolved->decisions as $path => $decision) { - Assert::contains("`$path`", Markup::formatMarkdown($console, $printer->printDecision($decision)), $path); + $markdown = $printer->printDecision($decision); + Assert::match("## `$path`\n\n%A%\n\nTakes: %A%\n\nHere %A%", $markdown, $path); + Assert::notSame('', Markup::formatMarkdown($console, $markdown), $path); } }); @@ -147,6 +149,8 @@ test('explain without a decision draws the document that the markdown format wri [$code, $text] = explainApp($root, []); Assert::same(0, $code); Assert::contains('Decisions of this project', $text); + Assert::notContains('# Decisions of this project', $text); + Assert::notContains('## controlFlow', $text); Assert::contains('Composed of:', $text); Assert::contains('imports.unused', $text); }); diff --git a/tests/DressCode/Console/fixtures/upgrade-plugin.php b/tests/DressCode/Console/fixtures/upgrade-plugin.php new file mode 100644 index 0000000000..bb03ab4bed --- /dev/null +++ b/tests/DressCode/Console/fixtures/upgrade-plugin.php @@ -0,0 +1,39 @@ +report($node, 'A variable of the upgrade.', fixable: false); + } +} + + +final class UpgradePlugin implements Plugin +{ + public function getManifest(): PluginManifest + { + return new PluginManifest(rules: [UpgradeVariableRule::class], section: 'acmeUpgrade'); + } +} diff --git a/tests/DressCode/Console/init.questions.phpt b/tests/DressCode/Console/init.questions.phpt index 19023054f8..50834bdee2 100644 --- a/tests/DressCode/Console/init.questions.phpt +++ b/tests/DressCode/Console/init.questions.phpt @@ -211,8 +211,8 @@ test('a close call of standards is asked first, and the answer measures against $root = createProject('close', stragglers()); [$code, $out] = runInit($root, [], "2\n\n"); Assert::same(0, $code); - Assert::match('%A%Your code is as near to `%a%` as to `%a%`; which standard should it follow?%A%', $out); - Assert::notSame('perCs', Loader::loadFile("$root/dresscode.neon")->use[0] ?? null); + Assert::match('%A%Your code is as near to `perCs` as to `nette` and `symfony`; which standard should it follow?%A%', $out); + Assert::same('nette', Loader::loadFile("$root/dresscode.neon")->use[0] ?? null); // without a terminal the nearer is taken, and the line says how to measure against the other $root = createProject('close-pipe', stragglers()); diff --git a/tests/DressCode/Console/init.scope.phpt b/tests/DressCode/Console/init.scope.phpt index ffb4600555..7170c7d159 100644 --- a/tests/DressCode/Console/init.scope.phpt +++ b/tests/DressCode/Console/init.scope.phpt @@ -157,7 +157,7 @@ test('the sample is every k-th file of every directory, the same for the same tr }); -test('the probes run in-process with --jobs 1 and measure the same', function () use ($tabbed) { +test('the probes measure the same in workers as with --jobs 1 in the process', function () use ($tabbed) { $root = createProject('jobs', ['src/A.php' => $tabbed, 'src/B.php' => str_replace('A', 'B', $tabbed), 'composer.json' => '{}']); $neon = fn(?int $jobs) => json_decode( runInit($root, ['--use', 'perCs', '--dry-run', '--format', 'json'], jobs: $jobs)[1], diff --git a/tests/DressCode/Engine/Baseline.phpt b/tests/DressCode/Engine/Baseline.phpt index a1b89d1e65..53ddcd04de 100644 --- a/tests/DressCode/Engine/Baseline.phpt +++ b/tests/DressCode/Engine/Baseline.phpt @@ -1,6 +1,6 @@ [$b], 'src/a.php' => [$a, $c]]); Assert::same(3, $baseline->count()); $baseline->save($file); Assert::match(<<<'XX' @@ -67,11 +64,11 @@ test('of the refused risky fixes it holds only those changing what the code does risk: $risk, refused: true, ); - $baseline = Baseline::fromResults([new FileResult('src/a.php', '', '', [ + $baseline = Baseline::fromViolations(['src/a.php' => [ $refused('test/type', Risk::TypeUnknown), $refused('test/name', Risk::NameUncertain), $refused('test/behavior', Risk::BehaviorChanges), - ])]); + ]]); Assert::same(1, $baseline->count()); Assert::true($baseline->has('src/a.php', 'test/behavior')); }); @@ -81,7 +78,7 @@ test('a fingerprint of nothing but digits survives the round trip', function () // PHP turns such a key into an int, NEON writes an unquoted number and the loader refuses the file $digits = new Violation('test/a', 'M.', 1, null, Severity::Error, fingerprint: '9231335105126121'); $file = "$dir/digits.neon"; - Baseline::fromResults([new FileResult('src/a.php', '', '', [$digits])])->save($file); + Baseline::fromViolations(['src/a.php' => [$digits]])->save($file); Assert::contains("'9231335105126121'", (string) file_get_contents($file)); $baseline = Baseline::load($file); assert($baseline !== null); diff --git a/tests/DressCode/Engine/Helpers.phpt b/tests/DressCode/Engine/Helpers.phpt index d1c4fc9d7c..adf4f6358c 100644 --- a/tests/DressCode/Engine/Helpers.phpt +++ b/tests/DressCode/Engine/Helpers.phpt @@ -115,6 +115,15 @@ test('writeFile leaves a read-only file alone', function () { }); +test('replaceFile writes the file whole, its directory created, and leaves no temporary file', function () { + $dir = createTempDir('write'); + Helpers::replaceFile("$dir/state/a.json", 'one'); + Helpers::replaceFile("$dir/state/a.json", 'two'); + Assert::same('two', file_get_contents("$dir/state/a.json")); + Assert::same(['a.json'], array_values(array_diff(scandir("$dir/state"), ['.', '..']))); +}); + + test('createFile never writes over a file that exists', function () { $dir = createTempDir('write'); Assert::true(Helpers::createFile("$dir/a.neon", 'one')); diff --git a/tests/DressCode/Engine/PassLoop.phpt b/tests/DressCode/Engine/PassLoop.phpt index a07d06e269..cefd3c108e 100644 --- a/tests/DressCode/Engine/PassLoop.phpt +++ b/tests/DressCode/Engine/PassLoop.phpt @@ -772,7 +772,7 @@ test('suppression stops the fix', function () { test('a rule may fix a violation the baseline holds, and the contract holds', function () { $code = "violations[0]])]); + $baseline = DressCode\Engine\Baseline::fromViolations(['test.php' => [$result->violations[0]]]); [$file, $result] = run($code, [new RenameA], baseline: $baseline); Assert::same("violations, fn($v) => $v->decision === 'mistakes.globalStatement', )); - $baseline = Baseline::fromResults([new FileResult('a.php', $code, $code, $global)]); + $baseline = Baseline::fromViolations(['a.php' => $global]); $result = processWithBaseline($rules(), $code, $baseline); Assert::same("output); @@ -203,7 +203,7 @@ test('a violation the baseline holds is not recognized in a later round on a lin test('a violation the baseline holds is not recorded, and a rule that can fix it fixes it', function () { $rules = fn() => [RuleBuilder::createRule(DressCode\Rules\Literals\StringQuotesRule::class, ['literals.quotes' => 'single'])]; $code = " processWithBaseline($rules(), $code, null)->violations]); $result = processWithBaseline($rules(), $code, $baseline); Assert::same("output); diff --git a/tests/DressCode/Engine/Profiler.phpt b/tests/DressCode/Engine/Profiler.phpt new file mode 100644 index 0000000000..e2b8722fbb --- /dev/null +++ b/tests/DressCode/Engine/Profiler.phpt @@ -0,0 +1,53 @@ +addPhase('parse', 10); + $worker->addRule('a/rule', 5, mutated: true); + $worker->addRule('a/rule', 7, mutated: false); + $worker->addClaim('a/gap', 3); + $worker->addFile(['path' => 'x.php', 'size' => 1, 'time' => 30]); + $records = $worker->takeRecords(); + + $worker->addPhase('parse', 20); + $worker->addFile(['path' => 'y.php', 'size' => 1, 'time' => 40]); + $second = $worker->takeRecords(); + Assert::same(['parse' => [20, 1]], $second['phases']); // taken records are forgotten + + $parent = new Profiler; + $parent->merge(json_decode(json_encode($records), associative: true)); // as it travels between processes + $parent->merge(json_decode(json_encode($second), associative: true)); + $profile = $parent->toArray(); + + Assert::same(Profiler::Schema, $profile['schema']); + Assert::same(2, $profile['files']); + Assert::same(['parse' => ['time' => 30, 'calls' => 2]], $profile['phases']); + Assert::same(['a/rule' => ['time' => 12, 'calls' => 2, 'mutating' => 1]], $profile['rules']); + Assert::same(['a/gap' => ['time' => 3, 'calls' => 1]], $profile['claims']); + Assert::same(['y.php', 'x.php'], array_column($profile['slowestFiles'], 'path')); +}); + + +test('the most expensive come first, the slowest files in detail and every file in short', function () { + $profiler = new Profiler; + $profiler->addRule('cheap', 1, mutated: false); + $profiler->addRule('dear', 100, mutated: false); + for ($i = 1; $i <= 120; $i++) { + $profiler->addFile(['path' => "$i.php", 'size' => $i, 'time' => $i]); + } + + $profile = $profiler->toArray(); + Assert::same(['dear', 'cheap'], array_keys($profile['rules'])); + Assert::same(120, $profile['files']); + Assert::count(50, $profile['slowestFiles']); + Assert::same('120.php', $profile['slowestFiles'][0]['path']); + Assert::same('71.php', $profile['slowestFiles'][49]['path']); + Assert::count(120, $profile['fileTimes']); // every file, for a sample to be drawn from + Assert::same(['1.php', '10.php', '100.php'], array_slice(array_keys($profile['fileTimes']), 0, 3)); +}); diff --git a/tests/DressCode/Engine/RunResult.phpt b/tests/DressCode/Engine/RunResult.phpt index 0c79e3b083..f2c4a112ce 100644 --- a/tests/DressCode/Engine/RunResult.phpt +++ b/tests/DressCode/Engine/RunResult.phpt @@ -49,7 +49,7 @@ test('a check reports the violations of the code, a fix leaves what the fixed te Assert::same(4, $fix->countViolations()); Assert::same(4, $fix->countReported()); Assert::same(1, $fix->countReported(Severity::Error)); - Assert::same($fix->countRemaining(), $fix->countReported()); + Assert::same(4, $fix->countRemaining()); }); @@ -107,3 +107,17 @@ test('the derived violations are counted among those the run reports', function Assert::same(1, new RunResult($files, fix: true)->countDerived(Severity::Error)); Assert::same(0, new RunResult($files, fix: true)->countDerived(Severity::Warning)); }); + + +test('the violations no rule has a fix for are counted among those the run reports', function () { + $unfixable = new Violation('test/a', 'M.', 1, null, Severity::Error, fingerprint: 'a', fixable: false); + $files = [FileSummary::of(new FileResult( + 'a.php', + "countUnfixable()); + Assert::same(1, new RunResult($files, fix: true)->countUnfixable()); +}); diff --git a/tests/DressCode/Engine/Runner.phpt b/tests/DressCode/Engine/Runner.phpt index 0d79b45888..6b7c9ef06e 100644 --- a/tests/DressCode/Engine/Runner.phpt +++ b/tests/DressCode/Engine/Runner.phpt @@ -2,6 +2,7 @@ use DressCode\{Analyses, Config, ConfigurationException, FileResult, NodeRule, Reporter, RuleContext, RuleInfo, Stage}; use DressCode\Engine\{FileProcessors, FileSummary, PhpFileProcessor, ReportPolicy, RunInfo, Runner, RunResult}; +use DressCode\Reporters\CollectingReporter; use PhpSyntax\{Node, Token}; use PhpSyntax\Nodes\Expression\VariableNode; use Tester\Assert; @@ -155,6 +156,9 @@ final class RecordingReporter implements Reporter /** @var array */ public array $texts = []; + /** @var array */ + public array $results = []; + public function start(RunInfo $run): void { @@ -164,6 +168,7 @@ final class RecordingReporter implements Reporter public function reportFile(FileResult $result): void { + $this->results[$result->path] = $result; $this->texts[$result->path] = [$result->code, $result->output]; $this->events[] = "file $result->path " . json_encode($result->changed) . ' ' . json_encode($result->written) . ($result->failure === null ? '' : " failure: $result->failure"); @@ -424,10 +429,46 @@ test('a reporter sees the texts of a file, what the run keeps of it does not', f }); +test('a reporter sees the violations of a file, the run only counts them, a large tree having millions', function () use ($root) { + file_put_contents("$root/src/a.php", "> */ + public array $seen = []; + + + public function start(RunInfo $run): void + { + } + + + public function reportFile(FileResult $result): void + { + array_push($this->seen, ...array_map(WeakReference::create(...), $result->violations)); + } + + + public function finish(RunResult $result): void + { + } + }; + + $result = engine($root)->run(['src/a.php', 'src/b.php'], fix: false, reporter: $reporter); + Assert::same(2, $result->countViolations()); + Assert::count(2, $reporter->seen); + Assert::null($reporter->seen[0]->get()); // the processor may still hold those of the last file +}); + + test('processCode processes a text for the given path and writes nothing', function () use ($root) { $runner = engine($root); Assert::true($runner->processCode("$root/src/x.php", "changed); + Assert::false(is_file("$root/src/x.php")); Assert::same('src/x.php', $runner->processCode("$root/src/x.php", 'path); + + file_put_contents("$root/src/a.php", "processCode("$root/src/a.php", "changed); + Assert::same("run(['src/a.php'], false, new RecordingReporter)->files, - ); + $generated = new CollectingReporter; + new Runner($processor(null), $root)->run(['src/a.php'], false, $generated); + $baseline = DressCode\Engine\Baseline::fromViolations($generated->violations); Assert::same(1, $baseline->count()); $run = new Runner($processor($baseline), $root, baseline: $baseline)->run(['src/a.php', 'src/b.php'], false, new RecordingReporter); Assert::same(1, $run->countViolations()); // the one of src/b.php, which the baseline does not know Assert::same(1, $run->baselined); - Assert::same([], $run->files[0]->violations); + Assert::same(0, $run->files[0]->violations->count()); Assert::same([], $run->warnings); }); @@ -462,23 +503,26 @@ test('a violation the baseline holds is fixed by a rule that can fix it, and its Config::DefaultPhpVersion, policy: new ReportPolicy(baseline: $baseline), ); - $generated = new Runner($processor(null), $root)->run(['src/a.php'], false, new RecordingReporter)->files; + $generated = new CollectingReporter; + new Runner($processor(null), $root)->run(['src/a.php'], false, $generated); // every run loads the baseline anew, and an instance remembers the entries its runs matched $runner = function () use ($processor, $root, $generated): Runner { - $baseline = DressCode\Engine\Baseline::fromResults($generated); + $baseline = DressCode\Engine\Baseline::fromViolations($generated->violations); return new Runner($processor($baseline), $root, baseline: $baseline); }; // check reports only what the baseline does not know, and fix reports the same - $fingerprints = fn(RunResult $run) => array_map( - fn(FileSummary $file) => array_map(fn($violation) => $violation->fingerprint, $file->violations), - $run->files, + $fingerprints = fn(CollectingReporter $reporter) => array_map( + fn(array $violations) => array_column($violations, 'fingerprint'), + $reporter->violations, ); - $check = $runner()->run(['src/a.php', 'src/b.php'], false, new RecordingReporter); + $checked = new CollectingReporter; + $check = $runner()->run(['src/a.php', 'src/b.php'], false, $checked); Assert::same(1, $check->countViolations()); Assert::same(1, $check->baselined); - $fix = $runner()->run(['src/a.php', 'src/b.php'], true, new RecordingReporter); - Assert::same($fingerprints($check), $fingerprints($fix)); + $fixed = new CollectingReporter; + $fix = $runner()->run(['src/a.php', 'src/b.php'], true, $fixed); + Assert::same($fingerprints($checked), $fingerprints($fixed)); Assert::same(0, $fix->getExitCode()); Assert::same([], $fix->warnings); // the first round matched the entry @@ -597,9 +641,10 @@ test('a cached file tells the baseline what it matched, so a second run counts t Config::DefaultPhpVersion, policy: new ReportPolicy(baseline: $baseline), ); - $generated = new Runner($processor(null), $root)->run(['src/a.php'], false, new RecordingReporter); + $generated = new CollectingReporter; + new Runner($processor(null), $root)->run(['src/a.php'], false, $generated); $run = function () use ($root, $file, $processor, $generated): RunResult { - $baseline = DressCode\Engine\Baseline::fromResults($generated->files); + $baseline = DressCode\Engine\Baseline::fromViolations($generated->violations); return new Runner($processor($baseline), $root, baseline: $baseline, cache: DressCode\Engine\ResultCache::load($file, 'cfg')) ->run(['src/a.php'], false, new RecordingReporter); }; @@ -621,9 +666,10 @@ test('an entry of the baseline is stale only when its file was processed and its Config::DefaultPhpVersion, policy: new ReportPolicy(baseline: $baseline), ); - $generated = new Runner($processor(true), $root)->run(['src/a.php', 'src/b.php'], false, new RecordingReporter); + $generated = new CollectingReporter; + new Runner($processor(true), $root)->run(['src/a.php', 'src/b.php'], false, $generated); $warnings = function (bool $rename, bool $narrowed, bool $both) use ($root, $processor, $generated): array { - $baseline = DressCode\Engine\Baseline::fromResults($generated->files); + $baseline = DressCode\Engine\Baseline::fromViolations($generated->violations); return new Runner($processor($rename, $baseline), $root, baseline: $baseline, narrowed: $narrowed) ->run($both ? ['src/a.php', 'src/b.php'] : ['src/a.php'], false, new RecordingReporter) ->warnings; @@ -651,10 +697,12 @@ test('a fix is judged by the text it leaves, so a problem reported beside a fix cache: DressCode\Engine\ResultCache::load($file, 'cfg'), ); - $run = $runner()->run(['src/a.php'], true, new RecordingReporter); + $reporter = new RecordingReporter; + $run = $runner()->run(['src/a.php'], true, $reporter); Assert::same(" $v->message, $run->files[0]->violations)); - Assert::same(['A problem no fix removes.'], array_map(fn($v) => $v->message, $run->files[0]->remaining)); + $result = $reporter->results['src/a.php']; + Assert::same(['A problem no fix removes.', 'Rename $a.'], array_column($result->violations, 'message')); + Assert::same(['A problem no fix removes.'], array_column($result->remaining, 'message')); Assert::same(1, $run->getExitCode()); Assert::false($runner()->run(['src/a.php'], false, new RecordingReporter)->files[0]->cached); // the fixed text was not clean }); diff --git a/tests/DressCode/Engine/Suppression.phpt b/tests/DressCode/Engine/Suppression.phpt index c21ea19747..66b26d8054 100644 --- a/tests/DressCode/Engine/Suppression.phpt +++ b/tests/DressCode/Engine/Suppression.phpt @@ -316,3 +316,19 @@ test('a comment the configuration names silences its rules on its line', functio Assert::true($s->isSilenced('dresscode/noLooseComparisons', 11)); Assert::false($s->isSilenced('dresscode/noLooseComparisons', 12)); }); + + +test('a directive is read with its kind, names and reason, and a comment without one none', function () { + Assert::same( + [ + 'kind' => 'ignore', + 'names' => 'upgrading.php', + 'reason' => 'the locale', + 'text' => 'dresscode:ignore upgrading.php -- the locale', + 'offset' => 3, + ], + Suppression::findDirective('// dresscode:ignore upgrading.php -- the locale'), + ); + Assert::same(['disable', '', ''], array_slice(array_values(Suppression::findDirective('/* phpcs:disable */') ?? []), 0, 3)); + Assert::null(Suppression::findDirective('// the ignore of dresscode')); +}); diff --git a/tests/DressCode/Engine/WorkerCodec.phpt b/tests/DressCode/Engine/WorkerCodec.phpt index f050bd3dde..ff0f7e2a06 100644 --- a/tests/DressCode/Engine/WorkerCodec.phpt +++ b/tests/DressCode/Engine/WorkerCodec.phpt @@ -1,5 +1,6 @@ code); }; -test('a result survives the way from a worker to the parent and back', function () use ($roundTrip) { +test('a result survives the way from a worker to the parent and back, with what the worker measured', function () use ($roundTrip) { $violation = new Violation( 'test/a', 'A.', @@ -29,6 +30,7 @@ test('a result survives the way from a worker to the parent and back', function offset: 6, length: 2, originalLines: [2, 3], + source: new Layer(LayerKind::Package, 'php.neon', 'php', 'upgrading.php.deprecatedApi', 'php', '8.5', '8.0'), ); $unfixable = new Violation('test/b', 'B.', 3, null, Severity::Error, fingerprint: '5678', fixable: false); $result = new FileResult( @@ -46,15 +48,15 @@ test('a result survives the way from a worker to the parent and back', function ], ); $result->markWritten(); - Assert::equal($result, $roundTrip($result)); + Assert::equal([$result, ['files' => [1]]], $roundTrip($result, ['files' => [1]])); }); test('an output that is not valid UTF-8 survives the way byte for byte', function () { $code = "output, $decoded->output); Assert::same($code, $decoded->code); }); @@ -62,15 +64,15 @@ test('an output that is not valid UTF-8 survives the way byte for byte', functio test('a path that is not valid UTF-8 survives the way byte for byte', function () use ($roundTrip) { $result = new FileResult("\xE9.php", "code); + $json = json_encode(WorkerCodec::encode($result, null), JSON_THROW_ON_ERROR | JSON_INVALID_UTF8_SUBSTITUTE); + [$decoded] = WorkerCodec::decode(json_decode($json, associative: true), $result->code); Assert::same("bad \u{FFFD} byte.", $decoded->violations[0]->message); Assert::same("bad \u{FFFD} byte.", $decoded->remaining[0]->message); }); @@ -78,8 +80,8 @@ test('a message that is not valid UTF-8 gets through the transport with the bad test('an unchanged output, a syntax error and a result from the cache', function () use ($roundTrip) { $clean = new FileResult('a.php', " processWith(new WorkerPool(fakeWorker('stall'), jobs: 1, taskTimeout: 1)), RuntimeException::class, - 'A worker has spent more than 1 s on `a.php`; a rule has most likely looped.%A?%', + 'A worker process has not answered about `a.php` within 1 s: a rule may loop on it, or the answer does not reach the main process. Run with `--jobs 1`, which uses no workers: if it finishes, the rules are fine.%A?%', ); Assert::true(microtime(as_float: true) - $started < 10); }); diff --git a/tests/DressCode/Engine/fixtures/fake-worker.php b/tests/DressCode/Engine/fixtures/fake-worker.php index 467751857f..29060c21c9 100644 --- a/tests/DressCode/Engine/fixtures/fake-worker.php +++ b/tests/DressCode/Engine/fixtures/fake-worker.php @@ -53,6 +53,7 @@ 'cached' => false, 'removedImports' => [], 'mutatedRules' => [], + 'profile' => null, 'dependencies' => ['stubs/' . (mb_check_encoding($name = (string) base64_decode($path), 'UTF-8') ? $name : 'other') . '.stub'], 'runWarnings' => ['The types go without the configuration.'], ], JSON_THROW_ON_ERROR) . "\n"; diff --git a/tests/DressCode/Interop/Translator.phpt b/tests/DressCode/Interop/Translator.phpt index d2c17e3c47..2261016cb4 100644 --- a/tests/DressCode/Interop/Translator.phpt +++ b/tests/DressCode/Interop/Translator.phpt @@ -142,7 +142,7 @@ test('every rule read is counted once under the worst said of it', function () { // a rule set names rules and is none, a set for a version of PHP stands for its rules Assert::same(1, (new Translator)->translate(['@PSR12' => true, 'cast_spaces' => true])->ruleCount); - Assert::true((new Translator)->translate(['@PHP84Migration' => true])->ruleCount > 1); + Assert::same(14, (new Translator)->translate(['@PHP84Migration' => true])->ruleCount); }); @@ -1211,7 +1211,6 @@ test('the sniffs of PSR12 listed one by one translate, all but four that no rule 'Squiz.WhiteSpace.ControlStructureSpacing', 'Squiz.WhiteSpace.ScopeClosingBrace', 'Squiz.WhiteSpace.ScopeKeywordSpacing', 'Squiz.WhiteSpace.SuperfluousWhitespace', ]; - Assert::count(60, $sniffs); $translation = (new Translator)->translate(array_fill_keys($sniffs, true)); $uncovered = [ 'Generic.PHP.DisallowAlternativePHPTags', diff --git a/tests/DressCode/Measuring/StandardChoice.phpt b/tests/DressCode/Measuring/StandardChoice.phpt index 2978ef95bf..7da3f32269 100644 --- a/tests/DressCode/Measuring/StandardChoice.phpt +++ b/tests/DressCode/Measuring/StandardChoice.phpt @@ -62,5 +62,5 @@ test('a standard a rule failed under is chosen only where every one failed, its ), array_combine(array_keys($probes), array_keys($probes))); } }; - Assert::notSame(['perCs'], StandardChoice::measure(ProjectFacts::detect($root), null, $runner, [])->presets); + Assert::same(['psr12'], StandardChoice::measure(ProjectFacts::detect($root), null, $runner, [])->presets); }); diff --git a/tests/DressCode/Plugin/plugin.phpt b/tests/DressCode/Plugin/plugin.phpt index 4170ccae10..a9d2514312 100644 --- a/tests/DressCode/Plugin/plugin.phpt +++ b/tests/DressCode/Plugin/plugin.phpt @@ -20,7 +20,13 @@ function runPlugin(array $args, ?string $cwd = null, ?Config $default = null): a { $out = fopen('php://memory', 'w+') ?: throw new RuntimeException; $err = fopen('php://memory', 'w+') ?: throw new RuntimeException; - $app = new Application($out, $err, cwd: $cwd ?? __DIR__ . '/fixtures/project', defaultConfig: $default); + $app = new Application( + $out, + $err, + cwd: $cwd ?? __DIR__ . '/fixtures/project', + script: __DIR__ . '/../../../bin/dresscode', + defaultConfig: $default, + ); $code = $app->run(['dresscode', ...$args]); rewind($out); rewind($err); diff --git a/tests/DressCode/Presets/sets.phpt b/tests/DressCode/Presets/sets.phpt index 621cfe8a50..cb80f6a780 100644 --- a/tests/DressCode/Presets/sets.phpt +++ b/tests/DressCode/Presets/sets.phpt @@ -67,6 +67,8 @@ test('a decision is made by a set or a standard, or written by the project on pu 'upgrading.classes.Override', // a guarantee the code takes on, which no older construct gave 'upgrading.phpdoc.readonly', // an annotation may promise what the code does not keep, which only the project knows 'upgrading.classes.SensitiveParameter', // what is sensitive the project knows best + // what the estimate of an upgrade counts of what it cannot see, nothing a project fixes + 'upgrading.unseen.classNameString', 'upgrading.unseen.dynamicAccess', // the maps: a set lets the upgrading files of the packages in, a project writes its own 'upgrading.api.attributeForAnnotation', 'upgrading.api.attributeForMember', 'upgrading.api.forbiddenClasses', 'upgrading.api.forbiddenConstants', 'upgrading.api.forbiddenFunctions', diff --git a/tests/DressCode/Presets/symfony.phpt b/tests/DressCode/Presets/symfony.phpt index d8cb1ad2b4..15a64235cc 100644 --- a/tests/DressCode/Presets/symfony.phpt +++ b/tests/DressCode/Presets/symfony.phpt @@ -16,94 +16,65 @@ require __DIR__ . '/../../bootstrap.php'; $registry = new PluginRegistry; $resolver = new ConfigResolver($registry); -$resolved = $resolver->resolve(new Config(use: ['symfony']), Config::DefaultPhpVersion); -$rules = RuleBuilder::buildRules($resolved); // which rules run, not in what order -$slugs = array_map(fn($rule) => ruleSlug($rule), $rules); -sort($slugs); -$expected = [ - 'delimiterSpacing', - 'arraySyntax', - 'trailingComma', - 'classHeadSpacing', - 'nameCasing', - 'memberOrder', - 'privateForProtected', - 'noGroupedDeclarations', +$names = function (string $preset) use ($resolver): array { + $names = array_map( + fn($rule) => ruleSlug($rule), + RuleBuilder::buildRules($resolver->resolve(new Config(use: [$preset]), Config::DefaultPhpVersion)), + ); + sort($names); + return $names; +}; +$symfonyAdds = [ 'uselessNullInitialization', - 'visibilityRequired', - 'modifierOrder', 'commentSpacing', 'noEmptyComments', 'noHashComments', - 'noBracelessBodies', - 'elseifNotation', - 'fallThroughComment', - 'multilineCondition', 'noAlternativeSyntax', 'noContinueInSwitch', - 'noEmptyStatements', - 'switchCaseNotation', - 'switchCaseSpacing', 'uselessBraces', - 'uselessParenthesesAfterConstruct', 'uselessElse', 'uselessReturn', - 'binaryOperatorSpacing', - 'castCanonicalType', - 'operandSpacing', - 'emptyArgumentParentheses', 'increment', - 'multilineBinaryOperator', + 'memberAccessSpacing', + 'noBacktickOperators', 'noDoubleNegations', 'notEqualsNotation', - 'memberAccessSpacing', - 'ternaryOperatorSpacing', + 'uselessParenthesesAfterConstruct', 'yoda', - 'declareSpacing', - 'finalLineEndings', - 'openingTagNotation', - 'lineEnding', - 'noBom', - 'noClosingTag', - 'noInvalidUtf8', - 'noTrailingWhitespace', - 'strictTypesRequired', - 'arrowFunctionForClosure', - 'functionNameSpacing', 'methodCasing', - 'namedArgumentSpacing', 'noDollarBraceInterpolations', - 'builtinCasing', - 'noBacktickOperators', 'stringQuotes', - 'importNotation', - 'declaredNameCasing', - 'importOrder', 'globalNameQualification', - 'optimizedCallNotation', - 'uselessLeadingBackslash', + 'importNotation', 'noUnusedImports', + 'optimizedCallNotation', 'uselessAlias', 'phpdocBlankLines', 'phpdocTypeNotation', 'nullableTypeForDefaultNull', - 'typeDeclarationSpacing', - 'typeNotation', - 'attributePosition', - 'attributeSpacing', - 'statementBlankLines', - 'memberBlankLines', - 'blockBlankLines', - 'bracesPosition', - 'commaSpacing', - 'constructSpacing', - 'indentation', - 'semicolonSpacing', - 'noStatementsSharingLine', ]; +// what breaks a construct over lines, which Symfony leaves to the author, and what its rule set does not have +$symfonyOff = [ + 'multilineArray', + 'multilineImplements', + 'multilineFor', + 'multilineChain', + 'multilineMatchArm', + 'multilineTernary', + 'lineLength', + 'multilineCall', + 'multilineSignature', + 'heredocIndentation', + 'nowdocForHeredoc', + 'phpdocAboveAttributes', +]; +$expected = [...array_diff($names('perCs'), $symfonyOff), ...$symfonyAdds]; sort($expected); -Assert::same($expected, $slugs); +Assert::same($expected, $names('symfony')); + +$resolved = $resolver->resolve(new Config(use: ['symfony']), Config::DefaultPhpVersion); +$rules = RuleBuilder::buildRules($resolved); Assert::same([' ', null], [$resolved->indent, $resolved->lineEnding]); $style = $resolved->createStyle(); diff --git a/tests/DressCode/Reporters/reporters.phpt b/tests/DressCode/Reporters/reporters.phpt index 6be0346cee..162f163203 100644 --- a/tests/DressCode/Reporters/reporters.phpt +++ b/tests/DressCode/Reporters/reporters.phpt @@ -1,5 +1,6 @@ .', 2, null, Severity::Warning, fingerprint: 'f2', derivedFrom: 'f1'), new Violation('test/rename', 'Rename $c.', 3, 1, Severity::Error, fingerprint: 'f3', derivedFrom: 'f1'), ], ['Rule test/x is faulty: it changed the file without reporting a violation.'], remaining: [ @@ -354,14 +362,24 @@ test('lines: the path relative to the working directory or absolute, a message o test('an empty scope still gets the skeleton of a machine-readable format', function () { + $reports = []; foreach ([JsonReporter::class, CheckstyleReporter::class, GithubReporter::class] as $class) { $stream = memory(); $reporter = new $class($stream); $reporter->start(new RunInfo('', false, 0)); $reporter->finish(new RunResult([], fix: false)); rewind($stream); - Assert::notSame('', (string) stream_get_contents($stream), $class); + $reports[$class] = (string) stream_get_contents($stream); } + + $json = json_decode($reports[JsonReporter::class], associative: true, flags: JSON_THROW_ON_ERROR); + Assert::same([], $json['files']); + Assert::same(0, $json['summary']['files']); + Assert::same( + "\n\n\n", + $reports[CheckstyleReporter::class], + ); + Assert::same("no violations in no files\n", $reports[GithubReporter::class]); }); @@ -570,7 +588,13 @@ test('json', function () { "refused": false, "because": null, "fingerprint": "f1", - "derivedFrom": null + "derivedFrom": null, + "source": { + "package": "acme/upgrade-lib", + "library": "acme/lib", + "since": "3.0", + "from": "2.4" + } }, { "decision": "test/report", @@ -587,7 +611,8 @@ test('json', function () { "refused": false, "because": null, "fingerprint": "f2", - "derivedFrom": "f1" + "derivedFrom": "f1", + "source": null }, { "decision": "test/rename", @@ -604,7 +629,8 @@ test('json', function () { "refused": false, "because": null, "fingerprint": "f3", - "derivedFrom": "f1" + "derivedFrom": "f1", + "source": null } ], "remaining": [ @@ -623,7 +649,8 @@ test('json', function () { "refused": false, "because": null, "fingerprint": "f2", - "derivedFrom": null + "derivedFrom": null, + "source": null } ], "warnings": [ diff --git a/tests/DressCode/Rules/analyses.phpt b/tests/DressCode/Rules/analyses.phpt index 0f82b06167..1682f6c6ad 100644 --- a/tests/DressCode/Rules/analyses.phpt +++ b/tests/DressCode/Rules/analyses.phpt @@ -89,6 +89,7 @@ function collectAsked(array $methods, string $method, array $seen = []): array test('a rule names every analysis it or a static helper it calls asks for', function () { $methods = collectMethods(__DIR__ . '/../../../src/Rules'); $missing = []; + $asking = 0; foreach (require __DIR__ . '/rules.provider.php' as [, $rule]) { $prefix = strtolower("$rule::"); $asked = []; @@ -98,10 +99,12 @@ test('a rule names every analysis it or a static helper it calls asks for', func } } + $asking += $asked !== [] ? 1 : 0; foreach (array_diff(array_unique($asked), RuleInfo::fromRule($rule)->analyses) as $analysis) { $missing[] = "$rule asks for $analysis"; } } Assert::same([], $missing); + Assert::true($asking > 50, 'the rules asking for an analysis were not found'); }); diff --git a/tests/DressCode/Rules/fixtures/indentation/comments-before-continuation.code b/tests/DressCode/Rules/fixtures/indentation/comments-before-continuation.code index ef6254507f..01212df6e2 100644 --- a/tests/DressCode/Rules/fixtures/indentation/comments-before-continuation.code +++ b/tests/DressCode/Rules/fixtures/indentation/comments-before-continuation.code @@ -18,3 +18,26 @@ if ($a) { while ($a) { foo(); } + +try { + foo(); + // ends the try +} catch (Exception $e) { + bar(); + + // ends the catch + +} finally { + baz(); +} + +if ($a) { + foo(); + // ends the if +} elseif ($b) { + bar(); + // ends the elseif + // on two lines +} else { + baz(); +} diff --git a/tests/DressCode/Rules/fixtures/indentation/comments-before-continuation.expected b/tests/DressCode/Rules/fixtures/indentation/comments-before-continuation.expected index 3be122c638..f6227125db 100644 --- a/tests/DressCode/Rules/fixtures/indentation/comments-before-continuation.expected +++ b/tests/DressCode/Rules/fixtures/indentation/comments-before-continuation.expected @@ -18,3 +18,26 @@ if ($a) { while ($a) { foo(); } + +try { + foo(); + // ends the try +} catch (Exception $e) { + bar(); + + // ends the catch + +} finally { + baz(); +} + +if ($a) { + foo(); + // ends the if +} elseif ($b) { + bar(); + // ends the elseif + // on two lines +} else { + baz(); +} diff --git a/tests/DressCode/Rules/fixtures/multilineBinaryOperator/operator-position.code b/tests/DressCode/Rules/fixtures/multilineBinaryOperator/operator-position.code index 6d58b8d9c5..9b6ec8cf38 100644 --- a/tests/DressCode/Rules/fixtures/multilineBinaryOperator/operator-position.code +++ b/tests/DressCode/Rules/fixtures/multilineBinaryOperator/operator-position.code @@ -34,3 +34,7 @@ $a = $b + $c; $a = $someRatherLongVariableName->withAnotherLongPropertyName->andAThirdOneForGoodMeasure === $yetAnotherLongVariableName->withItsOwnProperty; +$r = match (true) { + $a || + $b => 1, +}; diff --git a/tests/DressCode/Rules/fixtures/multilineBinaryOperator/operator-position.expected b/tests/DressCode/Rules/fixtures/multilineBinaryOperator/operator-position.expected index 585ea53e80..59623f2c18 100644 --- a/tests/DressCode/Rules/fixtures/multilineBinaryOperator/operator-position.expected +++ b/tests/DressCode/Rules/fixtures/multilineBinaryOperator/operator-position.expected @@ -33,3 +33,7 @@ $a = $b + $c; $a = $someRatherLongVariableName->withAnotherLongPropertyName->andAThirdOneForGoodMeasure === $yetAnotherLongVariableName->withItsOwnProperty; +$r = match (true) { + $a + || $b => 1, +}; diff --git a/tests/DressCode/Rules/fixtures/multilineBinaryOperator/operator-position.violations b/tests/DressCode/Rules/fixtures/multilineBinaryOperator/operator-position.violations index b54fb9f59b..0ec23ba7c9 100644 --- a/tests/DressCode/Rules/fixtures/multilineBinaryOperator/operator-position.violations +++ b/tests/DressCode/Rules/fixtures/multilineBinaryOperator/operator-position.violations @@ -7,3 +7,4 @@ 22: Expected a line break before the `||` operator. 27: Expected a line break before the `??` operator. 30: Expected a line break before the `.` operator. +38: Expected a line break before the `||` operator. diff --git a/tests/DressCode/Rules/fixtures/unseenReferences/class-name-string.code b/tests/DressCode/Rules/fixtures/unseenReferences/class-name-string.code new file mode 100644 index 0000000000..b8d4425cff --- /dev/null +++ b/tests/DressCode/Rules/fixtures/unseenReferences/class-name-string.code @@ -0,0 +1,12 @@ +$method(); + $object->{$method . 'Async'}(); + $object->send(); + echo $object->$method; + echo $object->name; + $class::create(); + Factory::$method(); + Factory::create(); + new $class; + new Factory; + new class {}; + $callback(); + call_user_func($callback); + call_user_func('App\helper'); + \call_user_func_array([$object, $method], []); + helper(); +} diff --git a/tests/DressCode/Rules/fixtures/unseenReferences/dynamic-access.violations b/tests/DressCode/Rules/fixtures/unseenReferences/dynamic-access.violations new file mode 100644 index 0000000000..a14d5df4a5 --- /dev/null +++ b/tests/DressCode/Rules/fixtures/unseenReferences/dynamic-access.violations @@ -0,0 +1,9 @@ +8: A method called by a name the code computes, which no map of upgrading data sees. +9: A method called by a name the code computes, which no map of upgrading data sees. +11: A property read by a name the code computes, which no map of upgrading data sees. +13: A static method called by a name the code computes, which no map of upgrading data sees. +14: A static method called by a name the code computes, which no map of upgrading data sees. +16: A class instantiated by a name the code computes, which no map of upgrading data sees. +19: A function called by a name the code computes, which no map of upgrading data sees. +20: A function called by a name the code computes, which no map of upgrading data sees. +22: A function called by a name the code computes, which no map of upgrading data sees. diff --git a/tests/DressCode/Rules/fuzz-whitespace.phpt b/tests/DressCode/Rules/fuzz-whitespace.phpt index cff4690d23..600bc1e8c4 100644 --- a/tests/DressCode/Rules/fuzz-whitespace.phpt +++ b/tests/DressCode/Rules/fuzz-whitespace.phpt @@ -492,6 +492,7 @@ if ($only = getenv('DRESSCODE_FUZZ_ONLY')) { // every file is reported, so that one broken rule does not hide the rest $failures = []; +$damagedFiles = 0; foreach ($files as $file) { $where = substr($file, strrpos($file, '/corpus/') + 8); $fixed = $processor->process($file, (string) file_get_contents($file)); @@ -513,6 +514,7 @@ foreach ($files as $file) { candidateSpaces($tree), $randomizer, ); + $damagedFiles += $damaged !== $canonical ? 1 : 0; $what = "$where: the damage to lines " . implode(', ', $lines) . ' of its fixed form'; if (meaning($canonical) !== meaning($damaged)) { $failures[] = "$what changed the code.\nThe damage:\n" . excerpt(Diff::unified($canonical, $damaged, $where)); @@ -532,3 +534,4 @@ foreach ($files as $file) { } Assert::same([], $failures, "seed $seed"); +Assert::true($damagedFiles > count($files) / 2, "seed $seed: most files were left undamaged"); diff --git a/tests/DressCode/Rules/name-meaning.phpt b/tests/DressCode/Rules/name-meaning.phpt index ac35e0c375..7b9f9326f5 100644 --- a/tests/DressCode/Rules/name-meaning.phpt +++ b/tests/DressCode/Rules/name-meaning.phpt @@ -129,6 +129,7 @@ $worlds = [ // every file of every world is reported, so that one broken rule does not hide the rest $registry = new PluginRegistry; $failures = []; +$rewritten = 0; foreach ($worlds as $world => $symbols) { $processor = new PhpFileProcessor( $rules, @@ -145,6 +146,7 @@ foreach ($worlds as $world => $symbols) { continue; } + $rewritten += $result->output !== $code ? 1 : 0; $before = meanings($code, $symbols); $after = meanings($result->output, $symbols); if ($before !== $after) { @@ -155,3 +157,4 @@ foreach ($worlds as $world => $symbols) { } Assert::same([], $failures); +Assert::true($rewritten > 0, 'the rules rewrote no file, so no name was put to the test'); diff --git a/tests/DressCode/Rules/naming.phpt b/tests/DressCode/Rules/naming.phpt index ed30556c21..f96f7ae892 100644 --- a/tests/DressCode/Rules/naming.phpt +++ b/tests/DressCode/Rules/naming.phpt @@ -99,6 +99,7 @@ test('every name is built in the shape of its kind', function () use ($rules) { 'lineLength', // the example of a decision: the noun of the construct, the width its value 'redundantArguments', // says the state of the arguments it drops, which `hygiene.defaultArgument` names 'phpdocAboveAttributes', // says the state, in the words of the two constructs + 'unseenReferences', // names what it reports, the references an upgrade cannot see, which it never fixes ]; $outside = []; diff --git a/tests/DressCode/Testing/UpgradingTester.phpt b/tests/DressCode/Testing/UpgradingTester.phpt index 796cc05159..cca4670cd3 100644 --- a/tests/DressCode/Testing/UpgradingTester.phpt +++ b/tests/DressCode/Testing/UpgradingTester.phpt @@ -116,7 +116,10 @@ test('a file turns on only a requirement of the rules of its package, with a wor ['`since 3.0`: `upgrading.php.backticks`: An upgrading file turns on only a requirement of the rules of its package.'], $problems("\tupgrading.php.backticks: forbidden"), ); - Assert::match('%a%`acme.retired`%a%', $problems("\tacme.retired: forbidden")[0]); + Assert::match( + '`since 3.0`: Key `acme.retired` does not take `forbidden`; write `required`.', + $problems("\tacme.retired: forbidden")[0], + ); }); @@ -244,16 +247,43 @@ test('a key under extra.dresscode that DressCode does not read is a problem', fu $file = "package: acme/lib\n\nsince 3.0:\n\treplacedClasses:\n\t\tAcme\\Lib\\IControl: Acme\\Lib\\Control\n"; Assert::same( [], - check($file, '{"name": "acme/rules", "extra": {"dresscode": {"upgrading-dir": "upgrading", "plugin": "Acme\\\\Rules"}}}'), + check( + $file, + '{"name": "acme/rules", "extra": {"dresscode": {"upgrading-dir": "upgrading", "packages": ["acme/lib"], "plugin": "Acme\\\\Rules"}}}', + ), ); Assert::same([], check($file, '{"name": "acme/rules", "extra": {"branch-alias": {}}}')); Assert::same( - ['Package `acme/rules`: `extra.dresscode` in its `composer.json` holds the key `upgrades`, which DressCode does not know; it reads `upgrading-dir`, `plugin`.'], + ['Package `acme/rules`: `extra.dresscode` in its `composer.json` holds the key `upgrades`, which DressCode does not know; it reads `upgrading-dir`, `packages`, `plugin`.'], check($file, '{"name": "acme/rules", "extra": {"dresscode": {"upgrading-dir": "upgrading", "upgrades": []}}}'), ); }); +test('the packages a package lists are exactly those its upgrading files are about', function () { + $root = createTempDir('upgrading-packages'); + FileSystem::write("$root/upgrading/lib.neon", "package: acme/lib\n"); + FileSystem::write("$root/upgrading/tools.neon", "package: acme/tools\n"); + $problems = function (string $packages) use ($root): array { + FileSystem::write( + "$root/composer.json", + '{"name": "acme/rules", "extra": {"dresscode": {"upgrading-dir": "upgrading", "packages": ' . $packages . '}}}', + ); + return UpgradingTester::collectPackageProblems($root); + }; + + Assert::same([], $problems('["acme/lib", "acme/tools"]')); + Assert::same([], $problems('["acme/"]')); + Assert::same( + [ + 'Package `acme/rules`: `extra.dresscode.packages` in its `composer.json` does not list `acme/tools`, which `upgrading/tools.neon` is about.', + 'Package `acme/rules`: `extra.dresscode.packages` in its `composer.json` lists `acme/gone`, which no upgrading file is about.', + ], + $problems('["acme/lib", "acme/gone"]'), + ); +}); + + test('a forbidden map of a package must give every entry a sentence', function () { $problems = check(<<<'XX' package: acme/lib @@ -373,6 +403,11 @@ test('a sample reads its classes from its own code, not from those of a sample r namespace App { class Job implements \Acme\Lib\Control {} + + function run(Job $job): mixed + { + return $job->limit; + } } XX; $own = <<<'XX' @@ -391,12 +426,16 @@ test('a sample reads its classes from its own code, not from those of a sample r } } XX; - $run = fn(string $code, string $name) => UpgradingTester::runSample($code, $root, name: $name)->violations; + $run = fn(string $code, string $name) => array_map( + fn($violation) => $violation->message, + UpgradingTester::runSample($code, $root, name: $name)->violations, + ); + $reported = ['Property `Acme\Lib\Control::$limit` is removed: there is no replacement, since acme/lib 3.0.']; // the class of the sample implements nothing, whichever sample ran before - $run($implementing, 'a'); + Assert::same($reported, $run($implementing, 'a')); Assert::same([], $run($own, 'b')); - $run($implementing, 'c'); + Assert::same($reported, $run($implementing, 'c')); Assert::same([], $run($own, 'b')); Assert::same([], glob("$root/temp/*")); }); diff --git a/tests/DressCode/Upgrade/Composer.phpt b/tests/DressCode/Upgrade/Composer.phpt new file mode 100644 index 0000000000..818529be74 --- /dev/null +++ b/tests/DressCode/Upgrade/Composer.phpt @@ -0,0 +1,131 @@ += 8.2) + latte/latte v3.1.6 requires php (8.2 - 8.5) + nette/application v3.3.0 requires php (8.3 - 8.5) + acme/legacy v1.0.0 conflicts php (>=8.4) + Not finding what you were looking for? Try calling `composer require "php:8.6" --dry-run` to get another view on the problem. + XX; + + $blockers = Composer::parseBlockers(Target::php('8.6'), $output, 'acme/shop'); + Assert::equal(Target::php('8.6'), $blockers->target); + Assert::equal( + [ + new Blocker('latte/latte', 'v3.1.6', '8.2 - 8.5'), + new Blocker('nette/application', 'v3.3.0', '8.3 - 8.5'), + new Blocker('acme/legacy', 'v1.0.0', 'conflicts with php >=8.4'), + ], + $blockers->packages, + ); +}); + + +test('the target itself refusing the PHP Composer runs on refuses no target', function () { + $output = <<<'XX' + acme/shop dev-master requires acme/mail (^3.2) + acme/mail v4.0.0 requires php (>=8.0 <8.3 but 8.5.12 is installed) + XX; + + Assert::same([], Composer::parseBlockers(new Target('acme/mail', '4.0'), $output, 'acme/shop')->packages); +}); + + +test('the operations of an update are read once, though Composer lists them for the lock and for the installation', function () { + $output = <<<'XX' + ./composer.json has been updated + Lock file operations: 0 installs, 1 update, 0 removals + - Upgrading nette/utils (v3.2.10 => v4.0.11) + Installing dependencies from lock file (including require-dev) + Package operations: 0 installs, 1 update, 0 removals + - Upgrading nette/utils (v3.2.10 => v4.0.11) + XX; + + Assert::same(['- Upgrading nette/utils (v3.2.10 => v4.0.11)'], Composer::parseOperations($output)); +}); + + +test('the moves of an update are read from its upgrades and downgrades, not from what it installs or removes', function () { + $output = <<<'XX' + Lock file operations: 1 install, 2 updates, 1 removal + - Removing acme/old (v1.0.0) + - Upgrading nette/utils (v3.2.10 => v4.0.11) + - Downgrading acme/mail (v2.1.0 => v2.0.3) + - Installing acme/new (v1.2.0) + XX; + + Assert::equal( + [new Move('nette/utils', 'v3.2.10', 'v4.0.11'), new Move('acme/mail', 'v2.1.0', 'v2.0.3')], + Composer::parseMoves(Composer::parseOperations($output)), + ); +}); + + +test('a Composer that fails says why, with the last line it wrote', function () { + putenv('COMPOSER_BINARY=dresscode-no-such-composer'); + try { + $root = createTempDir('composer-failed'); + file_put_contents("$root/composer.json", '{"require": {"acme/mail": "^3.0"}}'); + $composer = new Composer($root); + Assert::exception( + fn() => $composer->previewRequire(['acme/mail' => '^4.0']), + ComposerException::class, + 'Composer failed: %a%', + ); + Assert::match('Composer failed: %a%', (string) $composer->findMoves(['acme/mail' => '^4.0'])->unknown); + + // a Composer ending with a negative code, as a crash on Windows does + file_put_contents("$root/composer.php", " $composer->previewRequire(['acme/mail' => '^4.0']), + ComposerException::class, + 'Composer failed: Out of memory%a?%', + ); + } finally { + putenv('COMPOSER_BINARY'); + } +}); + + +test('the dry run of a raise is of a copy of composer.json with the platform raised, which it leaves nowhere', function () { + $root = createTempDir('composer-preview'); + file_put_contents("$root/composer.json", '{"require": {"php": "^8.0"}}'); + // a Composer that tells the arguments and the platform of the file it is given + file_put_contents("$root/composer.php", <<<'XX' + ' . ($data['config']['platform']['php'] ?? 'none') . ")\n"; + XX); + putenv("COMPOSER_BINARY=$root/composer.php"); + try { + $composer = new Composer($root); + Assert::same(['- Upgrading acme/args (update --lock --dry-run => 8.4)'], $composer->previewRequire([], platform: '8.4')); + Assert::same(['- Upgrading acme/args (require php:^8.4 -W => 8.4)'], $composer->previewRequire(['php' => '^8.4'], platform: '8.4')); + Assert::same(['composer.json', 'composer.php'], array_values(array_diff(scandir($root), ['.', '..']))); + } finally { + putenv('COMPOSER_BINARY'); + } +}); + + +test('nothing refuses a version where why-not says no installed package depends on it otherwise', function () { + $output = 'There is no installed package depending on "php" in versions not matching 8.5'; + $blockers = Composer::parseBlockers(Target::php('8.5'), $output, null); + Assert::same([], $blockers->packages); + Assert::null($blockers->unknown); +}); + + +test('an output that is no answer of why-not leaves what refuses the version unknown', function () { + $blockers = Composer::parseBlockers(Target::php('8.5'), "Could not open input file: composer.phar\n", null); + Assert::same([], $blockers->packages); + Assert::same('Composer gave no answer: Could not open input file: composer.phar', $blockers->unknown); +}); diff --git a/tests/DressCode/Upgrade/Estimator.phpt b/tests/DressCode/Upgrade/Estimator.phpt new file mode 100644 index 0000000000..445bd8123b --- /dev/null +++ b/tests/DressCode/Upgrade/Estimator.phpt @@ -0,0 +1,153 @@ + every topic as `name set phase constraint files: automatic types names manual` */ +function describeTopics(Estimate $estimate): array +{ + return array_map( + fn(Topic $topic) => "$topic->name $topic->set {$topic->phase->value} " . ($topic->constraint ?? '-') + . " $topic->files: " . implode(' ', $topic->places), + $estimate->topics, + ); +} + + +test('the places are told by topic, by phase and by what the run can do about them, the jump first', function () { + $root = createEstimatedProject('estimate'); + file_put_contents( + "$root/src/Dynamic.php", + "\$method();\n}\n", + ); + file_put_contents("$root/src/Generated.php", "estimate([Target::php('8.4')]); + + // curl_close() does nothing since 8.0 already, strftime() has no replacement, `0o` needs 8.1, `?int` works on 8.0 + Assert::same([ + 'php deprecations jump ^8.4 1: 0 0 0 1', + 'upgrading.syntax.octalPrefix modernizations jump ^8.4 1: 1 0 0 0', + 'php deprecations bridge ^8.0 1: 1 0 0 0', + 'upgrading.functions.substringFunctions modernizations bridge ^8.0 1: 1 0 0 0', + 'upgrading.php.implicitNullable deprecations bridge ^8.0 1: 1 0 0 0', + ], describeTopics($estimate)); + Assert::same(2, $estimate->files); + // what the upgrade cannot see is counted apart from the topics, and a generated file is left out + Assert::equal(new BlindSpots(dynamicAccesses: 1, otherFiles: ['latte' => 1], generatedFiles: 1), $estimate->blindSpots); + Assert::true($estimate->namesMeasured); + Assert::false($estimate->types); + Assert::same(['php' => '8.6'], $estimate->knownVersions); + // without a lock nothing is asked of Composer + Assert::same([], $estimate->blockers); +}); + + +test('where the configuration says the names are uncertain, a fix of a call of a function waits for them', function () { + $root = createEstimatedProject('estimate-uncertain'); + $config = new Config(paths: ['src'], nameResolution: 'uncertain'); + $estimate = new Estimator(new Project($config, $root))->estimate([Target::php('8.4')]); + + Assert::false($estimate->namesMeasured); + Assert::contains('php deprecations bridge ^8.0 1: 0 0 1 0', describeTopics($estimate)); + Assert::contains('upgrading.functions.substringFunctions modernizations bridge ^8.0 1: 0 0 1 0', describeTopics($estimate)); +}); + + +test('without a target the rules and the data of a newer PHP stay off, and the project stays as it was', function () { + $root = createEstimatedProject('estimate-today'); + $before = hash_file('xxh128', "$root/src/Code.php"); + $estimate = new Estimator(new Project(new Config(paths: ['src']), $root))->estimate([]); + + // what PHP 8.1 retires, `strftime()`, says nothing to code that runs on 8.0, so there is no jump + Assert::same([], $estimate->findTopics(Phase::Jump)); + Assert::same($before, hash_file('xxh128', "$root/src/Code.php")); + Assert::notContains('Upgrading to PHP 8.0 is not covered; fixes of PHP 8 constructs stay off for 7.x.', $estimate->warnings); + + // a project on PHP 7 is told that its move to PHP 8 is no upgrade + file_put_contents("$root/composer.json", '{"require": {"php": "^7.4"}}'); + $estimate = new Estimator(new Project(new Config(paths: ['src']), $root))->estimate([]); + Assert::contains('Upgrading to PHP 8.0 is not covered; fixes of PHP 8 constructs stay off for 7.x.', $estimate->warnings); +}); + + + +test('the targets proposed are PHP and every library whose data know a newer version than the project allows', function () { + $root = createEstimatedProject('estimate-targets'); + $estimator = new Estimator(new Project(new Config(paths: ['src']), $root)); + + Assert::equal([Target::php('8.6')], $estimator->proposeTargets()); + Assert::equal([Target::php('8.6')], $estimator->proposeTargets(phpOnly: true)); + + // a project on PHP 7 is offered no move to PHP 8 + file_put_contents("$root/composer.json", '{"require": {"php": "^7.4"}}'); + Assert::same([], $estimator->proposeTargets()); +}); + + +test('a decision only the data of the target version turn on belongs to the jump, as nothing runs it today', function () { + require_once __DIR__ . '/../Console/fixtures/upgrade-plugin.php'; + $root = createTempDir('estimate-data-jump'); + mkdir("$root/src"); + file_put_contents("$root/composer.json", '{"require": {"php": ">=8.2", "acme/upgrade": "^1.0"}}'); + file_put_contents("$root/src/a.php", " [[ + 'name' => 'acme/upgrade', + 'version' => '1.0.0', + 'version_normalized' => '1.0.0.0', + 'install-path' => '../acme/upgrade', + 'extra' => ['dresscode' => ['plugin' => 'UpgradePlugin', 'upgrading-dir' => 'upgrading']], + ]]], JSON_THROW_ON_ERROR)); + + $estimate = new Estimator(new Project(new Config(paths: ['src']), $root))->estimate([new Target('acme/upgrade', '2.0')]); + // the rule does not say which entry it reports, and the map is filled by the data of that library alone + Assert::same(['acme/upgrade deprecations jump ^2.0 1: 0 0 0 1'], describeTopics($estimate)); +}); + + +test('the check a worker repeats is read back from its file, the scope of a project without a configuration file with it', function () { + $file = createTempDir('estimate-run') . '/run.json'; + $run = new UpgradeCheck( + new Config(use: ['deprecations']), + ['php'], + ['deprecations'], + new Config(paths: ['src'], excludePaths: ['src/Gen']), + ); + $run->write($file); + Assert::equal($run->toArray(), UpgradeCheck::read($file)->toArray()); + Assert::same(['src'], UpgradeCheck::read($file)->scope?->paths); +}); diff --git a/tests/DressCode/Upgrade/Git.phpt b/tests/DressCode/Upgrade/Git.phpt new file mode 100644 index 0000000000..583a89fadc --- /dev/null +++ b/tests/DressCode/Upgrade/Git.phpt @@ -0,0 +1,42 @@ + str_replace("\r", '', ProcessRunner::run(['git', ...array_values($args)], $repository, 60)[1]); + $git('init', '--quiet'); + $git('add', '--all'); + $git('-c', 'user.name=Test', '-c', 'user.email=test@example.com', 'commit', '--quiet', '-m', 'start'); + file_put_contents("$repository/pkg/src/A.php", "after\r\n"); + file_put_contents("$repository/pkg/src/B.php", 'mine'); + file_put_contents("$repository/composer.json", 'after'); + + putenv('GIT_AUTHOR_NAME=Test'); + putenv('GIT_COMMITTER_NAME=Test'); + putenv('GIT_AUTHOR_EMAIL=test@example.com'); + putenv('GIT_COMMITTER_EMAIL=test@example.com'); + $project = new Git("$repository/pkg"); + Assert::same(['src/A.php', '../composer.json'], $project->listUnignored(['src/A.php', '../composer.json', 'src/C.php'])); + $project->commit(['src/A.php' => "after\r\n", '../composer.json' => 'after'], 'subject', 'body'); + + Assert::same(".gitattributes\ncomposer.json\npkg/src/A.php\npkg/src/B.php\n", $git('ls-tree', '-r', '--name-only', 'HEAD')); + // the text is cleaned by the attributes of its path in the repository + Assert::same(["after\n", 'after', 'before'], [ + $git('show', 'HEAD:pkg/src/A.php'), + $git('show', 'HEAD:composer.json'), + $git('show', 'HEAD:pkg/src/B.php'), + ]); + // the index takes the files committed as they are, and the change of the other one stays the user's own + Assert::same(" M pkg/src/B.php\n", $git('status', '--porcelain')); +}); diff --git a/tests/DressCode/Upgrade/Move.phpt b/tests/DressCode/Upgrade/Move.phpt new file mode 100644 index 0000000000..764c4513aa --- /dev/null +++ b/tests/DressCode/Upgrade/Move.phpt @@ -0,0 +1,28 @@ +isMajor()); + Assert::true(new Move('acme/mail', '4.0.0', '3.9.0')->isMajor()); + Assert::true(new Move('acme/beta', '0.3.1', '0.4.0')->isMajor()); + Assert::false(new Move('nette/utils', 'v4.0.1', 'v4.1.0')->isMajor()); + Assert::false(new Move('acme/beta', '0.3.1', '0.3.7')->isMajor()); +}); + + +test('the data know a move when they reach the minor version it moves to, its major version alone being less', function () { + $known = ['nette/utils' => '4.1', 'acme/beta' => '0.3']; + Assert::true(new Move('nette/utils', 'v3.2.10', 'v4.0.11')->isKnown($known)); + Assert::true(new Move('nette/utils', 'v3.2.10', 'v4.1.5')->isKnown($known)); + Assert::false(new Move('nette/utils', 'v4.0.1', 'v4.9.0')->isKnown($known)); + Assert::true(new Move('nette/utils', 'v4.0.1', 'v4.9.0')->isSeriesKnown($known)); + Assert::false(new Move('nette/utils', 'v4.1.0', 'v5.0.0')->isKnown($known)); + Assert::false(new Move('nette/utils', 'v4.1.0', 'v5.0.0')->isSeriesKnown($known)); + Assert::false(new Move('acme/beta', '0.3.1', '0.4.0')->isSeriesKnown($known)); + Assert::false(new Move('acme/mail', 'v2.0.0', 'v3.0.0')->isSeriesKnown($known)); +}); diff --git a/tests/DressCode/Upgrade/Plan.phpt b/tests/DressCode/Upgrade/Plan.phpt new file mode 100644 index 0000000000..eb445996fd --- /dev/null +++ b/tests/DressCode/Upgrade/Plan.phpt @@ -0,0 +1,295 @@ + $blockers */ +function createPlanEstimate(bool $library = false, ?array $blockers = null): Estimate +{ + $topic = fn(string $name, string $set, Phase $phase) => new Topic($name, $set, $phase, 1, ['automatic' => 1]); + return new Estimate( + [Target::php('8.4'), new Target('acme/mail', '3.0')], + [ + $topic('php', 'deprecations', Phase::Jump), + $topic('acme/mail', 'deprecations', Phase::Jump), + $topic('upgrading.syntax.octalPrefix', 'modernizations', Phase::Jump), + $topic('php', 'deprecations', Phase::Bridge), + $topic('hygiene.uselessVersionCheck', 'cleanup', Phase::Jump), + ], + 1, + new BlindSpots, + $blockers ?? [new Blockers(new Target('acme/mail', '3.0'), [new Blocker('acme/shop', 'v1.0.0', '^2.0')])], + [], + [], + true, + false, + [], + library: $library, + ); +} + + +test('the steps go from what a human makes way for, through the bridge and the raise, to the jump and what is left', function () { + $project = new ProjectPackages(required: ['php' => '>=8.1', 'acme/mail' => '^2.4']); + $plan = new PlanBuilder($project)->build(createPlanEstimate(), 'vendor/bin/tester tests -o junit:{junit}'); + + Assert::equal([ + new ManualStep('make way for acme/mail 3.0: acme/shop', new Target('acme/mail', '3.0')), + new FixStep('works on the versions allowed today', ['php']), + // each constraint raised in the shape the project writes it + new ComposerStep('raise php to >=8.4, acme/mail to ^3.0', ['php' => '>=8.4', 'acme/mail' => '^3.0']), + new FixStep('needs the targets', ['php', 'acme/mail']), + new FixStep('code for the versions given up', ['hygiene.uselessVersionCheck']), + // the raise installs the lowest versions, which the application then updates, tested as every step + new UpdateStep('update to the newest versions'), + // what a newer PHP offers waits until the user takes it in + new FixStep('what the targets offer', ['upgrading.syntax.octalPrefix'], skip: true), + ], $plan->steps); + Assert::same( + [ + 1 => ManualStep::class, + 2 => FixStep::class, + 3 => ComposerStep::class, + 4 => FixStep::class, + 5 => FixStep::class, + 6 => UpdateStep::class, + ], + array_map(fn(Step $step) => $step::class, $plan->findSteps()), + ); + Assert::same('vendor/bin/tester tests -o junit:{junit}', $plan->testCommand); +}); + + +test('a tilde keeps its precision, and an upper bound of its own the target passes is said', function () { + $project = new ProjectPackages(required: ['php' => '~8.1.0', 'acme/mail' => '>=2.4 <3.0']); + $plan = new PlanBuilder($project)->build(createPlanEstimate()); + Assert::equal( + new ComposerStep('raise php to ~8.4.0, acme/mail to ^3.0 past its upper bound <3.0', ['php' => '~8.4.0', 'acme/mail' => '^3.0']), + $plan->steps[2], + ); +}); + + +test('an estimate is complete once it processed every file, had the upgrading data and Composer told what refuses', function () { + Assert::true(createPlanEstimate()->isComplete()); + Assert::false(createPlanEstimate(blockers: [new Blockers(new Target('acme/mail', '3.0'), unknown: 'Composer failed')])->isComplete()); +}); + + +test('a target Composer could not tell what refuses is a step for a human all the same', function () { + $project = new ProjectPackages(required: ['php' => '>=8.1', 'acme/mail' => '^2.4']); + $plan = new PlanBuilder($project)->build(createPlanEstimate( + blockers: [new Blockers(new Target('acme/mail', '3.0'), unknown: 'Composer failed')], + )); + Assert::equal( + new ManualStep('make way for acme/mail 3.0, which Composer could not tell', new Target('acme/mail', '3.0')), + $plan->steps[0], + ); +}); + + +test('a constraint is raised by its lower bound, its upper bound kept and a part the target is past dropped', function () { + foreach ([ + ['>=8.1', '>=8.4'], + ['^8.1', '^8.4'], + ['8.1', '^8.4'], + ['>=8.1 <8.5', '>=8.4 <8.5'], + ['>=8.1, <8.5', '>=8.4, <8.5'], + ['^8.1 <8.5', '^8.4 <8.5'], + ['^7.4 || ^8.0', '^8.4'], + ['^8.0 || ^9.0', '^8.4 || ^9.0'], + ['~8.1.0', '~8.4.0'], + ['>=8.1 <8.4', '^8.4'], + ['', '^8.4'], + // an operator apart from its version, and a range of a hyphen + ['>= 8.1 < 8.5', '>=8.4 <8.5'], + ['8.1 - 8.5', '8.4 - 8.5'], + ['^7.4 || 8.1 - 8.5', '8.4 - 8.5'], + ['8.1 - 8.3', '^8.4'], + ] as [$constraint, $raised]) { + Assert::same($raised, Constraints::raiseConstraint($constraint, '8.4'), $constraint); + } + + Assert::same('8.3', Constraints::findPassedUpperBound('8.1 - 8.3', '8.4')); +}); + + +test('a platform of PHP below the target is raised with the constraint, which the file of the plan keeps', function () { + $root = createTempDir('plan-platform'); + file_put_contents("$root/composer.json", '{"require": {"php": ">=8.1", "acme/mail": "^2.4"}, "config": {"platform": {"php": "8.1"}}}'); + $plan = new PlanBuilder(ProjectPackages::read($root))->build(createPlanEstimate()); + Assert::equal( + new ComposerStep( + 'raise php to >=8.4, acme/mail to ^3.0, config.platform.php to 8.4', + ['php' => '>=8.4', 'acme/mail' => '^3.0'], + platform: '8.4', + ), + $plan->steps[2], + ); + + PlanFile::write($plan, $root); + Assert::equal($plan->steps, PlanFile::read($root)->steps); + + // a platform below the target is raised where composer.json requires the target already, the step done once it is + file_put_contents("$root/composer.json", '{"require": {"php": "^8.4", "acme/mail": "^3.0"}, "config": {"platform": {"php": "8.0"}}}'); + $plan = new PlanBuilder(ProjectPackages::read($root))->build(createPlanEstimate()); + $step = new ComposerStep('raise config.platform.php to 8.4', [], platform: '8.4'); + Assert::equal($step, $plan->steps[2]); + Assert::same(['composer config platform.php 8.4', 'composer update --lock'], $step->formatCommands()); + Assert::false($step->isDoneIn(ProjectPackages::read($root))); + file_put_contents("$root/composer.json", '{"require": {"php": "^8.4", "acme/mail": "^3.0"}, "config": {"platform": {"php": "8.4"}}}'); + Assert::true($step->isDoneIn(ProjectPackages::read($root))); + + PlanFile::write($plan, $root); + Assert::equal($plan->steps, PlanFile::read($root)->steps); +}); + + +test('a target the lowest version allowed today already reaches raises nothing', function () { + $project = new ProjectPackages(required: ['php' => '^8.4', 'acme/mail' => '^3.1']); + $plan = new PlanBuilder($project)->build(createPlanEstimate()); + Assert::false(array_any($plan->steps, fn(Step $step) => $step instanceof ComposerStep)); +}); + + +test('the first raise of a lower bound the project has not made is due, a widening or the platform alone never', function () { + $today = new ProjectPackages(required: ['php' => '>=8.1', 'acme/mail' => '^2.4']); + Assert::same(3, new PlanBuilder($today)->build(createPlanEstimate())->findDueRaise($today)); + Assert::null(new PlanBuilder($today)->build(createPlanEstimate(library: true))->findDueRaise($today)); + + $plan = new Plan([Target::php('8.4')], [ + new ComposerStep('raise config.platform.php to 8.4', [], platform: '8.4'), + new FixStep('needs the targets', ['php']), + new ComposerStep('raise php to ^8.4', ['php' => '^8.4']), + ], '1.0'); + Assert::same(3, $plan->findDueRaise($today)); + Assert::null($plan->findDueRaise(new ProjectPackages(required: ['php' => '^8.4']))); + $skipped = new Plan([Target::php('8.4')], [new ComposerStep('raise php to ^8.4', ['php' => '^8.4'], skip: true)], '1.0'); + Assert::null($skipped->findDueRaise($today)); +}); + + +test('the file of the plan gives back the plan it was written from', function () { + $root = createTempDir('plan-file'); + $plan = new PlanBuilder(new ProjectPackages(required: ['php' => '^8.1'])) + ->build(createPlanEstimate(), 'composer test -- {junit}', 'composer quick -- {junit}'); + PlanFile::write($plan, $root); + Assert::equal($plan, PlanFile::read($root)); + + // what the estimate could not see goes with the plan, so that a run of it says so + $plan = new Plan( + [Target::php('8.4')], + [new FixStep('fix', ['php'])], + '1.0', + unestimated: ['src/Broken.php'], + missingData: ['dresscode/upgrade-acme' => ['acme/mail']], + ); + PlanFile::write($plan, $root); + Assert::equal($plan, PlanFile::read($root)); +}); + + +test('the file of the plan is read as the team writes it, and one that is no plan is refused', function () { + $root = createTempDir('plan-edited'); + file_put_contents("$root/" . PlanFile::Name, <<<'XX' + version: 1 + targets: {php: '8.4', acme/mail: '3.0'} + tests: {command: 'vendor/bin/phpunit --log-junit {junit}'} + steps: + - {kind: manual, title: make way, target: acme/mail} + - {kind: fix, topics: [php]} + - {kind: composer, title: raise, require: {php: ^8.4}, skip: true} + XX); + Assert::equal( + new Plan( + [Target::php('8.4'), new Target('acme/mail', '3.0')], + [ + new ManualStep('make way', new Target('acme/mail', '3.0')), + new FixStep('fix', ['php']), + new ComposerStep('raise', ['php' => '^8.4'], skip: true), + ], + '', + testCommand: 'vendor/bin/phpunit --log-junit {junit}', + ), + PlanFile::read($root), + ); + + foreach ([ + "version: 1\nsteps: []\n" => '`targets` and `steps` are expected', + "targets: {php: '8.4'}\n" => '`version: 1` is expected, the plan of another version of DressCode is made anew', + "version: 1\ntarget: {php: '8.4'}\n" => '`target` is no key of a plan', + "version: 1\ntargets: {php: 8.4}\nsteps: []\n" => "`targets` must be a map of strings, a version quoted as `'8.4'`", + "version: 1\ntargets: {php: '8.4'}\nsteps:\n\t- {title: who knows}\n" => '`steps.1` must give its `kind`, `fix`, `composer`, `update` or `manual`', + "version: 1\ntargets: {php: '8.4'}\nsteps:\n\t- {kind: fix, topic: [php]}\n" => '`steps.1.topic` is no key of a step of the kind `fix`', + "version: 1\ntargets: {php: '8.4'}\nsteps:\n\t- {kind: fix, topics: [php], skip: falsee}\n" => '`steps.1.skip` must be `true` or `false`', + "version: 1\ntargets: {php: '8.4'}\nsteps:\n\t- {kind: fix}\n" => '`steps.1.topics` must name the topics the step fixes', + "version: 1\ntargets: {php: '8.4'}\nsteps:\n\t- {kind: composer}\n" => '`steps.1.require` must give the constraints the step writes, or the step its `platform`', + "version: 1\ntargets: {nonsense: '8.4'}\nsteps: []\n" => '`targets.nonsense` must be `php` or a package as `vendor/name`', + "version: 1\ntargets: {php: '8.4'}\nsteps:\n\t- {kind: composer, require: {garbage: ^1.0}}\n" + => '`steps.1.require.garbage` must be `php` or a package as `vendor/name`', + "version: 1\ntargets: {php: '8.4'}\nsteps:\n\t- {kind: composer, require: {php: no-constraint}}\n" + => '`steps.1.require.php` must be a constraint Composer reads, as `^8.4`', + "version: 1\ntargets: {php: '8.4'}\nsteps:\n\t- {kind: manual, target: acme/mail}\n" => '`steps.1.target` must name a package of `targets`', + "version: 1\ntargets: {php: '8.4'}\ntests: {quick: vendor/bin/phpunit}\nsteps:\n\t- {kind: fix, topics: [php]}\n" + => '`tests.quick` must be a command writing its JUnit report where `{junit}` stands', + "version: 1\ntargets: {php: '8.4'}\nestimate: {files: []}\nsteps:\n\t- {kind: fix, topics: [php]}\n" + => '`estimate.files` is no key of `estimate`, which takes `unprocessed` and `missingData`', + "version: 1\ntargets: {php: '8.4'}\nestimate: {missingData: {acme/x: acme/y}}\nsteps:\n\t- {kind: fix, topics: [php]}\n" + => '`estimate.missingData.acme/x` must be a list of strings', + "version: 1\ntargets: {php: '8.4'}\nestimate: {missingData: [acme/y]}\nsteps:\n\t- {kind: fix, topics: [php]}\n" + => '`estimate.missingData.0` must be a list of strings', + ] as $text => $message) { + file_put_contents("$root/" . PlanFile::Name, $text); + Assert::exception(fn() => PlanFile::read($root), DressCode\ConfigurationException::class, "The plan `%a%`: $message."); + } +}); + + +test('a library keeps the versions it allows: the bridge and the constraints widened to the targets', function () { + $project = new ProjectPackages(required: ['php' => '>=8.1', 'acme/mail' => '^2.4']); + $plan = new PlanBuilder($project)->build(createPlanEstimate(library: true)); + + Assert::equal([ + new ManualStep('make way for acme/mail 3.0: acme/shop', new Target('acme/mail', '3.0')), + new FixStep('works on the versions allowed today', ['php']), + new ComposerStep('widen acme/mail to ^2.4 || ^3.0', ['acme/mail' => '^2.4 || ^3.0'], update: false), + ], $plan->steps); +}); + + +test( + 'a library says so by its type, none being one as Composer reads it, and has no lock of its own, one with a lock its git does not ignore maybe being one', + function () { + $root = createTempDir('plan-library'); + file_put_contents("$root/composer.json", '{"type": "library"}'); + Assert::same(Tristate::Yes, ProjectPackages::read($root)->isLibrary()); + file_put_contents("$root/composer.lock", '{}'); + Assert::same(Tristate::Maybe, ProjectPackages::read($root)->isLibrary()); + file_put_contents("$root/composer.json", '{}'); + Assert::same(Tristate::Maybe, ProjectPackages::read($root)->isLibrary()); + unlink("$root/composer.lock"); + $untyped = ProjectPackages::read($root); + Assert::same([Tristate::Yes, 'library'], [$untyped->isLibrary(), $untyped->findType()]); + file_put_contents("$root/composer.json", '{"type": "project"}'); + Assert::same(Tristate::No, ProjectPackages::read($root)->isLibrary()); + + // the lock an install of a library leaves, which its git ignores, unless git ignores the whole project + file_put_contents("$root/composer.json", '{}'); + file_put_contents("$root/composer.lock", '{}'); + ProcessRunner::run(['git', 'init', '-q'], $root, 60); + Assert::same(Tristate::Maybe, ProjectPackages::read($root)->isLibrary()); + file_put_contents("$root/.gitignore", "composer.lock\n"); + Assert::same(Tristate::Yes, ProjectPackages::read($root)->isLibrary()); + file_put_contents("$root/.gitignore", "*\n"); + Assert::same(Tristate::Maybe, ProjectPackages::read($root)->isLibrary()); + }, +); diff --git a/tests/DressCode/Upgrade/PlanRunner.phpt b/tests/DressCode/Upgrade/PlanRunner.phpt new file mode 100644 index 0000000000..9997defc3a --- /dev/null +++ b/tests/DressCode/Upgrade/PlanRunner.phpt @@ -0,0 +1,975 @@ +' : '>') . ''); + XX); + return $root; +} + + +function createSteppedRunProject(string $root): Project +{ + return new Project(Config\Loader::loadFile("$root/dresscode.neon"), $root, "$root/dresscode.neon"); +} + + +/** Composer as a test scripts it: a raise writes its constraints into `composer.json`, an update changes what it is given until it ran. */ +final class PlanRunnerComposer implements PackageManager +{ + public int $updates = 0; + + + public function __construct( + private string $root, + /** @var ?Closure(array): void what a raise does instead */ + private ?Closure $onRequire = null, + /** @var list what an update changes, until it ran */ + private array $updateChanges = [], + /** @var ?Closure(): void what an install does */ + private ?Closure $onInstall = null, + ) { + } + + + public function findBlockers(Target $target): Blockers + { + return new Blockers($target, unknown: 'not asked'); + } + + + public function previewRequire(array $constraints, bool $update = true, ?string $platform = null): array + { + return []; + } + + + public function require(array $constraints, bool $update = true, ?string $platform = null): void + { + $this->onRequire === null + ? file_put_contents("$this->root/composer.json", json_encode(['require' => $constraints], JSON_THROW_ON_ERROR)) + : ($this->onRequire)($constraints); + } + + + public function previewUpdate(): array + { + return $this->updates === 0 ? $this->updateChanges : []; + } + + + public function update(): void + { + $this->updates++; + } + + + public function install(): void + { + $this->onInstall?->__invoke(); + } +} + + +function createSteppedPlan(?string $testCommand = null): Plan +{ + return new Plan( + [Target::php('8.4')], + [ + new FixStep('works on the versions allowed today', ['upgrading.php.implicitNullable']), + new ComposerStep('raise php to ^8.4', ['php' => '^8.4']), + ], + '1.0', + testCommand: $testCommand, + ); +} + + +test('the results of the tests are read from JUnit as PHPUnit and Nette Tester write it, a test by its class and name', function () { + $results = TestResults::fromJunit(<<<'XX' + + + + broken + + + + XX, 'W:/acme') ?? throw new RuntimeException; + + Assert::same([ + 'App.Tests.MailTest::testSend with data set #0' => TestStatus::Passed, + 'App/Tests/MailTest::testQueue' => TestStatus::Failed, + 'tests/Mail.phpt::W:/acme/tests/Mail.phpt' => TestStatus::Error, + ], $results->tests); + // what failed before, or passes now, is no new failure + Assert::same( + ['tests/Mail.phpt::W:/acme/tests/Mail.phpt (error)'], + $results->findNewFailures(new TestResults(['App/Tests/MailTest::testQueue' => TestStatus::Failed])), + ); + + // the results a run keeps are read back as they were written, those of another shape not at all + $file = createTempDir('test-results') . '/results.json'; + $results->save($file); + Assert::same($results->tests, TestResults::fromFile($file)?->tests); + file_put_contents($file, '{"A::one": true}'); + Assert::null(TestResults::fromFile($file)); + Assert::null(TestResults::fromJunit('no xml', 'W:/acme')); + Assert::null(TestResults::fromJunit('', 'W:/acme')); +}); + + +test('a test gone, skipped now or failing under one of its repeated identities is a new failure', function () { + $baseline = new TestResults(['A::one' => TestStatus::Passed, 'A::two' => TestStatus::Passed, 'A::three' => TestStatus::Failed]); + Assert::same(['A::one (gone)', 'A::two (gone)'], TestResults::fromJunit('', '')?->findNewFailures($baseline)); + + $results = TestResults::fromJunit(<<<'XX' + + + + + + XX, ''); + Assert::same(['A::one (skipped)', 'A::two'], $results?->findNewFailures($baseline)); +}); + + +test('a run says by its exit code whether it is done, leaves work for a human, is incomplete or waits outside DressCode', function () { + $codes = []; + foreach (RunStop::cases() as $stop) { + $codes[$stop->name] = new RunOutcome($stop)->getExitCode(); + } + + Assert::same([ + 'Done' => 0, + 'Composer' => 4, + 'Raised' => 4, + 'Manual' => 4, + 'Tasks' => 1, + 'Tests' => 1, + 'Unprocessed' => 2, + 'Remaining' => 1, + 'Interrupted' => 1, + 'Commit' => 2, + ], $codes); + // tests that do not run before the first step leave the run incomplete, a crash after a step goes back as a failure + Assert::same(2, new RunOutcome(RunStop::Tests, crash: 'it wrote no results')->getExitCode()); + Assert::same(1, new RunOutcome(RunStop::Tests, 1, crash: 'it wrote no results')->getExitCode()); +}); + + +test('a fix step runs over the project as it is and stops before the raise of Composer, which it waits for', function () { + $root = createSteppedProject('steps-blocked'); + $generated = " ['upgrading.php.implicitNullable' => ['src/Code.php']]]), + $runner->run(createSteppedPlan()), + ); + Assert::same(" ['upgrading.php.implicitNullable' => []]]), $runner->run(createSteppedPlan())); +}); + + +test('a step whose tests newly fail goes back byte for byte, and a command writing no results is refused', function () { + $root = createSteppedProject('steps-failed'); + $code = file_get_contents("$root/src/Code.php"); + $runner = new PlanRunner(createSteppedRunProject($root)); + $php = escapeshellarg(getPhpCliBinary()); + + $outcome = $runner->run(createSteppedPlan("$php tests.php {junit}")); + // a test of Nette Tester is named by its file within the root + Assert::same([RunStop::Tests, 1, ['tests/Code.phpt::run']], [$outcome->stop, $outcome->step, $outcome->newFailures]); + Assert::same($code, file_get_contents("$root/src/Code.php")); + // what the tests were compared with is said, a test failing before the first step being no regression + Assert::same([2, 0], [count($outcome->baseline->tests ?? []), $outcome->baseline?->countNotPassed()]); + // and a step sent back applied nothing + Assert::same([], $outcome->applied); + Assert::match( + "Tests compared with their run before the first step, %d%-%d%-%d% %d%:%d%, where 0 of 2 did not pass\n%A%", + new DressCode\Console\RunOutcomePrinter(createSteppedPlan(), $outcome)->print(new Nette\CommandLine\Console), + ); + + $outcome = new PlanRunner(new Project(new Config(paths: ['src'], cacheDir: 'other'), $root, "$root/dresscode.neon"))->run( + createSteppedPlan("$php -r 1;"), + ); + Assert::same([RunStop::Tests, null, []], [$outcome->stop, $outcome->step, $outcome->applied]); + Assert::match( + 'Failed the tests of `%a%` do not run before the first step, as the command of the tests wrote no JUnit report where `{junit}` stands, so nothing was changed', + new DressCode\Console\RunOutcomePrinter(createSteppedPlan(), $outcome)->print(new Nette\CommandLine\Console), + ); + + // a report of no test is no result, nor is an exit code no runner ends with for its failing tests + file_put_contents("$root/report.php", <<<'XX' + '; + file_put_contents($argv[1], "$case"); + exit((int) $argv[3]); + XX); + $report = fn(string $cases, int $exit) => new DressCode\Upgrade\ProcessTestRunner()->run( + escapeshellarg(getPhpCliBinary()) . " report.php {junit} $cases $exit", + $root, + )->crash; + Assert::same('the report of the tests holds no test', $report('none', 0)); + Assert::same('the command of the tests ended with exit code 255', $report('failing', 255)); + Assert::null($report('failing', 1)); +}); + + +test('a raise no fix follows is tested after it all the same, its dependencies staying raised where the tests fail', function () { + $root = createSteppedProject('steps-raise-tested'); + file_put_contents("$root/tests.php", <<<'XX' + ' : '>') . ''); + XX); + $plan = new Plan( + [Target::php('8.4')], + [new ComposerStep('raise php to ^8.4', ['php' => '^8.4'])], + '1.0', + testCommand: escapeshellarg(getPhpCliBinary()) . ' tests.php {junit}', + ); + // the run goes on after the raise in a process that loads what it installed, the tests and the check at the end too + $runner = new PlanRunner(createSteppedRunProject($root), composer: new PlanRunnerComposer($root)); + $raised = $runner->run($plan, approve: fn() => true); + Assert::same([RunStop::Raised, 1], [$raised->stop, $raised->step]); + $outcome = $runner->run($plan, resumed: $raised); + Assert::same([RunStop::Tests, 1, ['Raise::raise']], [$outcome->stop, $outcome->step, $outcome->newFailures]); + Assert::same('xx', file_get_contents("$root/runs.txt")); // before the first step and after the raise + // a run started anew, as one that could not go on in a process of its own is, finds the raise untested in the journal + $again = $runner->run($plan); + Assert::same([RunStop::Tests, 1, ['Raise::raise']], [$again->stop, $again->step, $again->newFailures]); + Assert::same('xxx', file_get_contents("$root/runs.txt")); + Assert::same(['composer.json'], $outcome->raisedFiles); + Assert::match( + "%A%Raised composer.json changed, which `dresscode upgrade abort` puts back as they were before the raise and installs\n" + . 'Failed step 1 raised the dependencies, which stay raised, and these tests now fail: Raise::raise%A%', + new DressCode\Console\RunOutcomePrinter($plan, $outcome)->print(new Nette\CommandLine\Console), + ); + + // the journal keeps the files until a step after the raise is done, or the user puts them back + $state = new RunState(createSteppedRunProject($root)); + Assert::same(1, $state->journal->findStep()); + $restoration = $state->restore(createSteppedRunProject($root), new PlanRunnerComposer($root)); + Assert::same([['composer.json'], [], false], [$restoration->restored, $restoration->left, $restoration->installs]); + Assert::same('{"require": {"php": "^8.0"}}', file_get_contents("$root/composer.json")); + Assert::null($state->journal->findStep()); +}); + + +test('an install of what abort put back that fails is tried again by the next abort, which forgets the journal only then', function () { + $root = createSteppedProject('steps-abort-install'); + file_put_contents("$root/composer.lock", '{}'); + $project = createSteppedRunProject($root); + $state = new RunState($project); + $state->journal->recordBefore(2, $root); + file_put_contents("$root/composer.json", '{"require": {"php": "^8.4"}}'); + $state->journal->recordAfter($root); + $failures = 1; + $composer = new PlanRunnerComposer($root, onInstall: function () use (&$failures): void { + if ($failures-- > 0) { + throw new ComposerException('Composer failed: the network is down'); + } + }); + + $first = $state->restore($project, $composer); + Assert::same( + [['composer.json'], true, 'Composer failed: the network is down'], + [$first->restored, $first->installs, $first->installFailure], + ); + Assert::same([2, true], [$state->journal->findStep(), $state->journal->isAwaitingInstall()]); + + $dryRun = $state->restore($project, $composer, dryRun: true); + Assert::same([[], true], [$dryRun->restored, $dryRun->installs]); + + $second = $state->restore($project, $composer); + Assert::same([[], true, null], [$second->restored, $second->installs, $second->installFailure]); + Assert::null($state->journal->findStep()); +}); + + +test('the journal of Composer puts back what the raise changed, a file it created removed, a file changed since left', function () { + $root = createTempDir('composer-journal'); + $journal = new DressCode\Upgrade\ComposerJournal("$root/state"); + file_put_contents("$root/composer.json", 'before'); + $journal->recordBefore(2, $root); + file_put_contents("$root/composer.json", 'raised'); + file_put_contents("$root/composer.lock", 'lock'); + $journal->recordAfter($root); + $journal->recordBefore(3, $root); // a later raise keeps what was before the first one + Assert::same([2, ['composer.json', 'composer.lock']], [$journal->findStep(), $journal->findChanged()]); + + file_put_contents("$root/composer.lock", 'edited'); + Assert::same( + [['composer.json'], ['composer.lock' => 'The file changed after the raise of step 2, so it is not written back.']], + $journal->restore($root), + ); + Assert::same('before', file_get_contents("$root/composer.json")); + Assert::same('edited', file_get_contents("$root/composer.lock")); + // a file left stays kept, to go back once the change of it is undone, and one written back is no change any more + Assert::same([2, ['composer.lock'], true], [$journal->findStep(), $journal->findChanged(), $journal->isAwaitingInstall()]); + file_put_contents("$root/composer.lock", 'lock'); + Assert::same([['composer.lock'], []], $journal->restore($root)); + Assert::same([[], false], [$journal->findChanged(), $journal->isAwaitingInstall()]); + $journal->forget(); + + file_put_contents("$root/composer.lock", 'edited'); + $journal->recordBefore(2, $root); + file_put_contents("$root/composer.lock", 'new'); + $journal->recordAfter($root); + Assert::same([['composer.lock'], []], $journal->restore($root)); + Assert::same('edited', file_get_contents("$root/composer.lock")); + $journal->forget(); + + unlink("$root/composer.lock"); + $journal->recordBefore(2, $root); + file_put_contents("$root/composer.lock", 'created'); + $journal->recordAfter($root); + Assert::same([['composer.lock'], []], $journal->restore($root)); + Assert::false(is_file("$root/composer.lock")); +}); + + +test('a command of the tests that crashes after writing a report of passing tests fails the step, and the baseline too', function () { + $root = createSteppedProject('steps-crashed'); + $code = file_get_contents("$root/src/Code.php"); + file_put_contents("$root/crash.php", <<<'XX' + '); + if (str_contains(file_get_contents(__DIR__ . '/src/Code.php'), '?int') || isset($argv[2])) { + echo "Fatal error: shutdown\n"; + exit(7); + } + XX); + $php = escapeshellarg(getPhpCliBinary()); + + $outcome = new PlanRunner(createSteppedRunProject($root))->run(createSteppedPlan("$php crash.php {junit}")); + Assert::same([RunStop::Tests, 1, []], [$outcome->stop, $outcome->step, $outcome->newFailures]); + Assert::same('the command of the tests ended with exit code 7: Fatal error: shutdown', $outcome->crash); + Assert::same($code, file_get_contents("$root/src/Code.php")); + + $outcome = new PlanRunner(new Project(new Config(paths: ['src'], cacheDir: 'other'), $root, "$root/dresscode.neon"))->run( + createSteppedPlan("$php crash.php {junit} always"), + ); + Assert::match( + 'the tests of `%a%` do not run before the first step, as the command of the tests ended with exit code 7: Fatal error: shutdown', + (string) $outcome->crash, + ); +}); + + +test('a run interrupted in a step stops the next one before it runs anything, unless it is told to discard what was kept', function () { + $root = createSteppedProject('steps-interrupted'); + $project = createSteppedRunProject($root); + new RunState($project)->snapshots->record(1, 'src/Code.php', 'before', 'after'); + $runner = new PlanRunner($project); + + Assert::equal(new RunOutcome(RunStop::Interrupted, 1, interrupted: ['src/Code.php']), $runner->run(createSteppedPlan())); + Assert::same([1 => ['src/Code.php']], new RunState($project)->snapshots->findInterrupted()); + Assert::same(RunStop::Composer, $runner->run(createSteppedPlan(), discard: true)->stop); + Assert::same(RunStop::Composer, $runner->run(createSteppedPlan())->stop); + + // snapshots that cannot be read stop the run all the same, with the files unknown + FileSystem::write(new RunState($project)->directory . '/snapshots/2/index.json', '{broken'); + Assert::equal(new RunOutcome(RunStop::Interrupted, 2), $runner->run(createSteppedPlan())); +}); + + +test('a run is refused while another one works in the project, and going back forgets a file its step did not write yet', function () { + $root = createSteppedProject('steps-locked'); + $project = createSteppedRunProject($root); + $state = new RunState($project); + Assert::exception( + fn() => $state->runExclusively(fn() => new PlanRunner($project)->run(createSteppedPlan())), + DressCode\ConfigurationException::class, + 'Another run of the upgrade works in the project right now; wait until it ends.', + ); + + $code = (string) file_get_contents("$root/src/Code.php"); + $state->snapshots->record(1, 'src/Code.php', $code, 'after'); + Assert::same([], $state->snapshots->restore(1, $root)); + Assert::same($code, file_get_contents("$root/src/Code.php")); + Assert::same([], $state->snapshots->findInterrupted()); +}); + + +test('a file the fix cannot process stops the run after its step, and going back leaves a file changed since as it is', function () { + $root = createSteppedProject('steps-errors'); + file_put_contents("$root/src/Broken.php", "run(createSteppedPlan()); + Assert::same([RunStop::Unprocessed, 1], [$outcome->stop, $outcome->step]); + Assert::match('Syntax error: %a%', $outcome->unprocessed['src/Broken.php']); + Assert::contains('?int', (string) file_get_contents("$root/src/Code.php")); + // the tasks of the plan say so too, as nothing of the file is checked + Assert::match( + 'Syntax error: %a%', + new PlanRunner(createSteppedRunProject($root))->findTasks(createSteppedPlan())[1]['src/Broken.php'] ?? '', + ); + + // the tests change the file the step wrote, as a user editing it while they run would + $root = createSteppedProject('steps-conflict'); + file_put_contents("$root/edit.php", <<<'XX' + run( + createSteppedPlan(escapeshellarg(getPhpCliBinary()) . ' edit.php {junit}'), + ); + Assert::same(RunStop::Tests, $outcome->stop); + Assert::match( + 'The file changed after step 1 wrote it, so it is not written back; its text before the step is kept in `%a%`.', + $outcome->unprocessed['src/Code.php'], + ); + Assert::contains("// edited\n", (string) file_get_contents("$root/src/Code.php")); + // the text before the step stays until the user decides, as for a step that did not finish + $runner = new PlanRunner(createSteppedRunProject($root)); + Assert::equal(new RunOutcome(RunStop::Interrupted, 1, interrupted: ['src/Code.php']), $runner->run(createSteppedPlan())); +}); + + +test('with commit, each topic is committed with the files it changed once the tests of its step pass', function () { + $root = createSteppedProject('steps-commit'); + foreach (['GIT_AUTHOR_NAME', 'GIT_COMMITTER_NAME'] as $name) { + putenv("$name=Test"); + } + + foreach (['GIT_AUTHOR_EMAIL', 'GIT_COMMITTER_EMAIL'] as $name) { + putenv("$name=test@example.com"); + } + + $git = fn(string ...$args) => ProcessRunner::run(['git', ...array_values($args)], $root, 60); + $git('init', '--quiet'); + $git('commit', '--quiet', '--allow-empty', '-m', 'start'); + + $runner = new PlanRunner(createSteppedRunProject($root), commit: true); + + // a change of the working tree would go into the commit of a topic changing that file + $git('add', 'src/Code.php'); + $git('commit', '--quiet', '-m', 'code'); + file_put_contents("$root/src/Code.php", "\n", FILE_APPEND); + Assert::exception( + fn() => $runner->run(createSteppedPlan()), + DressCode\ConfigurationException::class, + 'A commit of a topic takes the files it changed whole, and the working tree has changes of its own; %a%', + ); + $git('checkout', '--', 'src/Code.php'); + // the plan the run saves is no change of the code + file_put_contents("$root/dresscode-upgrade.neon", "# plan\n"); + $git('add', 'dresscode-upgrade.neon'); + $git('commit', '--quiet', '-m', 'plan'); + file_put_contents("$root/dresscode-upgrade.neon", "# plan saved anew\n"); + + $runner->run(createSteppedPlan()); + [, $log] = $git('log', '-1', '--name-only'); + Assert::match( + "%A% upgrade: upgrading.php.implicitNullable\n\n DressCode-Upgrade-Step: 1\n\nsrc/Code.php\n", + str_replace("\r", '', $log), + ); + + // a raise the run makes is committed too, so that the next run finds no changes of its own + $runner = new PlanRunner(createSteppedRunProject($root), commit: true, composer: new PlanRunnerComposer($root)); + $raised = $runner->run(createSteppedPlan(), approve: fn() => true); + Assert::same(RunStop::Done, $runner->run(createSteppedPlan(), resumed: $raised)->stop); + Assert::contains('upgrade: raise php to ^8.4', $git('log', '-1')[1]); + Assert::false($runner->hasOwnChanges()); + file_put_contents("$root/composer.json", '{"require": {"php": "^8.0"}}'); + $git('commit', '--quiet', '-am', 'php ^8.0'); + + // a commit git refuses ends the run, what the step changed left in the working tree + file_put_contents("$root/src/Code.php", "run(createSteppedPlan()); + Assert::same( + [RunStop::Commit, 1, '`git commit` failed: refused by the hook; what step 1 changed is left uncommitted in the working tree.'], + [$outcome->stop, $outcome->step, $outcome->commitFailure], + ); + Assert::contains('?int', (string) file_get_contents("$root/src/Code.php")); +}); + + +test('with commit, a project git finds no repository of is refused before anything changes', function () { + $root = createSteppedProject('steps-commit-no-git'); + $code = file_get_contents("$root/src/Code.php"); + Assert::exception( + fn() => new PlanRunner(createSteppedRunProject($root), commit: true)->run(createSteppedPlan()), + DressCode\ConfigurationException::class, + '`--commit` commits into the git repository of the project, and git finds none there that tracks it, or refuses to tell its status.', + ); + Assert::same($code, file_get_contents("$root/src/Code.php")); +}); + + +test('with commit, a file the tests change after its step wrote it is kept as it is, and the step stays uncommitted', function () { + $root = createSteppedProject('steps-commit-edited'); + file_put_contents("$root/edit.php", <<<'XX' + '); + XX); + $git = fn(string ...$args) => ProcessRunner::run(['git', ...array_values($args)], $root, 60); + $git('init', '--quiet'); + $git('add', '--all'); + $git('-c', 'user.name=Test', '-c', 'user.email=test@example.com', 'commit', '--quiet', '-m', 'start'); + + $outcome = new PlanRunner(createSteppedRunProject($root), commit: true)->run( + createSteppedPlan(escapeshellarg(getPhpCliBinary()) . ' edit.php {junit}'), + ); + Assert::same( + [ + RunStop::Commit, + '`src/Code.php` changed after step 1 wrote it, so the step is left uncommitted in the working tree; commit it yourself.', + ], + [$outcome->stop, $outcome->commitFailure], + ); + $code = (string) file_get_contents("$root/src/Code.php"); + Assert::contains('?int', $code); + Assert::contains("// edited\n", $code); + Assert::match("%A% start\n", str_replace("\r", '', $git('log', '-1')[1])); +}); + + +test('with commit, a step leaving a file it cannot process is committed whole once a later run processes it', function () { + $root = createSteppedProject('steps-commit-errors'); + file_put_contents("$root/src/Broken.php", " ProcessRunner::run(['git', ...array_values($args)], $root, 60); + $git('init', '--quiet'); + $git('add', '--all'); + $git('-c', 'user.name=Test', '-c', 'user.email=test@example.com', 'commit', '--quiet', '-m', 'start'); + $runner = new PlanRunner(createSteppedRunProject($root), commit: true); + + Assert::same(RunStop::Unprocessed, $runner->run(createSteppedPlan())->stop); + Assert::match("%A% start\n", str_replace("\r", '', $git('log', '-1')[1])); + Assert::contains('?int', (string) file_get_contents("$root/src/Code.php")); + + // what the run keeps lies in the repository, and a plan whose step 1 is another one now refuses to commit it + Assert::true(is_dir("$root/.git/dresscode-upgrade")); + $edited = new Plan([Target::php('8.4')], [new FixStep('edited', ['upgrading.php.deprecatedApi'])], '1.0'); + Assert::exception( + fn() => $runner->run($edited), + DressCode\ConfigurationException::class, + 'The plan changed since a run left step 1 uncommitted, waiting for files it could not process; %a%', + ); + + // a file the step wrote and someone changed since is a change of their own, which the commit would take + $written = (string) file_get_contents("$root/src/Code.php"); + file_put_contents("$root/src/Code.php", "$written// mine\n"); + Assert::exception( + fn() => $runner->run(createSteppedPlan()), + DressCode\ConfigurationException::class, + 'A commit of a topic takes the files it changed whole, and the working tree has changes of its own; %a%', + ); + file_put_contents("$root/src/Code.php", $written); + + // the user makes the file parse, which is no change of their own for the run, and the step goes into one commit + file_put_contents("$root/src/Broken.php", "run(createSteppedPlan())->stop); + Assert::match( + "%A% upgrade: upgrading.php.implicitNullable\n%A%\nsrc/Broken.php\nsrc/Code.php\n", + str_replace("\r", '', $git('log', '-1', '--name-only')[1]), + ); +}); + + +test('a fix resolves the names with what the namespaces declare, as the estimate does', function () { + $root = createSteppedProject('steps-names'); + file_put_contents("$root/src/Close.php", "run($plan)->applied[1]['php']); + Assert::notContains('curl_close', (string) file_get_contents("$root/src/Close.php")); +}); + + +test('a plan leaving a task is not done, and a step it does not run is refused', function () { + $root = createSteppedProject('steps-left'); + file_put_contents("$root/composer.json", '{"require": {"php": "^8.1"}}'); + file_put_contents("$root/src/Date.php", "run($plan); + Assert::same([RunStop::Tasks, 1], [$outcome->stop, $outcome->step]); + Assert::same(['src/Date.php'], array_map(fn(Task $task) => $task->path, $outcome->tasks['php'])); + + Assert::exception( + fn() => $runner->run($plan, singleStep: 3), + DressCode\ConfigurationException::class, + 'The plan has no step 3; it has 2.', + ); + Assert::exception( + fn() => $runner->run($plan, singleStep: 2), + DressCode\ConfigurationException::class, + 'Step 2 of the plan is left out with `skip: true`, so it is not run.', + ); +}); + + +test('a step of Composer that updates is done once the version installed is one it allows, not the constraint alone', function () { + $root = createSteppedProject('steps-installed'); + file_put_contents("$root/composer.json", '{"require": {"php": "^8.0", "acme/mail": "^4.0"}}'); + $installed = fn(string $version) => FileSystem::write( + "$root/vendor/composer/installed.json", + json_encode(['packages' => [['name' => 'acme/mail', 'version_normalized' => $version]]], JSON_THROW_ON_ERROR), + ); + $plan = new Plan( + [new Target('acme/mail', '4.0')], + [new ComposerStep('raise acme/mail to ^4.0', ['acme/mail' => '^4.0'])], + '1.0', + ); + $runner = new PlanRunner(createSteppedRunProject($root)); + + $installed('3.2.0.0'); + Assert::same(RunStop::Composer, $runner->run($plan)->stop); + $installed('4.0.0.0'); + // the plan is done once the targets find nothing in the whole scope, which no step of this one fixes + Assert::equal( + new RunOutcome(RunStop::Remaining, remaining: ['src/Code.php']), + $runner->run($plan), + ); + file_put_contents("$root/src/Code.php", "run($plan)->stop); + + // the lock holds what an install gives, so it must allow the version too + $lock = fn(string $version) => file_put_contents( + "$root/composer.lock", + json_encode(['packages' => [['name' => 'acme/mail', 'version' => $version]], 'packages-dev' => []], JSON_THROW_ON_ERROR), + ); + $lock('v3.2.0'); + Assert::same(RunStop::Composer, $runner->run($plan)->stop); + $lock('v4.0.0'); + Assert::same(RunStop::Done, $runner->run($plan)->stop); +}); + + +test('a step raising PHP is done once config.platform.php allows the version too, which Composer resolves for', function () { + $root = createSteppedProject('steps-platform'); + $composer = fn(string $platform) => file_put_contents( + "$root/composer.json", + json_encode(['require' => ['php' => '^8.4'], 'config' => ['platform' => ['php' => $platform]]], JSON_THROW_ON_ERROR), + ); + $plan = new Plan([Target::php('8.4')], [new ComposerStep('raise php to ^8.4', ['php' => '^8.4'], platform: '8.4')], '1.0'); + $runner = new PlanRunner(createSteppedRunProject($root)); + file_put_contents("$root/src/Code.php", "run($plan)->stop); + $composer('8.4'); + Assert::same(RunStop::Done, $runner->run($plan)->stop); +}); + + +test('a manual step passes once Composer says nothing of the lock refuses its target', function () { + $root = createSteppedProject('steps-manual'); + file_put_contents("$root/src/Code.php", " file_put_contents("$root/composer.lock", json_encode([ + 'packages' => [ + ['name' => 'acme/shop', 'version' => '1.2.0', 'require' => ['acme/mail' => $constraint]], + ['name' => 'acme/mail', 'version' => '2.1.0'], + ], + 'packages-dev' => [], + ], JSON_THROW_ON_ERROR)); + $target = new Target('acme/mail', '3.0'); + $plan = new Plan([$target], [new ManualStep('make way for acme/mail 3.0: acme/shop', $target)], '1.0'); + $runner = new PlanRunner(createSteppedRunProject($root)); + + $lock('^2.0'); + $outcome = $runner->run($plan); + Assert::same([RunStop::Manual, 1], [$outcome->stop, $outcome->step]); + Assert::same(['acme/shop'], array_map(fn(Blocker $blocker) => $blocker->package, $outcome->blockers->packages ?? [])); + + $lock('^2.0 || ^3.0'); // the project itself refusing it is left out + Assert::same(RunStop::Done, $runner->run($plan)->stop); + + // without a lock nothing tells, so the step waits as for an answer Composer did not give + unlink("$root/composer.lock"); + $outcome = $runner->run($plan); + Assert::same([RunStop::Manual, 'the project has no `composer.lock` to ask'], [$outcome->stop, $outcome->blockers?->unknown]); +}); + + +test( + 'a raise approved lets the run go on once Composer made it, one it did not make or that is not approved leaves the run waiting', + function () { + $root = createSteppedProject('steps-raised'); + $project = createSteppedRunProject($root); + $asked = []; + $approve = function (DependencyStep $step, array $changes) use (&$asked): bool { + $asked[] = $step->title; + return true; + }; + $runner = new PlanRunner($project, composer: new PlanRunnerComposer($root, onRequire: fn() => null)); + Assert::same(2, $runner->run(createSteppedPlan(), approve: $approve)->step); + Assert::same(['raise php to ^8.4'], $asked); + Assert::same( + [RunStop::Composer, 2], + [($outcome = $runner->run(createSteppedPlan(), approve: fn() => false))->stop, $outcome->step], + ); + + // where Composer fails, the outcome says why, beside what the run tells + $fail = fn() => throw new DressCode\Upgrade\ComposerException('Composer failed: Your requirements could not be resolved'); + $runner = new PlanRunner($project, composer: new PlanRunnerComposer($root, onRequire: $fail)); + $outcome = $runner->run(createSteppedPlan(), approve: fn() => true)->withWarnings(['The types are not there.']); + Assert::same( + [RunStop::Composer, 'Composer failed: Your requirements could not be resolved', ['The types are not there.']], + [$outcome->stop, $outcome->composerFailure, $outcome->warnings], + ); + Assert::match( + "%A%Warning The types are not there.\nFailed step 2, Composer failed: Your requirements could not be resolved; raise php to ^8.4: run %A%", + new DressCode\Console\RunOutcomePrinter(createSteppedPlan(), $outcome)->print(new Nette\CommandLine\Console), + ); + + $runner = new PlanRunner($project, composer: new PlanRunnerComposer($root)); + $raised = $runner->run(createSteppedPlan(), approve: fn() => true); + Assert::same([RunStop::Raised, 2], [$raised->stop, $raised->step]); + Assert::equal( + new RunOutcome(RunStop::Done, null, [1 => ['upgrading.php.implicitNullable' => []]]), + $runner->run(createSteppedPlan(), resumed: $raised), + ); + }, +); + + +test('the files of Composer a raise changes are kept to go back where they lie above the root of the configuration', function () { + $above = createTempDir('steps-composer-above'); + mkdir("$above/app"); + $root = "$above/app"; + foreach (['src', 'dresscode.neon', 'tests.php'] as $entry) { + rename(createSteppedProject('steps-composer-below') . "/$entry", "$root/$entry"); + } + + file_put_contents("$above/composer.json", '{"require": {"php": "^8.0"}}'); + $runner = new PlanRunner(createSteppedRunProject($root), composer: new PlanRunnerComposer($above)); + $plan = new Plan([Target::php('8.4')], [new ComposerStep('raise php to ^8.4', ['php' => '^8.4'])], '1.0'); + $raised = $runner->run($plan, approve: fn() => true); + Assert::same(RunStop::Remaining, $runner->run($plan, resumed: $raised)->stop); // the bridge is not in the plan + Assert::same(['composer.json'], $runner->state->journal->findChanged()); + Assert::same([['composer.json'], []], $runner->state->journal->restore(createSteppedRunProject($root)->findComposerRoot())); + Assert::same('{"require": {"php": "^8.0"}}', file_get_contents("$above/composer.json")); +}); + + +test('the update to the newest versions is done once Composer says it would change nothing, and asked for otherwise', function () { + $root = createSteppedProject('steps-newest'); + file_put_contents("$root/src/Code.php", " v3.2.1)']); + $runner = new PlanRunner(createSteppedRunProject($root), composer: $composer); + $asked = []; + $approve = function (DependencyStep $step, array $changes) use (&$asked): bool { + $asked[] = $changes; + return true; + }; + $raised = $runner->run($plan, approve: $approve); + Assert::same([RunStop::Raised, RunStop::Done], [$raised->stop, $runner->run($plan, resumed: $raised)->stop]); + Assert::same(RunStop::Done, $runner->run($plan, approve: $approve)->stop); + Assert::same([['- Upgrading acme/mail (v3.0.0 => v3.2.1)']], $asked); // done, so not asked again + Assert::same(1, $composer->updates); + Assert::same(['composer update'], $step->formatCommands()); +}); + + +test('a failure of Composer or of the tests stops the run where it happens, whoever runs them', function () { + $root = createSteppedProject('steps-boundaries'); + $composer = new class implements PackageManager { + public function findBlockers(Target $target): Blockers + { + return new Blockers($target, unknown: 'Composer did not answer within 60 s'); + } + + + public function previewRequire(array $constraints, bool $update = true, ?string $platform = null): array + { + return []; + } + + + public function require(array $constraints, bool $update = true, ?string $platform = null): void + { + } + + + public function previewUpdate(): array + { + throw new ComposerException('Composer failed: the network is down'); + } + + + public function update(): void + { + } + + + public function install(): void + { + } + }; + $tests = new class implements TestRunner { + public function run(string $command, string $root): TestResults + { + return new TestResults(['A::a' => TestStatus::Passed], crash: 'the command of the tests ended with exit code 255'); + } + }; + $project = createSteppedRunProject($root); + $target = new Target('acme/mail', '3.0'); + + $runner = new PlanRunner($project, composer: $composer); + $outcome = $runner->run(new Plan([$target], [new ManualStep('make way for acme/mail 3.0', $target)], '1.0')); + Assert::same([RunStop::Manual, 'Composer did not answer within 60 s'], [$outcome->stop, $outcome->blockers?->unknown]); + $outcome = $runner->run(new Plan([$target], [new UpdateStep('update to the newest versions')], '1.0')); + Assert::same([RunStop::Composer, 'Composer failed: the network is down'], [$outcome->stop, $outcome->composerFailure]); + + Assert::same( + 'the tests of `tests {junit}` do not run before the first step, as the command of the tests ended with exit code 255', + new PlanRunner($project, tests: $tests)->run(createSteppedPlan('tests {junit}'))->crash, + ); +}); + + +test('a raise a fix follows stops the run, which goes on after it from the outcome handed over as data', function () { + $root = createSteppedProject('steps-resumed'); + $plan = new Plan([Target::php('8.4')], [ + new FixStep('works on the versions allowed today', ['upgrading.php.implicitNullable']), + new ComposerStep('raise php to ^8.4', ['php' => '^8.4']), + new FixStep('needs the targets', ['upgrading.php.implicitNullable']), + ], '1.0'); + $runner = new PlanRunner(createSteppedRunProject($root), composer: new PlanRunnerComposer($root)); + $outcome = $runner->run($plan, approve: fn() => true); + Assert::equal(new RunOutcome(RunStop::Raised, 2, [1 => ['upgrading.php.implicitNullable' => ['src/Code.php']]]), $outcome); + + $handed = RunOutcome::fromArray(json_decode(json_encode($outcome->toArray(), JSON_THROW_ON_ERROR), associative: true)); + Assert::equal($outcome, $handed); + Assert::equal( + new RunOutcome(RunStop::Done, null, [ + 1 => ['upgrading.php.implicitNullable' => ['src/Code.php']], + 3 => ['upgrading.php.implicitNullable' => []], + ]), + $runner->run($plan, resumed: $handed), + ); + + // what a fix left goes over as data too + $violation = new DressCode\Violation( + 'upgrading.php.deprecatedApi', + 'Deprecated.', + 3, + 5, + DressCode\Severity::Error, + 'abc', + fixable: false, + ); + $outcome = new RunOutcome(RunStop::Raised, 2, tasks: ['php' => [new Task('src/Code.php', $violation)]]); + Assert::equal($outcome, RunOutcome::fromArray(json_decode(json_encode($outcome->toArray(), JSON_THROW_ON_ERROR), associative: true))); +}); + + +test( + 'the tasks are what the fixes of the plan leave in the code as it stands, changing nothing', + function () { + $root = createSteppedProject('steps-tasks'); + file_put_contents("$root/composer.json", '{"require": {"php": "^8.1"}}'); + $code = <<<'XX' + findTasks($plan); + Assert::same([], $unprocessed); + Assert::same([['src/Date.php', 5]], array_map(fn(Task $task) => [$task->path, $task->violation->line], $tasks['php'])); + Assert::equal( + [new Postponement('src/Date.php', 10, 'dresscode:ignore upgrading.php.deprecatedApi')], + Postponement::findIn($runner->project, $plan->paths), + ); + // a suppression without a reason only puts a task off; and nothing is changed, the fix of `Code.php` included + Assert::same($code, file_get_contents("$root/src/Date.php")); + Assert::notContains('?int', (string) file_get_contents("$root/src/Code.php")); + + // so a run whose fixes leave nothing else is not done either + file_put_contents( + "$root/src/Date.php", + str_replace( + "\treturn strftime('%B');", + "\t// dresscode:ignore upgrading.php.deprecatedApi -- legacy\n\treturn strftime('%B');", + $code, + ), + ); + $outcome = $runner->run($plan); + Assert::same([RunStop::Tasks, null], [$outcome->stop, $outcome->step]); + Assert::equal([new Postponement('src/Date.php', 11, 'dresscode:ignore upgrading.php.deprecatedApi')], $outcome->postponed); + }, +); + + +test('the tasks hold what the check of the whole scope at the end of a run finds and no topic of the plan does', function () { + $root = createSteppedProject('steps-tasks-remaining'); + file_put_contents("$root/composer.json", '{"require": {"php": "^8.1"}}'); + file_put_contents("$root/src/Date.php", "findTasks($plan); + Assert::same(['deprecations'], array_keys($tasks)); + Assert::same( + [['src/Date.php', 5, 'upgrading.php.deprecatedApi']], + array_map(fn(Task $task) => [$task->path, $task->violation->line, $task->violation->decision], $tasks['deprecations']), + ); +});