diff --git a/.changeset/first-release-cli.md b/.changeset/first-release-cli.md index 602e1b1..6235c7b 100644 --- a/.changeset/first-release-cli.md +++ b/.changeset/first-release-cli.md @@ -6,6 +6,7 @@ First release of the Druxt command-line tool, with the binary `drx`. - `drx init` creates a site from a starter in a registry, records its layout and parts in `drx.config.json` and prints what the site needs next. `--engine` chooses how the backend runs, from the engines the starter lists or `none` for a backend that exists already. `init` keeps that engine's files only and warns when its commands are not on `PATH`. - `drx module list`, `drx module search` and `drx module info` read the Druxt module registry, and in a project show what is installed and whether each module's range admits the Druxt there. +- `drx add` installs a module and lists it in the Nuxt config. It also requires and enables the Drupal modules the module needs, through the backend's engine. `drx remove` takes it out again. Both take `--dry-run`. - `drx info` prints the versions of the CLI, Node and the packages of each part of a project. - At a terminal, bare `drx` opens a menu and `drx init` is a guided run that asks before it writes. `--no-interactive`, `DRX_NO_INTERACTIVE=1`, `CI` or no terminal turn every prompt off. - The registry holds one starter, `quickstart`, and the `monorepo` layout is the one available. diff --git a/.cspell.json b/.cspell.json index 942f080..533ce18 100644 --- a/.cspell.json +++ b/.cspell.json @@ -18,7 +18,8 @@ "**/CHANGELOG.md", "package-lock.json", ".vale/", - "packages/cli/starters/" + "packages/cli/starters/", + "packages/cli/test/fixtures/" ], "useGitignore": true } diff --git a/.prettierignore b/.prettierignore index 58399a0..a8e1db8 100644 --- a/.prettierignore +++ b/.prettierignore @@ -7,6 +7,9 @@ CHANGELOG.md .vale/ packages/cli/starters/ +# Copies of real files, kept byte for byte so an edit to one can be compared. +packages/cli/test/fixtures/ + # Pipeline definitions are owned by yamllint, not prettier. The two disagree on # comment spacing, and letting both format these files means each run of one # undoes the other. diff --git a/README.md b/README.md index fce062b..86924d5 100644 --- a/README.md +++ b/README.md @@ -90,7 +90,7 @@ An engine is a way to run the site's backend on your machine. The starter lists - The prompt lists the engines whose commands are installed first, and marks the others as not installed. You can still choose one of those. `init` then warns which commands are missing, and creates the site. - With `--yes` or no terminal, the engine is the first whose commands are all installed, or the starter's first when none is. - `init` removes the files of the engines you did not choose, so a DDEV site has no `.lando.yml`. `--keep-engines` leaves them all. -- **`--force` into a project that exists.** `--force` writes the starter's files into a directory that holds files, and a file the starter also has is replaced by the starter's. It deletes nothing. The files of the engines you did not choose stay, since any of them may be your own. `init` warns with their paths, and a guided run says so in its summary before it asks. Commit or copy the project first. +- **`--force` into a project that exists.** `--force` writes the starter's files into a directory that holds files, and a file the starter also has is replaced by the starter's. It deletes nothing. The files of the engines you did not choose stay, since any of them may be your own. `init` warns with their paths, and a guided run says so in its summary before it asks. `drx.config.json` is written again from the starter and your choices, and keeps the `modules` records `drx add` wrote, so what was added can still be removed. Commit or copy the project first. - For an engine that serves the backend at a fixed URL, and for `none`, `init` writes the URL where the starter reads it. For the quickstart that is `BASE_URL` in `.env`. - What the site needs and the steps to run next are the chosen engine's. - An engine or a database the starter does not offer fails, with the names it does offer. @@ -148,6 +148,90 @@ The Druxt version compared is the one installed in the part, or the range the pa The same table, for the modules whose name, package name or description contains the text. Case is ignored. It takes the options of `drx module list`. +### `drx add ` + +Adds one or more modules to the project, by registry name or package name. `drx module add` is the same command. + +```bash +npx @druxt/cli add breadcrumb +npx @druxt/cli add breadcrumb --dry-run +``` + +For each module it does two things: + +- **Frontend.** It installs the package with the project's package manager, and adds the package to the `modules` array of `nuxt.config`. The rest of the file stays as you wrote it. When the config is a function, or its `modules` is not an array written out in the file, the package is installed, the file is left alone and the line to add is printed. The record says that the line was left to you. +- **Backend.** For each Drupal module the entry lists, a contributed one is required with Composer and enabled with Drush, and a core one is only enabled. The commands run through the part's engine: `ddev composer`, `lando drush`, or `composer` and `vendor/bin/drush` for the `php` engine. Once Composer has changed which packages are installed, `drush cr` rebuilds the caches before Drupal is asked anything more. Drupal keeps its container by the set of installed packages, so a set the site has had before brings back the container built for it then. + +The package manager is found as `drx init --install` finds it. The one a `package.json` names in `packageManager` comes first, looked for from the root of the project down to the part, so a workspace is installed with the manager of its root. Without one it is the manager of the first lock file on the same way down, and npm when there is no lock file. + +With several modules, each is added in full before the next is looked at. The steps of the second are worked out from the project as the first left it, so a backend module two of them need is required and enabled once, and goes on the record of the first. A dry run shows the steps of each from the project as it is now. + +It first asks the backend which modules are enabled, with `drush pm:list`, and leaves one that is enabled as it is. A dry run asks too, since asking changes nothing. Once the steps have run it asks again, because Drupal enables the modules a module depends on along with it, and those go on the record as enabled by `add` too. A package that `package.json` or `composer.json` already has is not installed again, and a module the config already lists is not listed twice. What `add` did, and what it found in place, goes on the [record](#the-project-configuration). + +| Option | What it does | +| ------------------------------------------------ | ------------------------------------------------------------------------------------ | +| `--dry-run` | Print every step, with each command line and what is left to you, and change nothing | +| `--force` | Add a module that is archived, or whose range does not admit the Druxt in the part | +| `--no-patches` | Leave out the patches the module needs, with a warning naming each | +| `--yes`, `-y` | Ask nothing | +| `--module-registry `, `--refresh`, `--json` | As for `drx module list` | + +What it refuses, before it takes any step: + +- A module when no frontend part of the project can take its package: the part's directory is missing, or it is of a kind this version cannot add to. Otherwise the run would end with "Added" and nothing done. +- An archived module, and one whose Druxt range excludes the Druxt in the frontend part. `--force` adds either. A module whose range is `unknown` is added with a warning. +- A module with no package, which is not released. `--force` does not change that. +- A Drupal module it cannot place as core or contributed. See below. +- A patch whose URL is not `https`. Composer does not fetch a patch over `http`, so `add` refuses, naming the patch and the module, before it writes anything. `--no-patches` adds the module without it. +- A patch whose description the site's `composer.json` already has for the same package, with another URL. That patch is the site's own, and `add` does not replace it. +- A patch on a site whose installed `cweagans/composer-patches` is version 1. The message names the version. `add` writes patches for version 2, which keeps them in a lock file. +- A patch on a site whose `composer.json` sets `allow-plugins` to `false`, or turns the patches plugin off by name. Composer does not run the plugin then, so the patch would never be applied. + +**Where the backend is not run from here.** With the `none` engine, or in a project that does not record an engine, the frontend is done and the Composer and Drush lines are printed under "Left to do", for you to run where the backend is. `add` cannot look in such a backend. Where the registry does not say whether a module is part of core, the `composer require` line names it, and a note says that a core module needs the enable line only. + +**Patches.** A Drupal module in the registry may list patches. `add` shows each with its issue and writes it to `extra.patches` in the site's `composer.json`. It then runs `composer patches-relock`, and `composer patches-repatch` when the patched package is installed already, whether the site requires it or another package brought it in. When the site lacks `cweagans/composer-patches`, it allows the plugin and requires it, and the record says which of the two `add` did. Allowing it adds one key to `allow-plugins`, as Composer does when you answer its own question. A list gets the key, and a site with no list gets one. `true` already allows every plugin and is left as it is. A patch is skipped when the installed package is at or past the version that has the fix. + +Whether a patch is applied is read from the site. `composer.json` only lists the patch. A patch that `composer.json` lists and `patches.lock.json` does not is locked and applied, so a run that stopped at the lock file is finished by the next one. Version 2 of the plugin does not record on a package which patches were applied to it. So when a patch is locked and its package is installed, `add` installs that package again with `composer reinstall`, which applies the patch. A patch that is locked for a package still to be installed is left alone. + +**A project with no backend part.** The frontend is done, and what the module needs of a backend is listed under "Left to do": the modules to enable, their patches and their setup steps. + +**Tools and their arguments.** Each tool is started directly, with its arguments as a list and no shell to read them, and with `--` before the names where the tool takes it: npm, pnpm, yarn, Composer and Drush do. On Windows a tool that is a batch file, as `npm` and `composer` are, can only be run by the command interpreter. It gets every argument in double quotes, and an argument with a quote, a percent sign or a line break in it is refused. That path is covered by tests of the command line it builds, and has not been run on a Windows machine yet. + +**Setup.** Steps a module needs done by hand, such as creating a consumer, are printed under "Left to do". They are not run. + +**When a tool fails.** The run stops there. The tool's output is printed, then what was done and what was not. The steps that were taken go on the record, and it asks the backend what is enabled by then. So running `drx add` again finishes the job and leaves the record of a run that never failed, and `drx remove` undoes what was done. A `drx remove` that fails keeps its record, and a second run takes out what is left. With `--json` the error has the code `step-failed`, and next to the message a `failed` object with the `part`, the `step`, its `exitCode` and its `output`, and the `done` and `notDone` steps as arrays. + +**Core or contributed.** The registry marks a core module with `core: true`, and a registry that marks any module is taken to mark them all. Against a registry that marks none, which is the published one today, `add` looks in the core the site has installed, under `web/core/modules`, and treats a package the site already requires as contributed. With no core installed it refuses that module and says to install the backend's dependencies first, since the CLI does not keep a list of core modules to guess from. A backend that is not run from here is the exception, described above. + +At a terminal with no name, `drx add` lists the modules to pick from, shows the steps and asks before it changes anything. + +### `drx remove ` + +Undoes what `drx add` did for a module, and nothing else. `drx module remove` is the same command. It takes `--dry-run`, `--yes`, `--module-registry`, `--refresh` and `--json`. + +It needs the record and not the registry. A module the registry no longer lists is removed by the name or the package on its record. When the registry cannot be read and there is no copy of it, `remove` warns and goes ahead. With `--backend` it then cannot tell whether another module still needs a backend module, and says so. + +It works from the record in `drx.config.json`: + +- The package is uninstalled when `add` installed it, and taken out of the `modules` array when `add` listed it. A package or an entry the site had before stays, with a line saying so. The rest of the config file stays as you wrote it. +- Where `add` printed the line for you to add, `remove` prints the line for you to remove, under "Left to do". `add` could not read that config, so `remove` does not claim the entry was there before. +- A module with no record is refused, and the exit code is 1: `add` did nothing for it, so there is nothing to undo. That goes for a module the project does not have, and for one you installed yourself. +- A record written by an earlier version does not say who installed the package. `remove` then leaves the frontend alone and prints the lines that take it out. + +The backend is left alone unless `--backend` is given. With it, `remove` undoes the rest of the record: + +- It uninstalls the Drupal modules `add` enabled. A module that was enabled before `add` ran is not uninstalled. +- It takes out the Composer requirements `add` added, and the patches it wrote. A package that another package still requires only leaves `composer.json`. A package that loses a patch and stays installed is reinstalled without it. +- With the last patch in `composer.json` it takes out `cweagans/composer-patches`, the key that allowed it and its `patches.lock.json`, each only when the record says `add` put it there. A plugin the site had stays. A plugin that another module's patch still needs stays too, and moves to the record of that module. +- Once Composer has taken packages out, `drush cr` rebuilds the caches, as after an `add`. +- A package stays required while a module in it is still enabled, so no enabled module loses its files. `remove` names the module. +- Before it uninstalls a module it asks Drupal what else that would uninstall, with `drush pm:uninstall --simulate -- `. Drupal uninstalls the modules that depend on one along with it. So a module that another enabled module depends on stays, with its requirement and its patches, and `remove` names what depends on it. +- Whether a module is enabled is asked twice, of `drush pm:list` and of the simulated uninstall. The first reads the site's configuration and the second its container, which can be out of date. When the two disagree, or one of them cannot be had, the module stays enabled and required, its record is not changed, and the commands are printed under "Left to do". +- When Drupal cannot be asked, nothing is uninstalled and the command is printed under "Left to do". +- A Drupal module that another Druxt module in the project needs stays. It moves to the record of that module when it has one, along with anything Drupal holds on to because of it, so removing that module takes it all out. + +Whatever stays in place stays on the record, so a later `drx remove --backend` can finish the job. + ### `drx module` With no command, at a terminal: a list of the modules that narrows as you type. Pick one and it is shown as `drx module info` shows it. Anywhere else it fails and names the commands. @@ -173,7 +257,7 @@ Usage for the CLI or one command, and the version. `drx` with no command opens a menu when a person is at the terminal. It names the project you are in, which it reads from `drx.config.json`. Below that are the actions for where you are: - Outside a project: create a site. -- Inside one: list, search or view modules, and view the project's details. Adding, removing and configuring a module and managing patches are listed as not available yet. +- Inside one: list, search or view modules, and view the project's details. Add or remove modules. Configuring a module and managing patches are listed as not available yet. Each entry runs the command it stands for, so the menu and the commands cannot differ. @@ -244,7 +328,7 @@ stdout is the JSON result and nothing else. stderr has one plain line per step. | `0` | The command did what it was asked | | `1` | It did not. The message on stderr says why | -With `--json`, a failure prints `{ "ok": false, "error": { "code", "message" } }` on stdout, and `code` says which kind it was: `usage`, `not-available`, `registry`, `invalid-entry`, `unknown-starter`, `unknown-source`, `unknown-module`, `directory-not-empty`, `config`, `download`, `install` or `cancelled`. +With `--json`, a failure prints `{ "ok": false, "error": { "code", "message" } }` on stdout, and `code` says which kind it was: `usage`, `not-available`, `registry`, `invalid-entry`, `unknown-starter`, `unknown-source`, `unknown-module`, `directory-not-empty`, `config`, `download`, `install`, `refused`, `step-failed` or `cancelled`. `refused` is `drx add` or `drx remove` declining before it takes a step. `step-failed` is a tool failing part way through one of them, and its error has the fields described under [`drx add`](#drx-add-module). ## The project configuration @@ -279,6 +363,44 @@ With `--json`, a failure prints `{ "ok": false, "error": { "code", "message" } } A kind is `nuxt` or `drupal` in this version. +`drx add` keeps a record under `modules`, one entry for each module it added, of what it did and what it found in place: + +```json +{ + "name": "breadcrumb", + "package": "druxt-breadcrumb", + "frontend": [{ "path": "nuxt", "installed": true, "listed": true }], + "backend": [ + { + "path": "drupal", + "modules": [ + { + "name": "decoupled_router", + "package": "drupal/decoupled_router", + "enabled": true, + "required": false + } + ], + "patches": [] + } + ] +} +``` + +| Key | What it holds | +| -------------------- | ------------------------------------------------------------------------------------------------------------------------------- | +| `frontend.installed` | `true` when `add` installed the package, `false` when the part had it | +| `frontend.listed` | `true` when `add` wrote the entry in the config, `false` when it was there | +| `frontend.byHand` | `true` when `add` could not write the entry and printed the line for you to add. Absent otherwise | +| `modules.enabled` | `true` when `add` enabled the Drupal module, or Drupal enabled it along with one `add` did. `false` when it was enabled already | +| `modules.required` | `true` when `add` added the Composer requirement. A core module has no `package` | +| `patches` | Each patch `add` wrote: its `package`, `description` and `url`, and the `module` it was written for | +| `patcher` | Present when `add` brought the patches plugin: `required` for its Composer requirement, `allowed` for its `allow-plugins` key | + +The names in a record are handed to the same tools as those of the registry, and the file travels with a clone of the project. So they are checked as the file is read, by the rules for the same names in a registry. A value that breaks one makes the file invalid, and the message names the field. + +Adding a module again adds to its entry and takes nothing from it. `drx remove` undoes what the entry says and keeps an entry for whatever it leaves behind. An entry written by an earlier version, with no `frontend` and no `enabled` or `required`, still reads: its modules count as both enabled and required by `add`. + A backend part also records the `engine` chosen at `init`, its `database` where the engine has one, and for the `none` engine the `baseUrl` of the backend. A file written before engines existed has none of the three and still reads. `drx info` prints them. ## The starter registry @@ -395,7 +517,7 @@ The package includes a copy of the public registry. When the public registry can The module commands read `https://cdn.jsdelivr.net/gh/druxt/modules@main/modules.json`, which the [druxt/modules](https://github.com/druxt/modules) repository publishes. The CLI reads `schemaVersion` 1. It refuses any other version with a message saying so, and ignores fields it has no use for. -The names in an entry become arguments of a package manager or a backend tool, so each is checked as the registry is read. A package name has to be one npm takes, and the name of a Drupal module has to be a machine name. Anything else, such as a name that starts with a hyphen, makes the registry invalid, and the message names the entry and the field. +The names in an entry become arguments of a package manager or a backend tool, so each is checked as the registry is read. A package name has to be one npm takes, and the name of a Drupal module has to be a machine name. A `composer.package` and the `package` of a patch have to be Composer names, as in `vendor/name`. A `composer.constraint` has to be a set of version constraints as Composer writes them, such as `^3.26 || ^4.0`, `>=1.0 <2.0` or `1.0 - 2.0`: versions with or without an operator, ranges, branches, aliases and stability flags. A word that is none of these is refused, and so is any word that begins with a hyphen. Anything else, such as a name that starts with a hyphen, makes the registry invalid, and the message names the entry and the field. The registry is cached on disk: @@ -404,6 +526,15 @@ The registry is cached on disk: - When the registry cannot be read, the copy is used whatever its age, and the command says so and how old it is. - With no copy and no registry, the command fails. +`drx add` reads four optional fields of a Drupal module in an entry, and works without them: + +| Field | What it holds | +| ---------- | ------------------------------------------------------------------------------------------------------------------------- | +| `core` | `true` for a module that is part of Drupal core | +| `composer` | The `package`, and a `constraint`, when the package is not `drupal/` | +| `patches` | Each a `description` and a `url`, with the `package` it applies to, its `issue` and the version it is fixed in as `until` | +| `setup` | Steps to do by hand once the module is enabled, each with a `title` and optionally a `command` and a `url` | + The copy is kept in `~/.cache/drx`, or under `XDG_CACHE_HOME` when that is set. `DRX_CACHE_DIR` names another directory. ## The user configuration @@ -435,7 +566,10 @@ The copy is kept in `~/.cache/drx`, or under `XDG_CACHE_HOME` when that is set. - The `split` and `workspace` layouts. `--layout` accepts them and fails with a message. - Sources other than `npm`. -- `drx module add`, `drx module remove` and `drx module configure`. The commands exist and fail with a message. +- `drx module configure`. The command exists and fails with a message. `drx add` does not ask for a module's options. +- Commands to list, check and relock patches. +- Running a module's setup steps. They are printed. +- Adding to a Nuxt 4 site through Nuxt's own CLI. `drx add` edits `nuxt.config` itself, for Nuxt 2 and later alike. - Making a wrapper component and upgrading a site. - Kinds other than `nuxt` and `drupal`. - `init --setup`, which would run the engine's steps. The flag exists and fails with a message, and `init` prints the steps. diff --git a/eslint.config.mjs b/eslint.config.mjs index ef18462..eef11f4 100644 --- a/eslint.config.mjs +++ b/eslint.config.mjs @@ -12,6 +12,7 @@ export default tseslint.config( 'reports/**', '.vale/**', 'packages/cli/starters/**', + 'packages/cli/test/fixtures/**', ], }, js.configs.recommended, diff --git a/knip.jsonc b/knip.jsonc index 2a2c97d..00b416e 100644 --- a/knip.jsonc +++ b/knip.jsonc @@ -1,5 +1,7 @@ { "$schema": "https://unpkg.com/knip@6/schema.json", + // Copies of real files from other projects, with those projects' imports. + "ignore": ["packages/cli/test/fixtures/**"], "workspaces": { ".": { "entry": ["scripts/*.mjs", "test/**/*.test.ts"], diff --git a/package-lock.json b/package-lock.json index 2fa3220..c9c9d73 100644 --- a/package-lock.json +++ b/package-lock.json @@ -63,7 +63,6 @@ "version": "7.29.14", "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.29.14.tgz", "integrity": "sha512-CXvKMFvM80ihI7Vox9jb+kQjnyjESQNPM+vB7U0Zz6TWuZA+Z/FL0QPMH300h33qJtIx+REeBhXqWOPW48TcAQ==", - "devOptional": true, "license": "MIT", "engines": { "node": ">=6.9.0" @@ -73,7 +72,6 @@ "version": "7.29.7", "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.29.7.tgz", "integrity": "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg==", - "devOptional": true, "license": "MIT", "engines": { "node": ">=6.9.0" @@ -83,7 +81,6 @@ "version": "7.29.14", "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.29.14.tgz", "integrity": "sha512-VL220vXuyO2z3rNIQwY7ftj9UwpqOt+33sH+sBWkOekbsSR2g7EEMnOx24ZlCH0xOA3DM/33SifVFGbnJD8r/w==", - "devOptional": true, "license": "MIT", "dependencies": { "@babel/types": "^7.29.14" @@ -99,7 +96,6 @@ "version": "7.29.14", "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.29.14.tgz", "integrity": "sha512-UjI/dKmwJwT9pOszJitq2G6EObZPnsZUfdCr92z2TlF3EZK9J3EdfOKUrCzHl6wFthbzwhzl1Soc/UIwxRiq6w==", - "devOptional": true, "license": "MIT", "dependencies": { "@babel/helper-string-parser": "^7.29.14", @@ -5470,7 +5466,6 @@ "version": "0.5.5", "resolved": "https://registry.npmjs.org/magicast/-/magicast-0.5.5.tgz", "integrity": "sha512-UicdXN8zQ3JHlxVq+28afMXPr1z7WNY6+7EJnzTdQWkTAlMLF5fNCCKxJHBQwGaNGR11581EiQmQzx73+MvszA==", - "devOptional": true, "license": "MIT", "dependencies": { "@babel/parser": "^7.29.7", @@ -6936,7 +6931,6 @@ "version": "1.2.2", "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.2.tgz", "integrity": "sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==", - "devOptional": true, "license": "BSD-3-Clause", "engines": { "node": ">=0.10.0" @@ -7537,6 +7531,7 @@ "c12": "^3.3.4", "citty": "^0.2.2", "giget": "^3.3.1", + "magicast": "^0.5.5", "semver": "^7.8.6" }, "bin": { diff --git a/packages/cli/README.md b/packages/cli/README.md index 215d0ac..6d2752e 100644 --- a/packages/cli/README.md +++ b/packages/cli/README.md @@ -14,6 +14,7 @@ The binary is `drx`. Install the package in a project to use that name: `npm ins | `drx init [dir]` | Creates a site from a starter and records its layout in `drx.config.json` | | `drx info` | Prints the versions of the CLI, Node and the packages of each part | | `drx module list`, `search`, `info` | Lists, searches and shows the modules in the Druxt module registry | +| `drx add`, `drx remove` | Adds a module to the frontend and backend of a project, or removes it | The options, the registry format and the configuration files are in the [repository README](https://github.com/druxt/cli#readme). diff --git a/packages/cli/package.json b/packages/cli/package.json index 168d7cc..204b5d1 100644 --- a/packages/cli/package.json +++ b/packages/cli/package.json @@ -1,7 +1,7 @@ { "name": "@druxt/cli", "version": "0.0.0", - "description": "The Druxt command-line tool: create a site from a starter and report on it.", + "description": "Command-line tool for Druxt: create a site, add modules and manage a decoupled Drupal project.", "keywords": [ "druxt", "cli" @@ -46,6 +46,7 @@ "c12": "^3.3.4", "citty": "^0.2.2", "giget": "^3.3.1", + "magicast": "^0.5.5", "semver": "^7.8.6" } } diff --git a/packages/cli/src/adapters/adapter.ts b/packages/cli/src/adapters/adapter.ts index e645f6f..43f83d0 100644 --- a/packages/cli/src/adapters/adapter.ts +++ b/packages/cli/src/adapters/adapter.ts @@ -1,4 +1,5 @@ -import { DrxError } from '../errors.js' +import type { ToolResult } from '../exec.js' +import type { BackendModule } from '../modules/entry.js' import type { Role } from '../parts.js' /** One package a part depends on. */ @@ -34,7 +35,13 @@ export interface KindAdapter { * The values of one reach the tools of the part as arguments, so each is * checked by its pattern where it is read, before any command is built. */ - moduleProblem?(module: { name: string }): FieldProblem | undefined + moduleProblem?(module: BackendModule): FieldProblem | undefined + /** + * What is wrong with a record of what was done to a part of this kind, or + * undefined. A record is read from a file anybody may have written, and + * its values reach the same tools, so it is checked in the same way. + */ + recordProblem?(record: BackendRecord): FieldProblem | undefined /** The packages `info` reports for a part of this kind. */ packages(dir: string): Promise /** @@ -47,11 +54,182 @@ export interface KindAdapter { * asks for it nor has it installed. */ package(dir: string, name: string): Promise - /** Installs a module into the part and registers it. Not available yet. */ - addModule(dir: string, name: string): Promise + /** + * What adding a module to the part takes. Nothing is run or written here: + * the command prints the steps, and runs them unless it is a dry run. + */ + addModule(dir: string, request: AddRequest): Promise + /** What taking a module out of the part takes. */ + removeModule(dir: string, request: RemoveRequest): Promise +} + +/** A tool to run in the part, by the name the part's engine knows it by. */ +export interface ToolRun { + tool: string + args: string[] +} + +/** + * Asks a part something by running one of its tools, with arguments that + * change nothing. It is how a plan finds out what the part has now. + */ +export type Ask = (tool: string, args: string[]) => Promise + +/** + * A change to a file of the part. The new content is worked out from the + * file as it is when the step is taken, never from a copy read while + * planning: a tool or another module may have written to it in between. + */ +export interface FileEdit { + /** Relative to the part. */ + file: string + /** + * The content to write, given the content the file has now. It throws, + * with the reason, when the file no longer takes the change. + */ + change(source: string): string + /** What the edit does, as one line. */ + summary: string +} + +/** + * A file of the part to delete. Whether it goes is worked out from the file + * as it is when the step is taken, and a file that is not there is left out. + */ +export interface FileRemoval { + /** Relative to the part. */ + file: string + /** True when the file, with the content it has now, is to go. */ + when(source: string): boolean + /** What the step does, as one line. */ + summary: string +} + +/** + * One step of a change. For an add it carries what it will have done once + * it is taken, so the record can say what was done when a later step fails. + */ +export type ChangeStep = ( + { run: ToolRun } | { edit: FileEdit } | { remove: FileRemoval } +) & { + /** What the step does about the package of the module. */ + did?: Partial + /** What the step does to a backend part. */ + record?: BackendRecord +} + +/** What a module needs of a part. A kind reads the fields that apply to it. */ +export interface AddRequest { + /** The frontend package of the module. */ + package?: string + /** + * The root of the project the part is in. A part looks from there down to + * itself for what the whole project declares, such as its package manager. + */ + root?: string + /** The backend modules it needs, of this part's kind. */ + needs: BackendModule[] + /** False to leave the patches of those modules out. */ + patches: boolean + /** True when the registry marks core modules, so one not marked is not core. */ + registryStatesCore: boolean + /** + * Asks the part what it has. Undefined when the part is not run from this + * machine, so nothing in it can be looked at or changed from here. + */ + ask?: Ask +} + +export interface RemoveRequest { + package?: string + /** The root of the project the part is in. */ + root?: string + /** + * What an earlier add did to the package in this part. Undefined when the + * record does not say, as one written by an older version does not. + */ + did?: PackageRecord + /** What an earlier add did to this backend part, and is to be undone. */ + record?: BackendRecord + ask?: Ask +} + +/** What an add did about the package of a module in a frontend part. */ +export interface PackageRecord { + /** True when it installed the package, false when the part had it. */ + installed: boolean + /** True when it listed the package in the config, false when it was there. */ + listed: boolean + /** + * True when it could not write to the config, and left the line that lists + * the package to the user. Nothing then says whether the line is there. + */ + byHand?: boolean +} + +/** What an add did to a backend part, kept so a remove undoes that and no more. */ +export interface BackendRecord { + modules: { + name: string + /** The package that provides it. A module of core has none. */ + package?: string + /** True when the add enabled it, false when it was enabled already. */ + enabled: boolean + /** True when the add put its requirement in the manifest. */ + required: boolean + }[] + /** The patches it wrote, each with the module it was for. */ + patches: { + package: string + description: string + url: string + /** Absent in a record written before the module was kept. */ + module?: string + }[] + /** + * What the add put in the part for its patches to be applied with, when + * the part did not have it: `required` for the requirement on the tool that + * applies them, `allowed` for the permission that lets the tool run. Absent + * when the part had both. They go with the last patch of the part. + */ + patcher?: { required: boolean; allowed: boolean } +} + +/** The steps of a change to one part, in the order to take them. */ +export interface ModuleChange { + steps: ChangeStep[] + /** Reasons the change cannot be made. With any, no step is taken. */ + problems: string[] + warnings: string[] + /** What was found that needs no step. */ + notes: string[] + /** What the user has to do by hand, because the tool could not. */ + manual: string[] + /** What is left to do once the change is made. */ + after: string[] + /** For an add, what the steps do to the package of the module. */ + did?: PackageRecord + /** + * For an add, what the steps do to a backend part. For a remove, what + * they leave in it, which stays on the project's record. + */ + record?: BackendRecord + /** + * For an add, asks the part what the steps did once they have run, or + * once one of them has failed. It is given the record of the steps that + * were taken, and returns the record to keep. A backend may enable more + * than it was asked to, or less, and only then can that be seen. + */ + settle?: (done: BackendRecord) => Promise } -/** The `addModule` of every adapter until the `add` command exists. */ -export async function addModuleNotAvailable(): Promise { - throw new DrxError('not-available', 'Adding a module is not available yet.') +export function emptyChange(): ModuleChange { + return { + steps: [], + problems: [], + warnings: [], + notes: [], + manual: [], + after: [], + } } diff --git a/packages/cli/src/adapters/drupal-fields.ts b/packages/cli/src/adapters/drupal-fields.ts index 9058104..972aa47 100644 --- a/packages/cli/src/adapters/drupal-fields.ts +++ b/packages/cli/src/adapters/drupal-fields.ts @@ -1,4 +1,5 @@ -import type { FieldProblem } from './adapter.js' +import type { BackendModule } from '../modules/entry.js' +import type { BackendRecord, FieldProblem } from './adapter.js' /** A module's machine name, as the backend itself defines one. */ const MACHINE_NAME = /^[a-z][a-z0-9_]*$/ @@ -6,15 +7,147 @@ const MACHINE_NAME_RULE = 'must be a machine name: lower-case letters, digits and underscores, starting with a letter' /** - * What is wrong with a module the registry lists for this kind. Its name is - * handed to the backend's tools as an argument, so anything but a machine - * name is refused here: an option, a list, or a character a shell reads. + * The name of a Composer package, as Composer defines one: a vendor and a + * name in lower case, each of letters and digits joined by single + * separators. Written so that it is matched in linear time. */ -export function moduleProblem(module: { - name: string -}): FieldProblem | undefined { - if (!MACHINE_NAME.test(module.name)) { +const PACKAGE = + /^[a-z0-9]+(?:[_.-][a-z0-9]+)*\/[a-z0-9]+(?:(?:[_.]|-{1,2})[a-z0-9]+)*$/ +const PACKAGE_RULE = 'must be the name of a Composer package, as in vendor/name' + +/** No name or constraint is anywhere near this long. */ +const LENGTH = 200 + +/** + * The characters a Composer version constraint is made of: versions, + * operators, ranges, stability flags, branch names and references. + */ +const CONSTRAINT_CHARACTERS = /^[A-Za-z0-9 .*^~<>=!|,@#/_+-]+$/ +const CONSTRAINT_RULE = 'must be a Composer version constraint' + +/** The parts of one constraint, each written to be matched in linear time. */ +const OPERATOR = '(?:\\^|~|<=?|>=?|==?|!=|<>)' +const STABILITY = '(?:@(?:dev|alpha|beta|rc|stable))?' +const REFERENCE = '(?:#[A-Za-z0-9]+)?' +/** A version: digits or a wildcard, then parts joined by single separators. */ +const VERSION = `v?(?:[0-9]+|[*xX])(?:[.+_-][A-Za-z0-9*]+)*${STABILITY}${REFERENCE}` +const A_VERSION = new RegExp(`^${VERSION}$`, 'i') +const A_TERM = new RegExp(`^${OPERATOR}?${VERSION}$`, 'i') +const AN_OPERATOR = new RegExp(`^${OPERATOR}$`) +const A_BRANCH = new RegExp( + `^dev-[A-Za-z0-9][A-Za-z0-9._/+-]*${STABILITY}${REFERENCE}$`, + 'i' +) +const A_STABILITY = /^@(?:dev|alpha|beta|rc|stable)$/i + +/** + * True when the words are constraints that all have to hold, as Composer + * reads them between two `||`: a version with or without an operator, an + * operator and its version apart, a branch, a stability flag, a range as in + * `1.0 - 2.0`, or an alias as in `dev-main as 1.0.0`. A word that begins + * with a hyphen is none of them, so an option is never one. + */ +function allHold(words: string[]): boolean { + if (words.length === 0) return false + for (let index = 0; index < words.length;) { + const word = words[index] as string + const next = words[index + 1] ?? '' + if (AN_OPERATOR.test(word)) { + if (!A_VERSION.test(next)) return false + index += 2 + continue + } + const version = A_VERSION.test(word) + if (!version && !A_TERM.test(word)) { + if (!A_BRANCH.test(word) && !A_STABILITY.test(word)) return false + } + index += 1 + const joins = words[index] + if (joins !== '-' && joins !== 'as') continue + // A range is between two versions, and an alias names a version. + const from = joins === '-' ? version : version || A_BRANCH.test(word) + if (!from || !A_VERSION.test(words[index + 1] ?? '')) return false + index += 2 + } + return true +} + +/** + * True for a set of version constraints as Composer writes them: one or + * more groups joined by `||` or `|`, each of constraints joined by spaces or + * commas. It is handed to Composer as one argument after the name of the + * package, and checked here so that nothing but a constraint gets that far. + */ +function isConstraint(value: string): boolean { + if (!CONSTRAINT_CHARACTERS.test(value)) return false + if (value.includes('|||') || value.includes(',,')) return false + return value + .replaceAll('||', '|') + .split('|') + .every((group) => { + const trimmed = group.trim() + if (trimmed.startsWith(',') || trimmed.endsWith(',')) return false + return allHold( + trimmed + .replaceAll(',', ' ') + .split(' ') + .filter((word) => word !== '') + ) + }) +} + +const matches = (value: string, pattern: RegExp) => + value.length <= LENGTH && pattern.test(value) + +/** + * What is wrong with a module the registry lists for this kind. Its name, + * its package and its constraint are handed to the backend's tools as + * arguments, so anything but the form each has is refused here: an option, + * a list, or a character a shell reads. + */ +export function moduleProblem(module: BackendModule): FieldProblem | undefined { + if (!matches(module.name, MACHINE_NAME)) { return { field: 'name', must: MACHINE_NAME_RULE } } + const { composer } = module + if (composer && !matches(composer.package, PACKAGE)) { + return { field: 'composer.package', must: PACKAGE_RULE } + } + if ( + composer?.constraint !== undefined && + !(composer.constraint.length <= LENGTH && isConstraint(composer.constraint)) + ) { + return { field: 'composer.constraint', must: CONSTRAINT_RULE } + } + for (const [index, patch] of (module.patches ?? []).entries()) { + if (patch.package !== undefined && !matches(patch.package, PACKAGE)) { + return { field: `patches[${index}].package`, must: PACKAGE_RULE } + } + } + return undefined +} + +/** + * What is wrong with a record of what an add did to a part of this kind. + * The record is in a file of the project, which a clone brings with it, and + * a remove hands its names to the same tools. + */ +export function recordProblem(record: BackendRecord): FieldProblem | undefined { + for (const [index, module] of record.modules.entries()) { + if (!matches(module.name, MACHINE_NAME)) { + return { field: `modules[${index}].name`, must: MACHINE_NAME_RULE } + } + if (module.package !== undefined && !matches(module.package, PACKAGE)) { + return { field: `modules[${index}].package`, must: PACKAGE_RULE } + } + } + for (const [index, patch] of record.patches.entries()) { + if (!matches(patch.package, PACKAGE)) { + return { field: `patches[${index}].package`, must: PACKAGE_RULE } + } + if (patch.module !== undefined && !matches(patch.module, MACHINE_NAME)) { + return { field: `patches[${index}].module`, must: MACHINE_NAME_RULE } + } + } return undefined } diff --git a/packages/cli/src/adapters/drupal-modules.ts b/packages/cli/src/adapters/drupal-modules.ts new file mode 100644 index 0000000..58cc6c2 --- /dev/null +++ b/packages/cli/src/adapters/drupal-modules.ts @@ -0,0 +1,911 @@ +import { existsSync } from 'node:fs' +import { readFile } from 'node:fs/promises' +import { join, resolve, sep } from 'node:path' +import semver from 'semver' +import type { BackendModule } from '../modules/entry.js' +import { isRecord } from '../validate.js' +import { + emptyChange, + type AddRequest, + type Ask, + type BackendRecord, + type ModuleChange, + type RemoveRequest, +} from './adapter.js' + +/** The Composer plugin that applies patches, and the line the quickstart is on. */ +const PATCHES_PLUGIN = 'cweagans/composer-patches' +const PATCHES_PLUGIN_CONSTRAINT = '^2.0@beta' +const PATCHES_PLUGIN_MAJOR = 2 +/** Where the plugin keeps the patches it has resolved. */ +const LOCK_FILE = 'patches.lock.json' + +type Json = Record +type Patches = Record> + +interface Manifest { + json: Json + require: Record + patches: Patches +} + +async function readManifest(dir: string): Promise { + try { + const json: unknown = JSON.parse( + await readFile(join(dir, 'composer.json'), 'utf8') + ) + if (!isRecord(json)) return undefined + const extra = isRecord(json.extra) ? json.extra : {} + return { + json, + require: isRecord(json.require) ? json.require : {}, + patches: (isRecord(extra.patches) ? extra.patches : {}) as Patches, + } + } catch { + return undefined + } +} + +/** A manifest as text, with the indent and final newline its source had. */ +function write(source: string, json: Json): string { + const indent = /^([ \t]+)"/m.exec(source)?.[1] ?? ' ' + const text = JSON.stringify(json, null, indent) + return source.endsWith('\n') ? `${text}\n` : text +} + +/** The manifest a step finds when it runs, which may not be the one planned from. */ +function parseManifest(source: string): Json { + let json: unknown + try { + json = JSON.parse(source) + } catch { + json = undefined + } + if (!isRecord(json)) { + throw new Error('composer.json can no longer be read as a JSON object.') + } + return json +} + +const extraOf = (json: Json): Json => (isRecord(json.extra) ? json.extra : {}) + +/** A copy of the patches a manifest lists, by package and description. */ +function patchesOf(json: Json): Patches { + const { patches } = extraOf(json) + return isRecord(patches) ? (structuredClone(patches) as Patches) : {} +} + +type RecordedPatch = BackendRecord['patches'][number] + +/** + * The manifest with patches added, and the patches plugin allowed when + * `allow` says so. It is made from the manifest as it is now, so what a tool + * or another module wrote since the plan was made is kept. + * + * `allow-plugins` is changed only where Composer itself would write to it: + * a list gets one key, and a site with no list gets one. `true` already + * allows every plugin and stays as it is. + */ +function withPatches( + source: string, + wanted: RecordedPatch[], + allow: boolean +): string { + const json = parseManifest(source) + const patches = patchesOf(json) + for (const patch of wanted) { + const own = patches[patch.package]?.[patch.description] + if (own !== undefined && own !== patch.url) { + throw new Error( + `composer.json now has a patch for ${patch.package} named "${patch.description}", from ${own}.` + ) + } + patches[patch.package] = { + ...patches[patch.package], + [patch.description]: patch.url, + } + } + json.extra = { ...extraOf(json), patches } + if (allow) { + const config = isRecord(json.config) ? json.config : {} + const allowed = config['allow-plugins'] + const none = Array.isArray(allowed) && allowed.length === 0 + if (allowed === undefined || none || isRecord(allowed)) { + json.config = { + ...config, + 'allow-plugins': { + ...(isRecord(allowed) ? allowed : {}), + [PATCHES_PLUGIN]: true, + }, + } + } + } + return write(source, json) +} + +/** True when a manifest has to gain a key for the patches plugin to run. */ +function needsAllowing(json: Json): boolean { + const allowed = isRecord(json.config) + ? json.config['allow-plugins'] + : undefined + if (allowed === undefined) return true + if (Array.isArray(allowed)) return allowed.length === 0 + return isRecord(allowed) && !(PATCHES_PLUGIN in allowed) +} + +/** + * The manifest without the key that lets the patches plugin run, and + * without an `allow-plugins` or a `config` that leaves empty. It stays as it + * is while the manifest lists a patch, which the plugin is there to apply. + */ +function withoutAllowing(source: string): string { + const json = parseManifest(source) + const config = isRecord(json.config) ? json.config : {} + const allowed = config['allow-plugins'] + if (!isRecord(allowed) || allowed[PATCHES_PLUGIN] !== true) return source + if (Object.keys(patchesOf(json)).length > 0) return source + const rest = { ...allowed } + delete rest[PATCHES_PLUGIN] + const next = { ...config } + if (Object.keys(rest).length === 0) delete next['allow-plugins'] + else next['allow-plugins'] = rest + if (Object.keys(next).length === 0) delete json.config + else json.config = next + return write(source, json) +} + +/** True for a lock file of the plugin that holds no patch. */ +function locksNothing(source: string): boolean { + try { + const lock: unknown = JSON.parse(source) + if (!isRecord(lock)) return false + const { patches } = lock + if (Array.isArray(patches)) return patches.length === 0 + return isRecord(patches) && Object.keys(patches).length === 0 + } catch { + return false + } +} + +/** + * The URLs of the patches the plugin has locked, by package. A patch is + * applied from the lock file, so one that is only in the manifest is not + * applied to anything yet. + */ +async function lockedPatches(dir: string): Promise> { + const found = new Map() + try { + const lock: unknown = JSON.parse( + await readFile(join(dir, LOCK_FILE), 'utf8') + ) + const patches = isRecord(lock) && isRecord(lock.patches) ? lock.patches : {} + for (const [name, list] of Object.entries(patches)) { + found.set( + name, + (Array.isArray(list) ? list : []).flatMap((patch: unknown) => + isRecord(patch) && typeof patch.url === 'string' ? [patch.url] : [] + ) + ) + } + } catch { + // No lock file, or one that cannot be read: nothing is locked. + } + return found +} + +/** + * The manifest without the patches an add wrote. A patch is taken out only + * while it is still the one that was written: the same description with + * another URL is the site's own by now. A key this leaves empty goes too. + */ +function withoutPatches(source: string, leaving: RecordedPatch[]): string { + const json = parseManifest(source) + const patches = patchesOf(json) + let changed = false + for (const patch of leaving) { + const forPackage = patches[patch.package] + if (forPackage?.[patch.description] !== patch.url) continue + delete forPackage[patch.description] + if (Object.keys(forPackage).length === 0) delete patches[patch.package] + changed = true + } + if (!changed) return source + const extra = { ...extraOf(json) } + if (Object.keys(patches).length === 0) delete extra.patches + else extra.patches = patches + if (Object.keys(extra).length === 0) delete json.extra + else json.extra = extra + return write(source, json) +} + +/** The web root the site names, which is where Drush counts paths from. */ +function webRootDir(dir: string, manifest: Manifest | undefined): string { + const extra = isRecord(manifest?.json.extra) ? manifest.json.extra : {} + const scaffold = extra['drupal-scaffold'] + const locations = isRecord(scaffold) ? scaffold.locations : undefined + const webRoot = isRecord(locations) ? locations['web-root'] : undefined + return resolve(dir, typeof webRoot === 'string' ? webRoot : 'web') +} + +/** The directory core keeps its modules in, under the web root. */ +const coreModulesDir = (dir: string, manifest: Manifest) => + join(webRootDir(dir, manifest), 'core', 'modules') + +interface Installed { + version: string + /** The names of the packages it requires. */ + requires: string[] + /** The directory its files are in, when Composer recorded one. */ + path?: string + /** + * The URLs of the patches the package says were applied to it. Version 1 + * of the plugin wrote them there. Version 2 keeps no such record. + */ + patched: string[] +} + +/** Each package Composer has installed, with its version and what it requires. */ +async function installedPackages(dir: string): Promise> { + const found = new Map() + try { + const installed: unknown = JSON.parse( + await readFile(join(dir, 'vendor', 'composer', 'installed.json'), 'utf8') + ) + const packages = isRecord(installed) ? installed.packages : undefined + for (const entry of Array.isArray(packages) ? packages : []) { + if (isRecord(entry) && typeof entry.name === 'string') { + const path = entry['install-path'] + const extra = isRecord(entry.extra) ? entry.extra : {} + const applied = extra.patches_applied + found.set(entry.name, { + version: String(entry.version), + requires: Object.keys(isRecord(entry.require) ? entry.require : {}), + patched: Object.values(isRecord(applied) ? applied : {}).filter( + (url) => typeof url === 'string' + ), + // Composer writes it from the directory the file itself is in. + ...(typeof path === 'string' + ? { path: resolve(dir, 'vendor', 'composer', path) } + : {}), + }) + } + } + } catch { + // Nothing is installed yet. + } + return found +} + +/** + * The modules the site has enabled, each with its path from the web root, + * as Drush lists them. Undefined when it cannot be asked: no database yet, + * or the backend is not running. + */ +async function enabledModules( + ask: Ask +): Promise | undefined> { + const result = await ask('drush', [ + 'pm:list', + '--type=module', + '--status=enabled', + '--fields=name,path', + '--format=json', + ]) + if (result.code !== 0) return undefined + try { + // Drush may print a notice before the document. + const list: unknown = JSON.parse( + result.output.slice(result.output.indexOf('{')) + ) + if (!isRecord(list)) return undefined + return new Map( + Object.entries(list).map(([name, row]) => [ + name, + isRecord(row) && typeof row.path === 'string' ? row.path : '', + ]) + ) + } catch { + return undefined + } +} + +/** + * What uninstalling a module would uninstall: the module and every enabled + * module that depends on it. Drush says so when it is asked to simulate, and + * uninstalls nothing. `absent` when the module is not enabled, and undefined + * when Drush did not answer in a form that can be read. + */ +async function uninstallList( + ask: Ask, + name: string +): Promise { + const result = await ask('drush', ['pm:uninstall', '--simulate', '--', name]) + if (result.code !== 0) { + return /not installed/.test(result.output) ? 'absent' : undefined + } + const listed = /will be uninstalled: *([^\n]+)/.exec(result.output)?.[1] + const names = listed?.split(',').map((item) => item.trim()) ?? [] + return names.includes(name) ? names : undefined +} + +const packageOf = (need: BackendModule) => + need.composer?.package ?? `drupal/${need.name}` + +/** + * Whether a module is core's own or a package to require. + * + * The registry's word is taken first. A registry that marks core modules + * marks all of them, so in one that does, a module not marked is a package. A + * package the site already requires is plainly a package. Past that the only + * honest source is the core the site has installed, and without it the + * answer is `unknown`. There is no list of core modules here to go stale. + */ +function origin( + need: BackendModule, + request: AddRequest, + manifest: Manifest, + coreDir: string +): 'core' | 'package' | 'unknown' { + if (need.core) return 'core' + if (need.core === false) return 'package' + if (request.registryStatesCore || need.composer) return 'package' + if (packageOf(need) in manifest.require) return 'package' + if (!existsSync(coreDir)) return 'unknown' + return existsSync(join(coreDir, need.name)) ? 'core' : 'package' +} + +const list = (names: string[]) => + names.length < 2 + ? names.join('') + : `${names.slice(0, -1).join(', ')} or ${names.at(-1)}` + +/** The steps that add the backend modules a Druxt module needs. */ +export async function planBackendAdd( + dir: string, + request: AddRequest +): Promise { + const change = emptyChange() + const { needs, ask } = request + if (needs.length === 0) return change + + // A backend that is run somewhere else may not have its files here. Its + // lines are printed for whoever is there, so an empty manifest will do. + const manifest = + (await readManifest(dir)) ?? + (ask ? undefined : { json: {}, require: {}, patches: {} }) + if (!manifest) { + change.problems.push( + `There is no composer.json to add ${needs.map(({ name }) => name).join(', ')} to.` + ) + return change + } + + const coreDir = coreModulesDir(dir, manifest) + const installed = await installedPackages(dir) + const locked = await lockedPatches(dir) + const enabled = ask ? await enabledModules(ask) : undefined + const record: BackendRecord = { modules: [], patches: [] } + const toRequire: string[] = [] + const toEnable: string[] = [] + const unsure: string[] = [] + const patches: Patches = structuredClone(manifest.patches) + let repatch = false + /** True when the manifest lists a patch the lock file does not have. */ + let relock = false + /** The packages to install again, for a locked patch to be applied. */ + const reapply = new Set() + /** The first patch found in the manifest and not yet applied. */ + let unfinished: string | undefined + + for (const need of needs) { + const pkg = packageOf(need) + let from = origin(need, request, manifest, coreDir) + if (from === 'unknown') { + if (ask) { + change.problems.push( + `Cannot tell whether ${need.name} is part of core or a package to require: the module registry does not say, and core is not installed in this part to look in. Install the dependencies of the backend, then run this again.` + ) + continue + } + // Nothing here can settle it, so the line is printed and the doubt said. + unsure.push(need.name) + from = 'package' + } + let required = false + if (from === 'package') { + if (pkg in manifest.require) { + change.notes.push(`${pkg} is already required in composer.json.`) + } else { + toRequire.push( + need.composer?.constraint ? `${pkg}:${need.composer.constraint}` : pkg + ) + required = true + } + } + + // Only a module this run enables is one a later remove may uninstall. + const wasEnabled = enabled?.has(need.name) === true + if (wasEnabled) change.notes.push(`${need.name} is already enabled.`) + else toEnable.push(need.name) + const enables = enabled !== undefined && !wasEnabled + if (required || enables) { + record.modules.push({ + name: need.name, + ...(from === 'package' ? { package: pkg } : {}), + enabled: enables, + required, + }) + } + + for (const patch of need.patches ?? []) { + const target = patch.package ?? pkg + if (!request.patches) { + change.warnings.push( + `The patch "${patch.description}" for ${target} was not applied. ${need.label} may not work without it.` + ) + continue + } + if (!patch.url.startsWith('https://')) { + change.problems.push( + `The patch "${patch.description}" that ${need.name} needs is at ${patch.url}, and Composer only fetches a patch over https. Pass --no-patches to add the module without it.` + ) + continue + } + const has = installed.get(target)?.version + const fixed = patch.until ? semver.coerce(patch.until) : null + const version = has ? semver.coerce(has) : null + if (fixed && version && semver.gte(version, fixed)) { + change.notes.push( + `The patch "${patch.description}" is not needed: ${target} ${has} has the fix, which came in ${patch.until}.` + ) + continue + } + if (Object.values(patches[target] ?? {}).includes(patch.url)) { + // The manifest only says a patch is wanted. Whether it is applied + // is for the lock file and the installed package to say, and a run + // that stopped part way leaves the manifest ahead of both. + const there = installed.get(target) + if (!locked.get(target)?.includes(patch.url)) { + relock = true + if (there) repatch = true + change.notes.push( + `The patch "${patch.description}" is in composer.json and not in ${LOCK_FILE}, so the patches are locked again.` + ) + } else if (there && !there.patched.includes(patch.url)) { + reapply.add(target) + change.notes.push( + `The patch "${patch.description}" is locked, and nothing on the site says ${target} was installed with it, so the package is installed again.` + ) + } else { + change.notes.push( + `The patch "${patch.description}" is already in composer.json.` + ) + continue + } + unfinished ??= patch.description + continue + } + // The same name with another URL is a patch the site's owner wrote. + const own = patches[target]?.[patch.description] + if (own !== undefined) { + change.problems.push( + `composer.json already has a patch for ${target} named "${patch.description}", from ${own}. It is the site's own, and drx add does not replace it. Rename it, or pass --no-patches to add the module without the patch from the registry.` + ) + continue + } + patches[target] = { ...patches[target], [patch.description]: patch.url } + record.patches.push({ + package: target, + description: patch.description, + url: patch.url, + module: need.name, + }) + change.notes.push( + `Patch for ${target}: ${patch.description}${patch.issue ? ` (${patch.issue})` : ''}` + ) + // A package that is installed has to be patched in place, whether the + // site requires it itself or another package brought it in. One that + // is not is patched as it is installed. + if (installed.has(target)) repatch = true + } + + for (const step of need.setup ?? []) { + change.after.push(`${need.label}: ${step.title}`) + if (step.command) change.after.push(` ${step.command}`) + if (step.url) change.after.push(` ${step.url}`) + } + } + + // A patch is written for the plugin that applies it, in the version that + // keeps a lock file, and only on a site that lets the plugin run. + const hasPlugin = PATCHES_PLUGIN in manifest.require + const config = isRecord(manifest.json.config) ? manifest.json.config : {} + const allowed = config['allow-plugins'] + const first = record.patches[0]?.description ?? unfinished + if (first !== undefined) { + const without = 'pass --no-patches to add the module without the patch' + const plugin = installed.get(PATCHES_PLUGIN)?.version + const major = plugin ? semver.coerce(plugin)?.major : undefined + if (major !== undefined && major < PATCHES_PLUGIN_MAJOR) { + change.problems.push( + `This site has ${PATCHES_PLUGIN} ${plugin}, and the patch "${first}" is written for version ${PATCHES_PLUGIN_MAJOR} of the plugin, which keeps patches in a lock file. Update the plugin to version ${PATCHES_PLUGIN_MAJOR}, or ${without}.` + ) + } + if (allowed === false) { + change.problems.push( + `composer.json sets allow-plugins to false, which turns every Composer plugin off, and the patch "${first}" needs ${PATCHES_PLUGIN}. Allow the plugin there, or ${without}.` + ) + } else if (isRecord(allowed) && allowed[PATCHES_PLUGIN] === false) { + change.problems.push( + `composer.json turns ${PATCHES_PLUGIN} off under allow-plugins, and the patch "${first}" needs it. Allow the plugin there, or ${without}.` + ) + } + } + + if (change.problems.length > 0) return change + if (ask && !enabled && toEnable.length > 0) { + change.warnings.push( + `The backend could not say which modules are enabled. ${toEnable.join(', ')} will be enabled, and drx remove will leave ${toEnable.length === 1 ? 'it' : 'them'} enabled, since ${toEnable.length === 1 ? 'it' : 'they'} may have been before.` + ) + } + if (unsure.length > 0) { + change.manual.push( + `The module registry does not say whether ${list(unsure)} is part of core. Leave a module that is out of the composer require line: only the enable line applies to it.` + ) + } + // Each step carries what it will have done, so a run that stops part way + // can still say what it did. + const tool = (name: string) => (args: string[], done?: BackendRecord) => + change.steps.push({ + run: { tool: name, args }, + ...(done ? { record: done } : {}), + }) + const composer = tool('composer') + const drush = tool('drush') + + // The plugin is added to a site without it, and what was added is kept: + // a remove takes out the requirement and the permission it put there, and + // never one the site had. + const patching = first !== undefined + const allow = patching && !hasPlugin && needsAllowing(manifest.json) + if (patching && !hasPlugin) + record.patcher = { required: true, allowed: allow } + const writes = record.patches.length + if (writes > 0 || allow) { + // Allowed before it is required, or Composer stops to ask. + change.steps.push({ + edit: { + file: 'composer.json', + change: (source) => withPatches(source, record.patches, !hasPlugin), + summary: + writes > 0 + ? `Add ${writes} patch${writes === 1 ? '' : 'es'} to composer.json` + : `Allow ${PATCHES_PLUGIN} in composer.json`, + }, + record: { + modules: [], + patches: record.patches, + ...(allow ? { patcher: { required: false, allowed: true } } : {}), + }, + }) + } + if (patching && !hasPlugin) { + composer( + ['require', '--', `${PATCHES_PLUGIN}:${PATCHES_PLUGIN_CONSTRAINT}`], + { + modules: [], + patches: [], + patcher: { required: true, allowed: false }, + } + ) + } + if (writes > 0 || relock) composer(['patches-relock']) + if (toRequire.length > 0) { + composer(['require', '--', ...toRequire], { + modules: record.modules + .filter((module) => module.required) + .map((module) => ({ ...module, enabled: false })), + patches: [], + }) + } + // Every patched package is installed again once the patches are locked + // anew. Otherwise only one that a locked patch may not be applied to. + if ((writes > 0 || relock) && repatch) composer(['patches-repatch']) + else if (reapply.size > 0) composer(['reinstall', '--', ...reapply]) + // The backend keeps its container by the set of packages installed, so + // after a change to that set it may answer from one built for another. + if ((patching && !hasPlugin) || toRequire.length > 0) drush(['cr']) + if (toEnable.length > 0) { + drush(['en', '-y', '--', ...toEnable], { + modules: record.modules + .filter((module) => module.enabled) + .map((module) => ({ ...module, required: false })), + patches: [], + }) + } + + change.record = record + if (ask && enabled) { + // Drush enables what a module depends on along with it, and a run that + // failed may have enabled some of what it was asked to. Either is seen + // only by asking again. What was required is what the steps taken say. + change.settle = async (done) => { + const after = await enabledModules(ask) + if (!after) return done + const came = [...after.keys()].filter((name) => !enabled.has(name)) + const modules = record.modules + .map((module) => ({ + ...module, + enabled: came.includes(module.name), + required: done.modules.some( + (other) => other.name === module.name && other.required + ), + })) + .filter((module) => module.enabled || module.required) + for (const name of came) { + if (!modules.some((module) => module.name === name)) { + modules.push({ name, enabled: true, required: false }) + } + } + return { ...done, modules } + } + } + return change +} + +/** + * The steps that undo what an add did to the part: the modules it enabled, + * the requirements it added and the patches it wrote, and nothing the site's + * owner put there. + * + * A module is uninstalled only once the site has said that nothing enabled + * depends on it. Drush uninstalls the dependents of a module along with it + * and asks first, and with nobody to ask it takes the answer to be yes. So + * a module with a dependent stays, with its requirement and its patches, and + * so does one the site cannot be asked about. + */ +export async function planBackendRemove( + dir: string, + request: RemoveRequest +): Promise { + const change = emptyChange() + const { record, ask } = request + if (!record) return change + + let listed: Map | undefined | null = null + const enabledNow = async () => { + if (listed === null) listed = ask ? await enabledModules(ask) : undefined + return listed + } + + // Whether a module is enabled is asked twice, of the list of enabled + // modules and of a simulated uninstall. The first reads the site's + // configuration and the second its container, which may have been built + // for another set of packages. Only an answer both give is acted on. + const stays = new Set() + const dependents = new Map() + for (const { name, package: pkg, enabled, required } of record.modules) { + if (!enabled) continue + const found = ask ? await uninstallList(ask, name) : undefined + const byHand = `drush pm:uninstall ${name}${required && pkg ? `, then composer remove ${pkg}` : ''}` + if (!found) { + stays.add(name) + change.manual.push( + `The backend could not say what depends on ${name}, so it was left enabled. Once nothing does: ${byHand}` + ) + continue + } + const list = await enabledNow() + if (list?.has(name) === (found !== 'absent')) { + if (found === 'absent') { + change.notes.push(`${name} is not enabled, so it is not uninstalled.`) + } else { + dependents.set(name, found) + } + continue + } + stays.add(name) + change.manual.push( + `The backend ${list ? 'gave two answers about' : 'could not say'} whether ${name} is enabled, so it was left as it is. Rebuild its caches with drush cr and run this again, or once nothing depends on it: ${byHand}` + ) + } + // A module goes only when everything that would go with it is going too. + let going = [...dependents.keys()] + for (let settled = false; !settled;) { + settled = true + for (const name of going) { + const held = (dependents.get(name) ?? []).filter( + (other) => !going.includes(other) + ) + if (held.length === 0) continue + going = going.filter((other) => other !== name) + stays.add(name) + change.notes.push( + `${name} stays enabled: ${held.join(', ')} depend${held.length === 1 ? 's' : ''} on it.` + ) + settled = false + break + } + } + + // A requirement goes with its module. One whose module the site had + // enabled before goes only while another package still brings the module + // in, or once the module is off: its files must not go from under it. + const manifest = await readManifest(dir) + const installed = await installedPackages(dir) + const removing = record.modules.filter( + (module) => module.required && module.package && !stays.has(module.name) + ) + const packages = new Set(removing.map((module) => module.package as string)) + const heldByAnother = (pkg: string) => + [...installed].some( + ([name, { requires }]) => !packages.has(name) && requires.includes(pkg) + ) + const unowned = removing.filter( + (module) => !module.enabled && !heldByAnother(module.package as string) + ) + for (const { name, package: pkg } of unowned) { + const enabled = await enabledNow() + // Off for the list and for a simulated uninstall, or it stays. + const off = ask && enabled && !enabled.has(name) + if (off && (await uninstallList(ask, name)) === 'absent') continue + stays.add(name) + packages.delete(pkg as string) + change.notes.push( + `${pkg} stays required: ${name} was enabled before drx add, and nothing else brings it in.` + ) + } + const kept = [...packages].filter(heldByAnother) + let free = [...packages].filter((pkg) => !kept.includes(pkg)) + + // A package whose files are about to go must hold no module that is still + // enabled: one the user enabled since, or one that came up with another. + const holding = new Set() + const root = webRootDir(dir, manifest) + for (const pkg of free) { + const base = installed.get(pkg)?.path + const enabled = base ? await enabledNow() : undefined + if (!base || !enabled) continue + const held = [...enabled] + .filter(([name, path]) => { + const at = resolve(root, path) + return ( + !going.includes(name) && (at === base || at.startsWith(base + sep)) + ) + }) + .map(([name]) => name) + if (held.length === 0) continue + holding.add(pkg) + change.notes.push( + `${pkg} stays required: ${held.join(', ')} ${held.length === 1 ? 'is' : 'are'} enabled, and ${held.length === 1 ? 'its' : 'their'} files are in that package.` + ) + } + free = free.filter((pkg) => !holding.has(pkg)) + /** The modules whose requirement stays though they are uninstalled. */ + const required = record.modules.filter( + (module) => + !stays.has(module.name) && module.package && holding.has(module.package) + ) + const keeps = (name: string) => + stays.has(name) || required.some((module) => module.name === name) + + if (going.length > 0) { + // -y answers a question that has been asked above, of each module. + change.steps.push({ + run: { tool: 'drush', args: ['pmu', '-y', '--', ...going] }, + }) + } + + // A patch goes with the requirement of the module it was written for. A + // record that does not say which that was keeps every patch while any + // module stays. + const leaving = record.patches.filter((patch) => + patch.module ? !keeps(patch.module) : stays.size + required.length === 0 + ) + const unpatched = new Set() + /** True when the manifest is left with no patch for the plugin to apply. */ + let noPatchLeft = false + if (manifest) { + const patches: Patches = structuredClone(manifest.patches) + for (const patch of leaving) { + const forPackage = patches[patch.package] + if (forPackage?.[patch.description] !== patch.url) continue + delete forPackage[patch.description] + if (Object.keys(forPackage).length === 0) delete patches[patch.package] + unpatched.add(patch.package) + } + noPatchLeft = Object.keys(patches).length === 0 + if (unpatched.size > 0) { + const count = leaving.filter((patch) => + unpatched.has(patch.package) + ).length + change.steps.push({ + edit: { + file: 'composer.json', + change: (source) => withoutPatches(source, leaving), + summary: `Remove ${count} patch${count === 1 ? '' : 'es'} from composer.json`, + }, + }) + } + } + + // The plugin an add put there goes with the last patch of the site, and + // so does the permission the add gave it. Neither goes while the record + // does not say the add put it there, or while a patch is left. + const { patcher } = record + const done = patcher !== undefined && manifest !== undefined && noPatchLeft + const dropPlugin = + done && patcher.required && PATCHES_PLUGIN in manifest.require + const shared = dropPlugin && heldByAnother(PATCHES_PLUGIN) + + const run = (tool: string, ...args: string[]) => + change.steps.push({ run: { tool, args } }) + const composer = (...args: string[]) => run('composer', ...args) + // Composer's remove fails on a package another one still requires, after + // it has taken the requirement out. So that one is only taken out of the + // manifest. The rest are removed without letting Composer update what + // they depended on, which is every package of core. + const held = [...kept, ...(shared ? [PATCHES_PLUGIN] : [])] + if (held.length > 0) composer('remove', '--no-update', '--', ...held) + if (free.length > 0) { + composer('remove', '--no-update-with-dependencies', '--', ...free) + } else if (held.length > 0) { + composer('update', '--lock') + } + if (unpatched.size > 0) { + composer('patches-relock') + // A package that stays installed still has the patch applied to it. + const still = [...unpatched].filter( + (pkg) => installed.has(pkg) && !free.includes(pkg) + ) + if (still.length > 0) composer('reinstall', '--', ...still) + } + // With what it depends on, which nothing else of the site uses. + if (dropPlugin && !shared) composer('remove', '--', PATCHES_PLUGIN) + const config = isRecord(manifest?.json.config) ? manifest.json.config : {} + const allowed = config['allow-plugins'] + if ( + done && + patcher.allowed && + isRecord(allowed) && + allowed[PATCHES_PLUGIN] === true + ) { + // After the plugin has gone: Composer stops one that is not allowed. + change.steps.push({ + edit: { + file: 'composer.json', + change: withoutAllowing, + summary: `Remove ${PATCHES_PLUGIN} from allow-plugins in composer.json`, + }, + }) + } + if (dropPlugin && !shared) { + // The plugin's own file, which nothing reads once the plugin has gone. + change.steps.push({ + remove: { + file: LOCK_FILE, + when: locksNothing, + summary: `Delete ${LOCK_FILE}`, + }, + }) + } + // The backend keeps its container by the set of packages installed. A set + // it has had before brings back the container built for it then, with the + // modules that were enabled then. + const fewer = free.length > 0 || (dropPlugin && !shared) + if (fewer && (!ask || (await enabledNow()))) run('drush', 'cr') + + const left: BackendRecord = { + modules: [ + ...record.modules.filter(({ name }) => stays.has(name)), + // Uninstalled by the steps above, so only the requirement is left. + ...required.map((module) => ({ ...module, enabled: false })), + ], + patches: record.patches.filter((patch) => !leaving.includes(patch)), + ...(patcher && !done ? { patcher } : {}), + } + if (left.modules.length + left.patches.length > 0 || left.patcher) { + change.record = left + } + return change +} diff --git a/packages/cli/src/adapters/drupal.ts b/packages/cli/src/adapters/drupal.ts index 66b22f1..3b9bd38 100644 --- a/packages/cli/src/adapters/drupal.ts +++ b/packages/cli/src/adapters/drupal.ts @@ -1,11 +1,8 @@ import { join } from 'node:path' import { isRecord } from '../validate.js' -import { - addModuleNotAvailable, - type KindAdapter, - type PackageVersion, -} from './adapter.js' -import { moduleProblem } from './drupal-fields.js' +import type { KindAdapter, PackageVersion } from './adapter.js' +import { moduleProblem, recordProblem } from './drupal-fields.js' +import { planBackendAdd, planBackendRemove } from './drupal-modules.js' import { readJsonObject, stringMap } from './read-json.js' /** Any of these in `require` makes a Composer project a Drupal site. */ @@ -46,6 +43,7 @@ export const drupalAdapter: KindAdapter = { }, moduleProblem, + recordProblem, async packages(dir) { const requires = await required(dir) @@ -63,5 +61,6 @@ export const drupalAdapter: KindAdapter = { druxt: async () => undefined, package: async () => undefined, - addModule: addModuleNotAvailable, + addModule: planBackendAdd, + removeModule: planBackendRemove, } diff --git a/packages/cli/src/adapters/nuxt-config.ts b/packages/cli/src/adapters/nuxt-config.ts new file mode 100644 index 0000000..cb422b4 --- /dev/null +++ b/packages/cli/src/adapters/nuxt-config.ts @@ -0,0 +1,137 @@ +import { generateCode, parseModule } from 'magicast' +import { getDefaultExportOptions } from 'magicast/helpers' + +/** The key Druxt modules are listed under, in Nuxt 2 and later alike. */ +const KEY = 'modules' + +/** The result of trying to change the modules list of a config. */ +export type ConfigEdit = + | { kind: 'changed'; content: string } + | { kind: 'unchanged' } + /** The file is not a shape that can be edited without guessing. */ + | { kind: 'unsafe' } + +/** The name of one entry of the list: a string, or the first of an array. */ +function entryName(entry: unknown): string | undefined { + if (typeof entry === 'string') return entry + if ( + Array.isArray(entry) || + (entry as { $type?: string })?.$type === 'array' + ) { + const first = (entry as unknown[])[0] + return typeof first === 'string' ? first : undefined + } + return undefined +} + +/** The names in the modules list of a config, or undefined when it has none. */ +function names(source: string): (string | undefined)[] | undefined { + try { + const list = getDefaultExportOptions(parseModule(source))?.[KEY] + return list?.$type === 'array' ? [...list].map(entryName) : undefined + } catch { + return undefined + } +} + +const SPACE = /[ \t]/ + +/** + * The source with one element of an array taken out, along with its comma + * and the line it had to itself. Undefined when the parser gave no positions. + */ +function withoutElement( + source: string, + array: unknown, + index: number +): string | undefined { + const elements = (array as { elements?: { start?: number; end?: number }[] }) + .elements + const element = elements?.[index] + if (typeof element?.start !== 'number' || typeof element.end !== 'number') { + return undefined + } + let { start, end } = element + let after = end + while (/\s/.test(source[after] ?? '')) after += 1 + + if (source[after] !== ',') { + // The last element: the comma before it goes, when there is one. + let before = start + while (before > 0 && /\s/.test(source[before - 1] ?? '')) before -= 1 + if (source[before - 1] === ',') start = before - 1 + return source.slice(0, start) + source.slice(end) + } + + end = after + 1 + let lineStart = start + while (lineStart > 0 && SPACE.test(source[lineStart - 1] ?? '')) { + lineStart -= 1 + } + let lineEnd = end + while (SPACE.test(source[lineEnd] ?? '')) lineEnd += 1 + const ownLine = + (lineStart === 0 || source[lineStart - 1] === '\n') && + (source[lineEnd] === '\n' || source.startsWith('\r\n', lineEnd)) + if (ownLine) { + return ( + source.slice(0, lineStart) + + source.slice(lineEnd + (source[lineEnd] === '\r' ? 2 : 1)) + ) + } + // Written on one line with its neighbours. + return source.slice(0, start) + source.slice(lineEnd) +} + +/** + * Adds a module to, or removes it from, the `modules` array of a Nuxt + * config, keeping the rest of the file as it is written. + * + * It edits a config that exports an object, or a call such as + * `defineNuxtConfig` with one, whose `modules` is an array written out in + * the file. Anything else, such as a function or a list held in a variable, + * is reported as unsafe and left for a person. + */ +export function editModules( + source: string, + name: string, + action: 'add' | 'remove' +): ConfigEdit { + try { + const module = parseModule(source) + const config = getDefaultExportOptions(module) + if (config?.$type !== 'object') return { kind: 'unsafe' } + + const list = config[KEY] + if (list === undefined) { + if (action === 'remove') return { kind: 'unchanged' } + config[KEY] = [name] + } else { + if (list.$type !== 'array') return { kind: 'unsafe' } + const index = [...list].findIndex((entry) => entryName(entry) === name) + if (action === 'add') { + if (index !== -1) return { kind: 'unchanged' } + list.push(name) + } else { + if (index === -1) return { kind: 'unchanged' } + // The printer rewrites a whole array it has taken an entry out of. + // Cutting the entry out of the text leaves the rest as written. + const cut = withoutElement(source, list.$ast, index) + if (cut !== undefined && names(cut)?.includes(name) === false) { + return { kind: 'changed', content: cut } + } + list.splice(index, 1) + } + } + + const { code } = generateCode(module) + // The printer drops the newline a file ends with. + return { + kind: 'changed', + content: + source.endsWith('\n') && !code.endsWith('\n') ? `${code}\n` : code, + } + } catch { + return { kind: 'unsafe' } + } +} diff --git a/packages/cli/src/adapters/nuxt.ts b/packages/cli/src/adapters/nuxt.ts index da828b3..07cc492 100644 --- a/packages/cli/src/adapters/nuxt.ts +++ b/packages/cli/src/adapters/nuxt.ts @@ -1,10 +1,14 @@ import { existsSync } from 'node:fs' -import { dirname, join, resolve } from 'node:path' +import { readFile } from 'node:fs/promises' +import { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path' import { - addModuleNotAvailable, + emptyChange, type KindAdapter, + type ModuleChange, + type PackageRecord, type PackageVersion, } from './adapter.js' +import { editModules } from './nuxt-config.js' import { readJsonObject, stringMap } from './read-json.js' const CONFIG_FILES = ['js', 'ts', 'mjs', 'cjs', 'mts'].map( @@ -59,6 +63,246 @@ async function packageVersion( return { name, range, installed } } +/** + * The package managers a part may be installed with, each with its lock + * files and the words it adds and removes a package with. `separator` is + * true where the manager is known to take `--` before the names, so that a + * name is never read as an option. + */ +const MANAGERS = [ + { + tool: 'pnpm', + locks: ['pnpm-lock.yaml'], + add: 'add', + remove: 'remove', + separator: true, + }, + { + tool: 'yarn', + locks: ['yarn.lock'], + add: 'add', + remove: 'remove', + separator: true, + }, + { + tool: 'bun', + locks: ['bun.lock', 'bun.lockb'], + add: 'add', + remove: 'remove', + separator: false, + }, + { + tool: 'npm', + locks: ['package-lock.json', 'npm-shrinkwrap.json'], + add: 'install', + remove: 'uninstall', + separator: true, + }, +] as const +type Manager = (typeof MANAGERS)[number] +const NPM = MANAGERS[3] + +/** The directories from the project's root down to the part, or the part. */ +function fromRoot(dir: string, root: string | undefined): string[] { + const part = resolve(dir) + const top = root === undefined ? part : resolve(root) + const down = relative(top, part) + if (down === '') return [part] + if (down.startsWith('..') || isAbsolute(down)) return [part] + const dirs = [top] + for (const segment of down.split(sep)) { + dirs.push(join(dirs.at(-1) as string, segment)) + } + return dirs +} + +/** + * The package manager of a part, found the way an install of the whole + * project finds it. The manager a package.json declares in `packageManager` + * comes first, looked for from the root of the project down to the part, so + * a workspace is installed with the manager of its root. Without one, it is + * the manager of the first lock file on the same way down, and npm when + * there is no lock file either. + */ +async function packageManager( + dir: string, + root: string | undefined +): Promise { + const dirs = fromRoot(dir, root) + for (const at of dirs) { + const manifest = await readJsonObject(join(at, 'package.json')) + const declared = String(manifest?.packageManager ?? '').split('@')[0] + const manager = MANAGERS.find(({ tool }) => tool === declared) + if (manager) return manager + } + for (const at of dirs) { + const manager = MANAGERS.find(({ locks }) => + locks.some((lock) => existsSync(join(at, lock))) + ) + if (manager) return manager + } + return NPM +} + +/** The arguments that add or remove one package with a manager. */ +const packageArgs = (manager: Manager, verb: 'add' | 'remove', name: string) => + manager.separator ? [manager[verb], '--', name] : [manager[verb], name] + +/** + * The change to the config that adds or removes a module, for the file as + * it is when the change is made. + */ +const moduleEdit = + (file: string, name: string, action: 'add' | 'remove') => + (source: string): string => { + const edit = editModules(source, name, action) + if (edit.kind === 'changed') return edit.content + if (edit.kind === 'unchanged') return source + throw new Error( + `${file} has changed since it was read, and its modules can no longer be edited safely.` + ) + } + +const configFile = (dir: string) => + CONFIG_FILES.find((candidate) => existsSync(join(dir, candidate))) + +/** + * The steps that add a package to the part and list it in the config. The + * install comes first, so a failed one leaves the config as it was. What the + * steps do, and what was there already, is kept for the project's record. + */ +async function addModule( + dir: string, + name: string | undefined, + root: string | undefined +): Promise { + const change = emptyChange() + if (!name) return change + const did: PackageRecord = { installed: false, listed: false } + change.did = did + + const manager = await packageManager(dir, root) + if (name in (await declared(dir))) { + change.notes.push(`${name} is already a dependency in package.json.`) + } else { + change.steps.push({ + run: { tool: manager.tool, args: packageArgs(manager, 'add', name) }, + did: { installed: true }, + }) + did.installed = true + } + + const file = configFile(dir) + if (!file) { + change.manual.push( + `Add '${name}' to the modules array of the config. No config file was found.` + ) + did.byHand = true + return change + } + const edit = editModules(await readFile(join(dir, file), 'utf8'), name, 'add') + if (edit.kind === 'changed') { + change.steps.push({ + edit: { + file, + change: moduleEdit(file, name, 'add'), + summary: `Add '${name}' to modules in ${file}`, + }, + did: { listed: true }, + }) + did.listed = true + } else if (edit.kind === 'unsafe') { + change.manual.push( + `Add '${name}' to the modules array in ${file}. It could not be edited safely.` + ) + did.byHand = true + } else { + change.notes.push(`${name} is already in modules in ${file}.`) + } + return change +} + +/** + * The steps that take away what an add did: the package when it installed + * it, and the entry in the config when it wrote it. What the part had before + * stays, and so does everything when the record does not say who put it + * there. An entry the add left to the user is left to the user again: the + * add could not read the config, so nothing says whether the entry is there. + */ +async function removeModule( + dir: string, + name: string | undefined, + did: PackageRecord | undefined, + root: string | undefined +): Promise { + const change = emptyChange() + if (!name) return change + + const manager = await packageManager(dir, root) + const dependency = name in (await declared(dir)) + const file = configFile(dir) + const edit = file + ? editModules(await readFile(join(dir, file), 'utf8'), name, 'remove') + : undefined + const listed = edit !== undefined && edit.kind !== 'unchanged' + + if (!did) { + if (dependency || listed) { + change.manual.push( + `The record does not say whether drx add installed ${name}, so it was left. To take it out: ${[ + ...(dependency ? [`${manager.tool} ${manager.remove} ${name}`] : []), + ...(listed ? [`remove '${name}' from modules in ${file}`] : []), + ].join(', and ')}.` + ) + } + return change + } + + if (dependency) { + if (did.installed) { + change.steps.push({ + run: { tool: manager.tool, args: packageArgs(manager, 'remove', name) }, + }) + } else { + change.notes.push( + `${name} was in package.json before drx add, so it stays.` + ) + } + } + if (did.byHand && !did.listed) { + if (edit?.kind !== 'unchanged') { + const where = file ? `in ${file}` : 'of the config' + const why = file ? 'could not edit the file' : 'found no config file' + change.manual.push( + `Remove '${name}' from the modules array ${where}, if you added it there. drx add ${why} and left that line to you, so it is yours to take out.` + ) + } + return change + } + if (!file || !edit || !listed) return change + if (!did.listed) { + // Only a config that can be read says the entry is there. + if (edit.kind === 'changed') { + change.notes.push( + `${name} was in modules in ${file} before drx add, so it stays.` + ) + } + } else if (edit.kind === 'changed') { + change.steps.push({ + edit: { + file, + change: moduleEdit(file, name, 'remove'), + summary: `Remove '${name}' from modules in ${file}`, + }, + }) + } else { + change.manual.push( + `Remove '${name}' from the modules array in ${file}. It could not be edited safely.` + ) + } + return change +} + export const nuxtAdapter: KindAdapter = { kind: 'nuxt', role: 'frontend', @@ -97,5 +341,7 @@ export const nuxtAdapter: KindAdapter = { package: packageVersion, - addModule: addModuleNotAvailable, + addModule: (dir, request) => addModule(dir, request.package, request.root), + removeModule: (dir, request) => + removeModule(dir, request.package, request.did, request.root), } diff --git a/packages/cli/src/cli.ts b/packages/cli/src/cli.ts index 6aad430..d02f2c4 100644 --- a/packages/cli/src/cli.ts +++ b/packages/cli/src/cli.ts @@ -6,6 +6,7 @@ import { type ArgsDef, type CommandDef, } from 'citty' +import { addCommand, removeCommand } from './commands/change.js' import { infoCommand } from './commands/info.js' import { initCommand } from './commands/init.js' import { runMenu } from './commands/menu.js' @@ -35,7 +36,12 @@ export function mainCommand(context: CliContext): CommandDef { subCommands: { init: initCommand(context), info: infoCommand(context), - module: moduleCommand(context), + add: addCommand(context), + remove: removeCommand(context), + module: moduleCommand(context, { + add: addCommand(context, 'module add'), + remove: removeCommand(context, 'module remove'), + }), }, }) } @@ -178,9 +184,13 @@ export function optionsAfterCommand( } /** The code and message to report for anything a command throws. */ -function describe(error: unknown): { code: string; message: string } { +function describe(error: unknown): { + code: string + message: string + [detail: string]: unknown +} { if (error instanceof DrxError) { - return { code: error.code, message: error.message } + return { ...error.details, code: error.code, message: error.message } } // citty's own error for a bad argument or command. The class is not // exported, so it is recognised by name. diff --git a/packages/cli/src/commands-on-path.ts b/packages/cli/src/commands-on-path.ts index 8dab810..6925db3 100644 --- a/packages/cli/src/commands-on-path.ts +++ b/packages/cli/src/commands-on-path.ts @@ -1,5 +1,5 @@ import { accessSync, constants, statSync } from 'node:fs' -import { extname, join } from 'node:path' +import { extname, join, resolve } from 'node:path' type Env = Record @@ -22,6 +22,20 @@ function isRunnable(file: string, windows: boolean): boolean { } } +/** A name as Windows would try it: as it is, or with each extension. */ +function spellings(name: string, env: Env, windows: boolean): string[] { + if (!windows || extname(name) !== '') return [name] + return ( + (env.PATHEXT || DEFAULT_PATHEXT) + .split(';') + .filter(Boolean) + // The file system ignores case there. Trying the lower-case spelling + // first gives the same answer on one that does not. + .flatMap((extension) => [extension.toLowerCase(), extension]) + .map((extension) => name + extension) + ) +} + /** * The file a command name resolves to on PATH, or undefined. It reads the * directories itself and runs nothing, so no shell is involved. @@ -42,17 +56,7 @@ export function findOnPath( .split(windows ? ';' : ':') .filter(Boolean) - let names = [name] - if (windows && extname(name) === '') { - names = (env.PATHEXT || DEFAULT_PATHEXT) - .split(';') - .filter(Boolean) - // The file system ignores case there. Trying the lower-case spelling - // first gives the same answer on one that does not. - .flatMap((extension) => [extension.toLowerCase(), extension]) - .map((extension) => name + extension) - } - + const names = spellings(name, env, windows) for (const directory of directories) { for (const candidate of names) { const file = join(directory, candidate) @@ -62,6 +66,24 @@ export function findOnPath( return undefined } +/** + * The file a command would start: a name is looked up on PATH, and a path + * is taken from the directory the command runs in. On Windows a path with + * no extension is tried with each extension in PATHEXT, as a name is. + */ +export function findCommandFile( + command: string, + cwd: string, + env: Env = process.env, + platform: string = process.platform +): string | undefined { + if (!/[\\/]/.test(command)) return findOnPath(command, env, platform) + const windows = platform === 'win32' + return spellings(resolve(cwd, command), env, windows).find((file) => + isRunnable(file, windows) + ) +} + /** What a starter's commands look like on this machine. */ export interface CommandCheck { /** True when every command of at least one alternative was found. */ diff --git a/packages/cli/src/commands/change.ts b/packages/cli/src/commands/change.ts new file mode 100644 index 0000000..d3aa48b --- /dev/null +++ b/packages/cli/src/commands/change.ts @@ -0,0 +1,363 @@ +import { defineCommand, type ArgsDef, type CommandDef } from 'citty' +import { assertKnownOptions } from '../args.js' +import type { CliContext } from '../context.js' +import { DrxError } from '../errors.js' +import { + carryOut, + changesSomething, + leftToDo, + planAdd, + planData, + planLines, + planRemove, + stepLabels, + type ChangeOptions, + type ModulePlan, + type Project, +} from '../modules/change.js' +import type { ModuleEntry } from '../modules/entry.js' +import type { LoadedModules } from '../modules/registry.js' +import { createOutput } from '../output.js' +import { + CONFIG_FILE, + findProjectRoot, + loadProjectConfig, + type ModuleRecord, +} from '../project.js' +import { repeatCommand } from '../repeat.js' +import { findModule, openModules, registryArgs } from './module.js' + +type Action = 'add' | 'remove' + +const WORDS = { + add: { did: 'Added', example: 'drx add blocks' }, + remove: { did: 'Removed', example: 'drx remove blocks' }, +} as const + +const shared = { + module: { + type: 'positional', + required: false, + description: 'One or more modules, by registry name or package name', + }, + 'dry-run': { + type: 'boolean', + description: 'Print every step and change nothing', + }, + yes: { + type: 'boolean', + alias: 'y', + description: 'Ask nothing', + }, + ...registryArgs, +} satisfies ArgsDef + +const ARGS = { + add: { + ...shared, + force: { + type: 'boolean', + description: + 'Add a module that is archived, or whose range does not admit the Druxt here', + }, + patches: { + type: 'boolean', + default: true, + description: 'Write the patches the module needs', + negativeDescription: 'Leave the patches out, with a warning', + }, + }, + remove: { + ...shared, + backend: { + type: 'boolean', + description: 'Also undo what drx add did to the backend', + }, + }, +} satisfies Record + +/** + * A module as the project's record names it, for a remove of one the + * registry no longer lists or cannot be asked about. The record holds + * everything a remove acts on. + */ +const fromRecord = (record: ModuleRecord): ModuleEntry => ({ + name: record.name, + npm: record.package, + repo: '', + category: '', + status: '', + type: '', + archived: false, + description: '', + backend: [], +}) + +/** The modules that the picker offers for an action. */ +function candidates( + action: Action, + modules: ModuleEntry[], + project: Project +): ModuleEntry[] { + const byName = (a: ModuleEntry, b: ModuleEntry) => + a.name.localeCompare(b.name) + if (action === 'add') { + return modules + .filter((module) => !module.archived && module.npm) + .sort(byName) + } + // What can be removed is what drx add recorded, in the registry or not. + return (project.config.modules ?? []) + .map( + (record) => + modules.find((module) => module.name === record.name) ?? + fromRecord(record) + ) + .sort(byName) +} + +/** + * `drx add` and `drx remove`: the same run for both, with the plan made by + * the adapters of the project's parts and carried out here. + */ +function changeCommand( + context: CliContext, + action: Action, + name: string +): CommandDef { + const args: ArgsDef = ARGS[action] + const words = WORDS[action] + return defineCommand({ + meta: { + name: action, + description: + action === 'add' + ? 'Install a module, list it in the config and set up what it needs in the backend' + : 'Take a module out of the config and uninstall it', + }, + args, + async run({ args: parsed, rawArgs }) { + assertKnownOptions(rawArgs, args, name) + const flags = parsed as Record + const dryRun = flags['dry-run'] === true + const output = createOutput(context, flags.json === true) + output.header() + + const root = findProjectRoot(context.cwd) + if (!root) { + throw new DrxError( + 'usage', + `drx ${action} works inside a project, and there is no ${CONFIG_FILE} in ${context.cwd} or above it.` + ) + } + const project: Project = { root, config: await loadProjectConfig(root) } + + const canAsk = context.interactive && !output.json && flags.yes !== true + let names = parsed._.map(String) + if (names.length === 0 && !canAsk) { + throw new DrxError( + 'usage', + `Give the name of a module, as in "${words.example}".` + ) + } + + // A remove undoes what the project's own record says. The registry + // only adds what else in the project may need a backend module, so a + // remove goes ahead without it. + let loaded: LoadedModules | undefined + try { + loaded = await openModules(context, flags, output) + } catch (error) { + const unread = error instanceof DrxError && error.code === 'registry' + if (action !== 'remove' || !unread) throw error + output.warn( + `${error.message} drx remove goes by the record in ${CONFIG_FILE}.` + ) + if (flags.backend === true) { + output.warn( + 'Without the module registry, drx remove cannot tell whether another module of the project needs what it takes out of the backend.' + ) + } + } + const registry = loaded?.modules ?? [] + const options: ChangeOptions = { + force: flags.force === true, + patches: flags.patches !== false, + backend: flags.backend === true, + // A registry that marks any module as core is taken to mark them all. + registryStatesCore: registry.some((module) => + module.backend.some((need) => need.core) + ), + registry, + names: [], + exec: context.exec, + } + + const picked = names.length === 0 + if (picked) { + const offered = candidates(action, registry, project) + if (offered.length === 0) { + throw new DrxError( + 'usage', + `There is no module to ${action} in this project.` + ) + } + names = await context.prompter.pickMany({ + message: 'Which modules?', + choices: offered.map((module) => ({ + value: module.name, + label: module.name, + hint: `${module.npm ?? 'not published'}. ${module.description}`.trim(), + })), + }) + } + + /** A module by name: in the registry, or for a remove on the record. */ + const named = (wanted: string): ModuleEntry => { + try { + return findModule(registry, wanted) + } catch (error) { + if (action !== 'remove') throw error + const name = wanted.toLowerCase() + const record = project.config.modules?.find( + (entry) => + entry.name.toLowerCase() === name || + entry.package.toLowerCase() === name + ) + if (record) return fromRecord(record) + if (loaded) throw error + throw new DrxError( + 'unknown-module', + `drx add recorded no module named "${wanted}" in this project.` + ) + } + } + const modules = names.map(named) + options.names = modules.map((module) => module.name) + const planFor = (module: ModuleEntry) => + action === 'add' + ? planAdd(module, project, options) + : planRemove(module, project, options) + const refusalsOf = (plan: ModulePlan) => + plan.refusals + .filter((refusal) => !(options.force && refusal.forceable)) + .map( + (refusal) => + `Cannot ${action} ${plan.module.name}: ${refusal.reason}${refusal.forceable ? ` Pass --force to ${action} it all the same.` : ''}` + ) + const plans: ModulePlan[] = [] + for (const module of modules) plans.push(await planFor(module)) + + // Every refusal is found before any step is taken, so one module that + // cannot be changed leaves the others as they were too. + const refused = plans.flatMap(refusalsOf) + if (refused.length > 0) throw new DrxError('refused', refused.join('\n')) + + for (const plan of plans) { + for (const refusal of plan.refusals) output.warn(refusal.reason) + for (const warning of plan.warnings) output.warn(warning) + for (const note of plan.notes) output.line(note) + } + + const shown = plans.flatMap((plan, index) => [ + ...(index > 0 ? [''] : []), + ...planLines(plan), + ]) + const data = () => + plans.map((plan) => ({ + name: plan.module.name, + package: plan.package, + steps: planData(plan), + leftToDo: leftToDo(plan), + })) + + if (dryRun) { + // The lines for a backend elsewhere are in the plan above already. + const byHand = plans.flatMap((plan) => plan.after) + output.result( + { ok: true, dryRun: true, modules: data() }, + [ + ...shown, + ...(byHand.length > 0 + ? ['', 'Left to do:', ...byHand.map((line) => ` ${line}`)] + : []), + '', + 'Nothing was changed: this was a dry run.', + ].join('\n') + ) + return + } + + if (picked) { + output.line() + for (const line of shown) output.line(line) + output.line() + const go = await context.prompter.confirm({ + message: 'Make these changes?', + initial: true, + }) + if (!go) { + throw new DrxError('cancelled', 'Cancelled. Nothing was changed.') + } + } + + // The plans above were all made from the project as it was, to refuse + // and to show before anything changed. A module after the first is + // planned again once the one before it is done, from the project as + // that one left it: its files, what is enabled and what is on record. + const done: string[] = [] + for (const [index, module] of modules.entries()) { + if (index > 0) { + const again = await planFor(module) + const stopped = refusalsOf(again) + if (stopped.length > 0) { + throw new DrxError('refused', stopped.join('\n')) + } + plans[index] = again + } + const plan = plans[index] as ModulePlan + await carryOut(plan, project, context, output, { + done, + pending: plans.slice(index + 1).flatMap(stepLabels), + }) + done.push(...stepLabels(plan)) + } + + const left = plans.flatMap(leftToDo) + output.result( + { ok: true, dryRun: false, modules: data() }, + [ + ...plans.map((plan) => + // A removal with no step found everything in place before it. + action === 'remove' && !changesSomething(plan) + ? `Nothing to remove for ${plan.module.name}: drx add found it in place.` + : `${words.did} ${plan.module.name}.` + ), + ...(left.length > 0 + ? ['', 'Left to do:', ...left.map((line) => ` ${line}`)] + : []), + ].join('\n') + ) + + if (picked) { + output.line() + output.line( + `Repeat this with: ${repeatCommand([ + action, + ...options.names, + ...(options.force ? ['--force'] : []), + ...(options.patches ? [] : ['--no-patches']), + ...(options.backend ? ['--backend'] : []), + '--yes', + ])}` + ) + } + }, + }) +} + +export const addCommand = (context: CliContext, name = 'add') => + changeCommand(context, 'add', name) + +export const removeCommand = (context: CliContext, name = 'remove') => + changeCommand(context, 'remove', name) diff --git a/packages/cli/src/commands/init.ts b/packages/cli/src/commands/init.ts index 02a445e..2b206e3 100644 --- a/packages/cli/src/commands/init.ts +++ b/packages/cli/src/commands/init.ts @@ -32,7 +32,13 @@ import { type Layout, } from '../layouts.js' import { columns, createOutput, type Output } from '../output.js' -import { writeProjectConfig, type ProjectConfig } from '../project.js' +import { + CONFIG_FILE, + loadProjectConfig, + writeProjectConfig, + type ModuleRecord, + type ProjectConfig, +} from '../project.js' import type { StarterEntry, StarterInstall } from '../registry/entry.js' import { repeatCommand, shellQuote } from '../repeat.js' import { @@ -544,6 +550,7 @@ async function runInit( text: counting(shared.prompter.text), select: counting(shared.prompter.select) as Prompter['select'], search: counting(shared.prompter.search) as Prompter['search'], + pickMany: shared.prompter.pickMany, confirm: counting(shared.prompter.confirm), }, } @@ -587,6 +594,20 @@ async function runInit( } const { entry, layout, engine, target, held, install } = settled + // The record of what `drx add` did is the project's own. A starter knows + // nothing of it, and without it nothing that was added could be removed. + let kept: ModuleRecord[] = [] + if (held && existsSync(join(target, CONFIG_FILE))) { + try { + kept = (await loadProjectConfig(target)).modules ?? [] + } catch (error) { + const detail = error instanceof Error ? error.message : String(error) + output.warn( + `The ${CONFIG_FILE} that was in ${target} could not be read, so no record of added modules was kept from it. ${detail}` + ) + } + } + const repository = enclosingRepository(target) if (repository) { output.warn( @@ -688,8 +709,14 @@ async function runInit( } : part ), + ...(kept.length > 0 ? { modules: kept } : {}), } await writeProjectConfig(target, config) + if (kept.length > 0) { + output.note( + `Kept the record of the ${kept.length} module${kept.length === 1 ? '' : 's'} drx add put in this project.` + ) + } const commands = warnAboutStarter(entry, engine, target, context, output) if (install) { diff --git a/packages/cli/src/commands/menu.ts b/packages/cli/src/commands/menu.ts index f4fcaca..b6b046c 100644 --- a/packages/cli/src/commands/menu.ts +++ b/packages/cli/src/commands/menu.ts @@ -18,8 +18,8 @@ const INSIDE: Choice[] = [ { value: 'search', label: 'Search the modules' }, { value: 'show', label: "View a module's details" }, { value: 'info', label: "View this project's details" }, - { value: 'add', label: 'Add a module', ...NOT_YET }, - { value: 'remove', label: 'Remove a module', ...NOT_YET }, + { value: 'add', label: 'Add a module' }, + { value: 'remove', label: 'Remove a module' }, { value: 'configure', label: 'Configure a module', ...NOT_YET }, { value: 'patches', label: 'Manage patches', ...NOT_YET }, { value: 'quit', label: 'Quit' }, @@ -96,8 +96,10 @@ export async function runMenu( const text = await context.prompter.text({ message: 'Search for what?' }) return repeatable(['module', 'search', text]) } + // Each of these picks its modules and says how to repeat itself. case 'add': case 'remove': + return run([choice]) case 'configure': return run(['module', choice]) default: diff --git a/packages/cli/src/commands/module.ts b/packages/cli/src/commands/module.ts index f3c7164..bec13bf 100644 --- a/packages/cli/src/commands/module.ts +++ b/packages/cli/src/commands/module.ts @@ -1,4 +1,4 @@ -import { defineCommand, type ArgsDef } from 'citty' +import { defineCommand, type ArgsDef, type CommandDef } from 'citty' import { assertKnownOptions } from '../args.js' import type { CliContext } from '../context.js' import { DrxError } from '../errors.js' @@ -17,7 +17,7 @@ import { columns, createOutput, type Output } from '../output.js' import { repeatCommand } from '../repeat.js' import { loadUserConfig, resolveModuleRegistryUrl } from '../user-config.js' -const registryArgs = { +export const registryArgs = { 'module-registry': { type: 'string', valueHint: 'url', @@ -64,7 +64,7 @@ function valueOf(parsed: Parsed, name: string): string | undefined { } /** Loads the registry the flags name and says on stderr where it came from. */ -async function openModules( +export async function openModules( context: CliContext, parsed: Parsed, output: Output @@ -317,7 +317,10 @@ function closestNames(modules: ModuleEntry[], wanted: string): string[] { .map(({ name }) => name) } -function findModule(modules: ModuleEntry[], wanted: string): ModuleEntry { +export function findModule( + modules: ModuleEntry[], + wanted: string +): ModuleEntry { const name = wanted.toLowerCase() const found = modules.find( (module) => @@ -536,13 +539,19 @@ function notAvailable(name: string, description: string) { }) } -export function moduleCommand(context: CliContext) { +/** + * The `module` group. The commands that change a project are handed in, as + * they are the top-level `add` and `remove` under a second name. + */ +export function moduleCommand( + context: CliContext, + changing: Record +) { const subCommands = { list: listCommand(context), search: searchCommand(context), info: infoCommand(context), - add: notAvailable('add', 'Install a module and add it to the project'), - remove: notAvailable('remove', 'Take a module out of the project'), + ...changing, configure: notAvailable('configure', 'Set the options of a module'), } return defineCommand({ diff --git a/packages/cli/src/context.ts b/packages/cli/src/context.ts index 833573a..d4229b1 100644 --- a/packages/cli/src/context.ts +++ b/packages/cli/src/context.ts @@ -2,6 +2,7 @@ import { downloadTemplate } from 'giget' import { findOnPath } from './commands-on-path.js' import { homedir } from 'node:os' import { join } from 'node:path' +import { runTool, type RunTool } from './exec.js' import { installDependencies } from './install.js' import { DEFAULT_MODULE_REGISTRY } from './modules/registry.js' import { bundledRegistryDir } from './package-root.js' @@ -37,6 +38,11 @@ export interface Prompter { message: string choices: Choice[] }): Promise + /** A list to narrow by typing, of which any number can be picked. */ + pickMany(question: { + message: string + choices: Choice[] + }): Promise confirm(question: { message: string; initial: boolean }): Promise } @@ -80,6 +86,8 @@ export interface CliContext { download: typeof downloadTemplate /** Installs the dependencies of the site in a directory. */ install: (dir: string) => Promise + /** Runs a tool of the project, such as its package manager. */ + exec: RunTool /** The file a command name resolves to on PATH, or undefined. */ findCommand: (name: string) => string | undefined /** @@ -119,6 +127,7 @@ export function defaultContext(): CliContext { cacheDir: cacheDirectory(process.env), download: downloadTemplate, install: (dir) => installDependencies(dir), + exec: runTool, findCommand: (name) => findOnPath(name), } } diff --git a/packages/cli/src/engines/engine.ts b/packages/cli/src/engines/engine.ts index 5a70bfc..fb1ba13 100644 --- a/packages/cli/src/engines/engine.ts +++ b/packages/cli/src/engines/engine.ts @@ -16,6 +16,8 @@ export interface EngineCommand { export interface EngineAdapter { /** The value a part's `engine` holds. */ readonly name: string + /** False when the backend is somewhere this machine cannot run tools in. */ + readonly local: boolean /** * The command line that runs a backend tool, such as its package manager, * with the given arguments. @@ -30,6 +32,7 @@ export interface EngineAdapter { export function wrappingEngine(name: string): EngineAdapter { return { name, + local: true, run: (part, command, args) => ({ command: name, args: [command, ...args], diff --git a/packages/cli/src/engines/none.ts b/packages/cli/src/engines/none.ts index 7613149..07a6d8e 100644 --- a/packages/cli/src/engines/none.ts +++ b/packages/cli/src/engines/none.ts @@ -5,6 +5,7 @@ import type { EngineAdapter } from './engine.js' /** A backend that runs somewhere else. Nothing can be run in it from here. */ export const noEngine: EngineAdapter = { name: EXISTING_BACKEND, + local: false, run(_part, command, args) { throw new DrxError( 'not-available', diff --git a/packages/cli/src/engines/php.ts b/packages/cli/src/engines/php.ts index 2f48341..ca368de 100644 --- a/packages/cli/src/engines/php.ts +++ b/packages/cli/src/engines/php.ts @@ -7,6 +7,7 @@ import type { EngineAdapter } from './engine.js' */ export const phpEngine: EngineAdapter = { name: 'php', + local: true, run: (part, command, args) => ({ command: command === 'composer' ? command : `vendor/bin/${command}`, args, diff --git a/packages/cli/src/errors.ts b/packages/cli/src/errors.ts index 1853c99..df35524 100644 --- a/packages/cli/src/errors.ts +++ b/packages/cli/src/errors.ts @@ -11,6 +11,8 @@ export type DrxErrorCode = | 'config' | 'download' | 'install' + | 'refused' + | 'step-failed' | 'cancelled' | 'node' @@ -20,10 +22,20 @@ export type DrxErrorCode = */ export class DrxError extends Error { readonly code: DrxErrorCode + /** + * What a caller reading `--json` gets next to the code and the message, as + * fields of the error. The message says the same in words. + */ + readonly details?: Record - constructor(code: DrxErrorCode, message: string) { + constructor( + code: DrxErrorCode, + message: string, + details?: Record + ) { super(message) this.name = 'DrxError' this.code = code + if (details) this.details = details } } diff --git a/packages/cli/src/exec.ts b/packages/cli/src/exec.ts new file mode 100644 index 0000000..2c30f55 --- /dev/null +++ b/packages/cli/src/exec.ts @@ -0,0 +1,120 @@ +import { spawn } from 'node:child_process' +import { extname } from 'node:path' +import { findCommandFile } from './commands-on-path.js' + +export interface ToolResult { + code: number + /** What the tool printed, stdout and stderr together in order. */ + output: string +} + +/** Runs a tool and waits for it, keeping its output to show if it fails. */ +export type RunTool = ( + command: string, + args: string[], + options: { cwd: string } +) => Promise + +/** What to start, and how its arguments are handed over. */ +export interface Spawn { + file: string + args: string[] + /** True when the arguments are a command line, to pass on as written. */ + verbatim: boolean +} + +/** The extensions of a file Windows runs with its command interpreter. */ +const BATCH = ['.cmd', '.bat'] + +/** + * What the command interpreter still reads inside double quotes: a quote + * ends them, a percent sign expands a variable, and a line ends the command. + */ +const READ_IN_QUOTES = /["%\r\n]/ + +/** An argument in double quotes, which the interpreter then reads as text. */ +const quoted = (value: string) => `"${value.replace(/(\\+)$/, '$1$1')}"` + +/** + * How a command is started, so that no argument is ever read as anything + * but an argument. + * + * Everywhere but Windows that is the command and its arguments, with no + * shell. On Windows a program is started by its file in the same way. A + * batch file, which is what `npm`, `composer` and the like are there, can + * only be run by the command interpreter. It is given one command line + * with every argument in double quotes, where `&`, `|`, `<`, `>` and `^` + * are plain characters. An argument with a character that is read even + * there is refused, since there is no way to pass it on unchanged. + */ +export function spawnOf( + command: string, + args: string[], + on: { + platform: string + /** The file a command resolves to, or undefined. */ + find: (command: string) => string | undefined + /** The command interpreter, where the system names one. */ + shell?: string + } +): Spawn | { refused: string } { + if (on.platform !== 'win32') return { file: command, args, verbatim: false } + const file = on.find(command) + if (!file || !BATCH.includes(extname(file).toLowerCase())) { + return { file: file ?? command, args, verbatim: false } + } + const unsafe = [file, ...args].find((value) => READ_IN_QUOTES.test(value)) + if (unsafe !== undefined) { + return { + refused: `${command} is a batch file on Windows, and ${JSON.stringify(unsafe)} cannot be handed to one as it is: it has a quote, a percent sign or a line break in it.`, + } + } + const line = [file, ...args].map(quoted).join(' ') + // /d runs no AutoRun command, and /s takes the line between the outer + // quotes as it is written. + return { + file: on.shell ?? 'cmd.exe', + args: ['/d', '/s', '/c', `"${line}"`], + verbatim: true, + } +} + +/** + * A `RunTool` for a platform and its environment. A tool that cannot be + * started is a failure like any other, with the reason as its output. + */ +export function runToolOn( + platform: string, + env: Record +): RunTool { + return (command, args, { cwd }) => + new Promise((resolve) => { + const plan = spawnOf(command, args, { + platform, + find: (name) => findCommandFile(name, cwd, env, platform), + ...(env.ComSpec ? { shell: env.ComSpec } : {}), + }) + if ('refused' in plan) { + resolve({ code: 126, output: plan.refused }) + return + } + let output = '' + const child = spawn(plan.file, plan.args, { + cwd, + stdio: ['ignore', 'pipe', 'pipe'], + windowsVerbatimArguments: plan.verbatim, + }) + child.stdout.on('data', (chunk: Buffer) => (output += chunk.toString())) + child.stderr.on('data', (chunk: Buffer) => (output += chunk.toString())) + child.on('error', (error) => + resolve({ + code: 127, + output: `${command} could not be started: ${error.message}`, + }) + ) + child.on('close', (code) => resolve({ code: code ?? 1, output })) + }) +} + +/** Runs a command with no shell that reads its arguments. */ +export const runTool: RunTool = runToolOn(process.platform, process.env) diff --git a/packages/cli/src/modules/change.ts b/packages/cli/src/modules/change.ts new file mode 100644 index 0000000..4e72261 --- /dev/null +++ b/packages/cli/src/modules/change.ts @@ -0,0 +1,930 @@ +import { existsSync } from 'node:fs' +import { readFile, rm, writeFile } from 'node:fs/promises' +import { join } from 'node:path' +import { adapterFor, type KindAdapter } from '../adapters/index.js' +import type { + Ask, + BackendRecord, + ChangeStep, + ModuleChange, + PackageRecord, +} from '../adapters/adapter.js' +import type { CliContext } from '../context.js' +import { engineFor } from '../engines/index.js' +import { DrxError } from '../errors.js' +import type { RunTool } from '../exec.js' +import type { Output } from '../output.js' +import type { Part } from '../parts.js' +import { + loadProjectConfig, + writeProjectConfig, + type ModuleRecord, + type ProjectConfig, +} from '../project.js' +import { compatibility } from './compatibility.js' +import type { ModuleEntry } from './entry.js' + +/** + * One thing to do to the project, as it will be shown and done. An edit + * holds the change and not the content: the content is made from the file + * as it is when the step is taken. + */ +export type PlannedStep = ( + | { + type: 'run' + command: string + args: string[] + cwd: string + display: string + } + | { + type: 'edit' + file: string + change: (source: string) => string + display: string + } + | { + type: 'remove' + file: string + /** True when the file, as it is when the step is taken, is to go. */ + when: (source: string) => boolean + display: string + } +) & { + /** For an add: what the step does about the package of the module. */ + did?: Partial + /** For an add: what the step does to a backend part. */ + record?: BackendRecord + /** True once the step has been taken. */ + done?: boolean +} + +/** The steps for one part, or what to do where a backend that is elsewhere is. */ +export interface PartPlan { + path: string + steps: PlannedStep[] + /** Why the steps cannot be taken from here, and the lines to run instead. */ + elsewhere?: { reason: string; lines: string[] } + /** + * Asks the part what the steps did, given the record of those that were + * taken, once they have run or one of them has failed. + */ + settle?: (done: BackendRecord) => Promise +} + +/** Why a module cannot be changed. `--force` goes past a forceable one. */ +interface Refusal { + reason: string + forceable: boolean +} + +export interface ModulePlan { + action: 'add' | 'remove' + module: ModuleEntry + package: string + parts: PartPlan[] + refusals: Refusal[] + warnings: string[] + notes: string[] + /** What is left for the user once the steps are done. */ + after: string[] + /** + * The record once the steps are done: what the project's record of the + * module becomes. Undefined when nothing of it is left to keep. + */ + record?: ModuleRecord + /** + * What a removal leaves in a backend part for another module of the + * project that still needs it, to go on that module's record. + */ + handOver: { to: string; path: string; record: BackendRecord }[] + /** + * For an add, sets `record` to what the steps taken so far did. It is + * called once they have all run, and when one of them fails. A plan is + * made before anything is changed, and a part may do more than it was + * asked to, or less. + */ + settle?: () => Promise +} + +/** + * The project a change is made to. `config` is kept in step with the file: + * carrying a plan out reads the file again, writes it and leaves the result + * here, for the plan of the next module to be made from. + */ +export interface Project { + root: string + config: ProjectConfig +} + +export interface ChangeOptions { + force: boolean + patches: boolean + backend: boolean + registryStatesCore: boolean + /** Every module of the registry, to see what else needs a backend module. */ + registry: ModuleEntry[] + /** The names being changed in this run. */ + names: string[] + /** Runs a tool, to ask a backend part what it has. */ + exec: RunTool +} + +interface Located { + part: Part + dir: string + adapter: KindAdapter +} + +/** The parts of one role that exist and have an adapter. */ +function located(project: Project, role: Part['role']): Located[] { + return project.config.parts.flatMap((part) => { + const adapter = adapterFor(part.kind) + const dir = join(project.root, part.path) + return part.role === role && adapter && existsSync(dir) + ? [{ part, dir, adapter }] + : [] + }) +} + +/** + * A way to ask a backend part what it has, through the engine that runs it. + * Undefined for a part that is not run from this machine. + */ +function asker(project: Project, at: Located, exec: RunTool): Ask | undefined { + const engine = at.part.engine ? engineFor(at.part.engine) : undefined + if (!engine?.local) return undefined + return (tool, args) => { + const line = engine.run(at.part, tool, args) + return exec(line.command, line.args, { + cwd: join(project.root, line.cwd), + }) + } +} + +/** Why each part of a role in the project cannot be changed, as sentences. */ +function unusable(project: Project, role: Part['role']): string[] { + const parts = project.config.parts.filter((part) => part.role === role) + if (parts.length === 0) return [`The project has no ${role} part.`] + return parts.flatMap((part) => { + if (!adapterFor(part.kind)) { + return [ + `${part.path}/ is of the kind ${part.kind}, which this version cannot add a module to.`, + ] + } + return existsSync(join(project.root, part.path)) + ? [] + : [`${part.path}/ does not exist.`] + }) +} + +const hasAny = (record: BackendRecord) => + record.modules.length + record.patches.length > 0 || + record.patcher !== undefined + +/** Two records of what was done to one backend part, as one. */ +function mergeBackend(a: BackendRecord, b: BackendRecord): BackendRecord { + const modules = a.modules.map((module) => ({ ...module })) + for (const module of b.modules) { + const same = modules.find(({ name }) => name === module.name) + if (!same) { + modules.push({ ...module }) + continue + } + same.enabled ||= module.enabled + same.required ||= module.required + if (module.package) same.package = module.package + } + const key = (patch: BackendRecord['patches'][number]) => + [patch.package, patch.description, patch.url].join('\n') + const patches = [...a.patches] + for (const patch of b.patches) { + if (!patches.some((other) => key(other) === key(patch))) patches.push(patch) + } + // What either put there for the patches of the part was put there. + const patcher = + a.patcher || b.patcher + ? { + required: + a.patcher?.required === true || b.patcher?.required === true, + allowed: a.patcher?.allowed === true || b.patcher?.allowed === true, + } + : undefined + return { modules, patches, ...(patcher ? { patcher } : {}) } +} + +/** One part's record folded into the list kept for a module. */ +function withBackend( + list: ModuleRecord['backend'], + path: string, + record: BackendRecord +): ModuleRecord['backend'] { + const merged = mergeBackend( + list.find((entry) => entry.path === path) ?? { modules: [], patches: [] }, + record + ) + return [ + ...list.filter((entry) => entry.path !== path), + ...(hasAny(merged) ? [{ path, ...merged }] : []), + ] +} + +/** + * What a second add leaves on the record: everything either add did. A part + * the first add installed the package in is still one the CLI installed it + * in, though the second found it there. + */ +function mergeRecords(old: ModuleRecord, now: ModuleRecord): ModuleRecord { + const frontend = (now.frontend ?? []).map((entry) => { + const before = old.frontend?.find(({ path }) => path === entry.path) + const listed = entry.listed || before?.listed === true + return { + path: entry.path, + installed: entry.installed || before?.installed === true, + listed, + // A line left to the user stays so until an add writes it itself. + ...(!listed && (entry.byHand || before?.byHand) ? { byHand: true } : {}), + } + }) + // What this add did comes first, so a run that finishes what an earlier + // one left undone ends with the record of a run that did it all. + const nothing: BackendRecord = { modules: [], patches: [] } + const paths = [...now.backend, ...old.backend].map(({ path }) => path) + const backend = [...new Set(paths)].flatMap((path) => { + const merged = mergeBackend( + now.backend.find((entry) => entry.path === path) ?? nothing, + old.backend.find((entry) => entry.path === path) ?? nothing + ) + return hasAny(merged) ? [{ path, ...merged }] : [] + }) + return { name: now.name, package: now.package, frontend, backend } +} + +const pluralPatches = (count: number) => + `${count} patch${count === 1 ? '' : 'es'}` + +/** A step of an adapter as one to show and take, with what it records. */ +function planned( + step: ChangeStep, + dir: string, + line: (run: { tool: string; args: string[] }) => { + command: string + args: string[] + cwd: string + } +): PlannedStep { + const records = { + ...(step.did ? { did: step.did } : {}), + ...(step.record ? { record: step.record } : {}), + } + if ('edit' in step) { + return { + type: 'edit', + file: join(dir, step.edit.file), + change: step.edit.change, + display: step.edit.summary, + ...records, + } + } + if ('remove' in step) { + return { + type: 'remove', + file: join(dir, step.remove.file), + when: step.remove.when, + display: step.remove.summary, + ...records, + } + } + const { command, args, cwd } = line(step.run) + return { + type: 'run', + command, + args, + cwd, + display: [command, ...args].join(' '), + ...records, + } +} + +/** The steps of a frontend part, which are run in it as they are. */ +function frontendPlan(at: Located, change: ModuleChange): PartPlan { + return { + path: at.part.path, + steps: change.steps.map((step) => + planned(step, at.dir, ({ tool, args }) => ({ + command: tool, + args, + cwd: at.dir, + })) + ), + } +} + +/** + * The steps of a backend part, with each tool turned into the command line + * of the part's engine. A backend that is not run from this machine gets no + * steps: the lines are kept to print, for whoever is where it runs. + */ +function backendPlan( + project: Project, + at: Located, + change: ModuleChange +): PartPlan { + const { part } = at + const engine = part.engine ? engineFor(part.engine) : undefined + + if (!engine?.local) { + const lines = [ + ...(change.record?.patches ?? []).map( + (patch) => + `Patch ${patch.package} with ${patch.url} (${patch.description})` + ), + ...change.steps.flatMap((step) => + 'run' in step ? [[step.run.tool, ...step.run.args].join(' ')] : [] + ), + ] + return { + path: part.path, + steps: [], + ...(lines.length > 0 + ? { + elsewhere: { + reason: engine + ? 'The backend of this project is not on this machine. Where it is:' + : `This project does not record how ${part.path}/ is run. In it:`, + lines, + }, + } + : {}), + } + } + + return { + path: part.path, + steps: change.steps.map((step) => + planned(step, at.dir, ({ tool, args }) => { + const line = engine.run(part, tool, args) + return { ...line, cwd: join(project.root, line.cwd) } + }) + ), + ...(change.settle ? { settle: change.settle } : {}), + } +} + +/** Folds what an adapter found into the plan of the module. */ +function absorb(plan: ModulePlan, change: ModuleChange): void { + plan.refusals.push( + ...change.problems.map((reason) => ({ reason, forceable: false })) + ) + plan.warnings.push(...change.warnings) + plan.notes.push(...change.notes) + plan.after.push(...change.manual, ...change.after) +} + +function elsewhereLines(part: PartPlan): string[] { + return part.elsewhere + ? [ + part.elsewhere.reason, + ...part.elsewhere.lines.map((line) => ` ${line}`), + ] + : [] +} + +/** Everything adding one module to the project takes. Nothing is done here. */ +export async function planAdd( + module: ModuleEntry, + project: Project, + options: ChangeOptions +): Promise { + const plan: ModulePlan = { + action: 'add', + module, + package: module.npm ?? '', + parts: [], + refusals: [], + warnings: [], + notes: [], + after: [], + handOver: [], + } + if (module.archived) { + plan.refusals.push({ + reason: `${module.name} is archived.`, + forceable: true, + }) + } + if (!module.npm) { + plan.refusals.push({ + reason: `${module.name} has no package to install: it is not released.`, + forceable: false, + }) + return plan + } + + const npm = module.npm + const frontend: { path: string; part: PartPlan; byHand: boolean }[] = [] + for (const at of located(project, 'frontend')) { + const druxt = await at.adapter.druxt(at.dir) + const fit = compatibility(module.druxt, druxt) + if (fit === 'incompatible' && druxt) { + const has = druxt.installed ?? `asked for as ${druxt.range}` + plan.refusals.push({ + reason: `${module.name} works with ${druxt.name} ${module.druxt}, and ${at.part.path}/ has ${druxt.name} ${has}.`, + forceable: true, + }) + } else if (fit === 'unknown' && druxt) { + plan.warnings.push( + `${module.name} does not say which ${druxt.name} it works with, so it may not work with the one in ${at.part.path}/.` + ) + } + const change = await at.adapter.addModule(at.dir, { + package: npm, + root: project.root, + needs: [], + patches: options.patches, + registryStatesCore: options.registryStatesCore, + }) + absorb(plan, change) + const part = frontendPlan(at, change) + plan.parts.push(part) + if (change.did) { + const byHand = change.did.byHand === true + frontend.push({ path: at.part.path, part, byHand }) + } + } + // With no part to put the package in, nothing would be added at all. + if (frontend.length === 0) { + plan.refusals.push({ + reason: [ + `No frontend part of this project can take ${npm}.`, + ...unusable(project, 'frontend'), + ].join(' '), + forceable: false, + }) + return plan + } + + const backend: { path: string; part: PartPlan }[] = [] + const parts = located(project, 'backend') + for (const at of parts) { + const needs = module.backend.filter((need) => need.kind === at.part.kind) + if (needs.length === 0) continue + const ask = asker(project, at, options.exec) + const change = await at.adapter.addModule(at.dir, { + root: project.root, + needs, + patches: options.patches, + registryStatesCore: options.registryStatesCore, + ...(ask ? { ask } : {}), + }) + const part = backendPlan(project, at, change) + absorb(plan, change) + plan.parts.push(part) + backend.push({ path: at.part.path, part }) + } + + // What the module needs of a backend that no part of the project is, is + // for the user to do where that backend runs. + const unmet = module.backend.filter( + (need) => !parts.some((at) => at.part.kind === need.kind) + ) + if (unmet.length > 0) { + plan.after.push( + `${module.name} needs a backend, and this project has no backend part that can take what it needs. Where the backend is:`, + ...unmet.flatMap((need) => [ + ` Enable ${need.label} (${need.name})`, + ...(options.patches ? (need.patches ?? []) : []).map( + (patch) => + ` Patch ${patch.package ?? need.label} with ${patch.url} (${patch.description})` + ), + ...(need.setup ?? []).flatMap((step) => [ + ` ${need.label}: ${step.title}`, + ...(step.command ? [` ${step.command}`] : []), + ...(step.url ? [` ${step.url}`] : []), + ]), + ]) + ) + } + + // A module added before keeps what that add did: this one found it there. + const before = project.config.modules?.find( + (entry) => entry.name === module.name + ) + // The record is what the steps taken did, and no more. Each step says + // what it does, so the record is as true of a run that stopped part way + // as of one that finished. + const taken = (part: PartPlan) => part.steps.filter((step) => step.done) + plan.settle = async () => { + const now: ModuleRecord = { + name: module.name, + package: npm, + frontend: frontend.map(({ path, part, byHand }) => ({ + path, + installed: taken(part).some((step) => step.did?.installed === true), + listed: taken(part).some((step) => step.did?.listed === true), + // The line is left to the user once the steps before it are done. + ...(byHand && part.steps.every((step) => step.done) + ? { byHand: true } + : {}), + })), + backend: [], + } + for (const { path, part } of backend) { + let done: BackendRecord = { modules: [], patches: [] } + for (const step of taken(part)) { + if (step.record) done = mergeBackend(done, step.record) + } + if (part.settle) done = await part.settle(done) + if (hasAny(done)) now.backend.push({ path, ...done }) + } + plan.record = before ? mergeRecords(before, now) : now + } + return plan +} + +/** True when a frontend part of the project asks for a package. */ +async function declares(project: Project, name: string): Promise { + for (const at of located(project, 'frontend')) { + const found = await at.adapter.package(at.dir, name) + if (found && found.range !== null) return true + } + return false +} + +/** + * Everything taking one module out of the project takes: what the record + * says `drx add` did, and no more. What stays in place stays on the record. + */ +export async function planRemove( + module: ModuleEntry, + project: Project, + options: ChangeOptions +): Promise { + const plan: ModulePlan = { + action: 'remove', + module, + package: module.npm ?? '', + parts: [], + refusals: [], + warnings: [], + notes: [], + after: [], + handOver: [], + } + const recorded = project.config.modules?.find( + (entry) => entry.name === module.name + ) + if (!recorded) { + const there = module.npm ? await declares(project, module.npm) : false + plan.refusals.push({ + reason: there + ? `drx add did not put ${module.npm} in this project, so there is nothing of its own to undo. Uninstall the package and take it out of the config by hand.` + : `${module.npm ?? module.name} is not in this project.`, + forceable: false, + }) + return plan + } + + for (const at of located(project, 'frontend')) { + // A record with a frontend list says what was done to every part. + const none: PackageRecord = { installed: false, listed: false } + const did = recorded.frontend + ? (recorded.frontend.find(({ path }) => path === at.part.path) ?? none) + : undefined + const change = await at.adapter.removeModule(at.dir, { + ...(module.npm ? { package: module.npm } : {}), + root: project.root, + ...(did + ? { + did: { + installed: did.installed, + listed: did.listed, + ...(did.byHand ? { byHand: true } : {}), + }, + } + : {}), + }) + absorb(plan, change) + plan.parts.push(frontendPlan(at, change)) + } + + const keep = (backend: ModuleRecord['backend']) => { + if (backend.length === 0) return + plan.record = { + name: recorded.name, + package: recorded.package, + frontend: [], + backend, + } + } + if (!options.backend) { + for (const entry of recorded.backend) { + const put = [ + ...entry.modules.map(({ name }) => name), + ...(entry.patches.length > 0 + ? [pluralPatches(entry.patches.length)] + : []), + ] + plan.after.push( + `The backend was left as it is. drx remove ${module.name} --backend takes out what drx add put in ${entry.path}/: ${put.join(', ')}.` + ) + } + // The record stays, so the backend can still be undone. + keep(recorded.backend) + return plan + } + + // A backend module stays while any other module in the project needs it. + // A module is in the project while a frontend part asks for its package: + // a record alone may be what an earlier removal left behind. + const neededBy = new Map() + for (const other of options.registry) { + if (options.names.includes(other.name) || !other.npm) continue + if (other.npm === module.npm) continue + if (!(await declares(project, other.npm))) continue + for (const need of other.backend) { + if (!neededBy.has(need.name)) neededBy.set(need.name, other.name) + } + } + + let left: ModuleRecord['backend'] = [] + for (const { path, ...entry } of recorded.backend) { + const at = located(project, 'backend').find( + (found) => found.part.path === path + ) + if (!at) { + // The part is gone or has moved. Its record waits for it. + left = withBackend(left, path, entry) + continue + } + + // What another module needs is set aside, with the patches written for + // it. A record that does not say what a patch was for keeps them all + // while any module stays. + const staying = entry.modules.filter(({ name }) => neededBy.has(name)) + const stays = (patch: BackendRecord['patches'][number]) => + patch.module + ? staying.some(({ name }) => name === patch.module) + : staying.length > 0 + for (const [index, held] of staying.entries()) { + const by = neededBy.get(held.name) as string + plan.notes.push(`${held.name} stays: ${by} needs it.`) + const record: BackendRecord = { + modules: [held], + patches: entry.patches.filter((patch) => + patch.module ? patch.module === held.name : index === 0 + ), + } + // It goes on the record of the module that needs it, when that one + // has a record, so removing that module takes it out. + if (project.config.modules?.some(({ name }) => name === by)) { + plan.handOver.push({ to: by, path, record }) + } else { + left = withBackend(left, path, record) + } + } + + const ask = asker(project, at, options.exec) + const change = await at.adapter.removeModule(at.dir, { + root: project.root, + record: { + modules: entry.modules.filter((held) => !staying.includes(held)), + patches: entry.patches.filter((patch) => !stays(patch)), + ...(entry.patcher ? { patcher: entry.patcher } : {}), + }, + ...(ask ? { ask } : {}), + }) + absorb(plan, change) + plan.parts.push(backendPlan(project, at, change)) + if (!change.record) continue + // What the backend itself holds on to goes with what was handed over: + // it is held by a module that stays, and comes out when that one does. + const heir = plan.handOver.find((handed) => handed.path === path) + // What the part keeps for the patches of other modules goes on the + // record of one that has a patch in it, to come out with the last. + const { patcher, ...own } = change.record + const patched = patcher + ? project.config.modules?.find( + (other) => + other.name !== recorded.name && + other.backend.some( + (held) => held.path === path && held.patches.length > 0 + ) + ) + : undefined + const stay: BackendRecord = patched ? own : change.record + if (patched && patcher) { + const record: BackendRecord = { modules: [], patches: [], patcher } + plan.handOver.push({ to: patched.name, path, record }) + } + if (!hasAny(stay)) continue + if (heir) { + heir.record = mergeBackend(heir.record, stay) + } else { + left = withBackend(left, path, stay) + } + } + keep(left) + return plan +} + +/** + * Everything a plan leaves to the user: first the commands for a backend + * that is elsewhere, then what no tool could do and the setup a module needs. + */ +export function leftToDo(plan: ModulePlan): string[] { + return [...plan.parts.flatMap(elsewhereLines), ...plan.after] +} + +/** True when carrying a plan out changes or runs something. */ +export function changesSomething(plan: ModulePlan): boolean { + return plan.parts.some((part) => part.steps.length > 0) +} + +/** A plan as the lines a person reads before it is carried out. */ +export function planLines(plan: ModulePlan): string[] { + const verb = plan.action === 'add' ? 'Add' : 'Remove' + const lines = [`${verb} ${plan.module.name} (${plan.package})`] + for (const part of plan.parts) { + if (part.steps.length === 0 && !part.elsewhere) continue + lines.push(` ${part.path}/`) + for (const step of part.steps) { + lines.push( + ` ${step.type === 'run' ? 'run ' : 'edit'} ${step.display}` + ) + } + lines.push(...elsewhereLines(part).map((line) => ` ${line}`)) + } + return lines +} + +/** A plan's steps as data, for `--json`. */ +export function planData(plan: ModulePlan) { + return plan.parts.flatMap((part) => [ + ...part.steps.map((step) => + step.type === 'run' + ? { part: part.path, run: step.display } + : { part: part.path, edit: step.display } + ), + ...(part.elsewhere + ? [{ part: part.path, elsewhere: part.elsewhere.lines }] + : []), + ]) +} + +/** The steps taken and not taken by the other modules of a run, as labels. */ +export interface Around { + done: string[] + pending: string[] +} + +/** The labels of the steps of a plan, as a failure lists them. */ +export function stepLabels(plan: ModulePlan): string[] { + return plan.parts.flatMap((part) => + part.steps.map((step) => `${part.path}/: ${step.display}`) + ) +} + +/** + * Puts the record of a plan into the project's config file. The file is + * read again first, so what was written to it since the command started is + * kept, and the result is left on `project` for whatever is planned next. + */ +async function writeRecord( + plan: ModulePlan, + project: Project, + handOver: boolean +): Promise { + const config = await loadProjectConfig(project.root) + let modules = (config.modules ?? []).filter( + (entry) => entry.name !== plan.module.name + ) + if (plan.record) modules = [...modules, plan.record] + for (const { to, path, record } of handOver ? plan.handOver : []) { + modules = modules.map((entry) => + entry.name === to + ? { ...entry, backend: withBackend(entry.backend, path, record) } + : entry + ) + } + const rest: ProjectConfig = { ...config } + delete rest.modules + project.config = modules.length > 0 ? { ...rest, modules } : rest + await writeProjectConfig(project.root, project.config) +} + +/** + * Carries out one plan and keeps the project's record in step. The first + * step that fails stops everything: its output is shown, with what had been + * done by then and what had not. + * + * A plan is carried out as soon as it is made, and the plan of the next + * module is made after it, from the project as this one left it. + * + * The record is true after a failure as well. An add that stops part way + * records the steps it took, so a second run finishes the job and a remove + * undoes what was done. A remove that stops keeps its record whole, and a + * second run finds what is already gone. + */ +export async function carryOut( + plan: ModulePlan, + project: Project, + context: CliContext, + output: Output, + around: Around = { done: [], pending: [] } +): Promise { + const steps = plan.parts.flatMap((part) => + part.steps.map((step) => ({ + step, + path: part.path, + label: `${part.path}/: ${step.display}`, + })) + ) + const list = (title: string, labels: string[]) => + labels.length > 0 ? [title, ...labels.map((label) => ` ${label}`)] : [] + + const fail = async ( + at: (typeof steps)[number], + headline: string, + exitCode: number, + shown: string + ): Promise => { + const taken = steps.filter(({ step }) => step.done) + if (plan.action === 'add' && taken.length > 0) { + await plan.settle?.() + await writeRecord(plan, project, false) + } + const finished = [...around.done, ...taken.map(({ label }) => label)] + const pending = [ + ...steps.filter(({ step }) => !step.done).map(({ label }) => label), + ...around.pending, + ] + throw new DrxError( + 'step-failed', + [ + headline, + shown, + ...list('Done:', finished), + ...list('Not done:', pending), + ] + .filter((line) => line !== '') + .join('\n'), + { + failed: { + part: at.path, + step: at.step.display, + exitCode, + output: shown, + }, + done: finished, + notDone: pending, + } + ) + } + + for (const at of steps) { + const { step, path, label } = at + if (step.type === 'edit') { + let source: string + let content: string + try { + source = await readFile(step.file, 'utf8') + content = step.change(source) + } catch (error) { + const reason = error instanceof Error ? error.message : String(error) + await fail(at, `${step.display} failed in ${path}/.`, 1, reason) + return + } + if (content !== source) await writeFile(step.file, content) + output.did(label) + } else if (step.type === 'remove') { + // A file that is not there, or is no longer what was to go, stays out + // of it: the step is done either way. + let source: string | undefined + try { + source = await readFile(step.file, 'utf8') + } catch { + source = undefined + } + if (source !== undefined && step.when(source)) await rm(step.file) + output.did(label) + } else { + output.note(label) + const result = await context.exec(step.command, step.args, { + cwd: step.cwd, + }) + if (result.code !== 0) { + await fail( + at, + `${step.display} failed in ${path}/ with exit code ${result.code}.`, + result.code, + result.output.trimEnd() + ) + } + } + step.done = true + } + + await plan.settle?.() + await writeRecord(plan, project, true) +} diff --git a/packages/cli/src/modules/entry.ts b/packages/cli/src/modules/entry.ts index e2729e1..e2970e6 100644 --- a/packages/cli/src/modules/entry.ts +++ b/packages/cli/src/modules/entry.ts @@ -1,6 +1,11 @@ import { adapterFor, kindsWithRole } from '../adapters/index.js' import { DrxError } from '../errors.js' -import { isNonEmptyString, isNpmName, isRecord } from '../validate.js' +import { + isHttpUrl, + isNonEmptyString, + isNpmName, + isRecord, +} from '../validate.js' /** The registry format this version reads. */ export const MODULE_SCHEMA_VERSION = 1 @@ -17,6 +22,28 @@ export interface BackendModule { */ core?: boolean url?: string + /** The package that provides the module, where its name does not say. */ + composer?: { package: string; constraint?: string } + /** What is left to do by hand once the module is enabled. */ + setup?: SetupStep[] + /** Patches the module needs until a fix is released. */ + patches?: ModulePatch[] +} + +export interface SetupStep { + title: string + command?: string + url?: string +} + +export interface ModulePatch { + description: string + url: string + /** The package the patch applies to, when it is not the module's own. */ + package?: string + issue?: string + /** The version of the patched package that holds the fix. */ + until?: string } /** @@ -71,6 +98,70 @@ function optionalBoolean(raw: Raw, key: string, at: string): boolean { return value ?? false } +/** A value with its undefined keys left out. */ +function compact(value: T): T { + return Object.fromEntries( + Object.entries(value).filter(([, inner]) => inner !== undefined) + ) as T +} + +function listOf( + raw: Raw, + key: string, + at: string +): [Raw, string][] | undefined { + const list = raw[key] + if (list === undefined) return undefined + if (!Array.isArray(list)) throw new Invalid(`${at}.${key} must be an array`) + return list.map((item, index) => { + const here = `${at}.${key}[${index}]` + if (!isRecord(item)) throw new Invalid(`${here} must be an object`) + return [item, here] + }) +} + +/** The optional fields that say how a backend module is added. */ +function additions(item: Raw, at: string) { + let composer: BackendModule['composer'] + if (item.composer !== undefined) { + if (!isRecord(item.composer)) { + throw new Invalid(`${at}.composer must be an object`) + } + composer = compact({ + package: requiredString(item.composer, 'package', `${at}.composer`), + constraint: optionalString(item.composer, 'constraint', `${at}.composer`), + }) as NonNullable + } + + const setup = listOf(item, 'setup', at)?.map( + ([step, here]) => + compact({ + title: requiredString(step, 'title', here), + command: optionalString(step, 'command', here), + url: optionalString(step, 'url', here), + }) as SetupStep + ) + + const patches = listOf(item, 'patches', at)?.map(([patch, here]) => { + const description = requiredString(patch, 'description', here) + if (!isHttpUrl(patch.url)) { + throw new Invalid(`${here}.url must be an http or https URL`) + } + return compact({ + description, + url: patch.url, + package: optionalString(patch, 'package', here), + issue: optionalString(patch, 'issue', here), + until: optionalString(patch, 'until', here), + }) as ModulePatch + }) + + return compact({ composer, setup, patches }) as Pick< + BackendModule, + 'composer' | 'setup' | 'patches' + > +} + /** * The backend modules of an entry. The registry lists them under a key named * after the kind of backend, so each backend kind that has an adapter is @@ -95,6 +186,7 @@ function backendModules(raw: Raw, at: string): BackendModule[] { label: requiredString(item, 'label', here), ...(item.core === undefined ? {} : { core }), ...(url === undefined ? {} : { url }), + ...additions(item, here), } // The kind says what its tools take, so a value is never an option. const problem = adapterFor(kind)?.moduleProblem?.(module) diff --git a/packages/cli/src/project.ts b/packages/cli/src/project.ts index d91ec5f..52a0fc4 100644 --- a/packages/cli/src/project.ts +++ b/packages/cli/src/project.ts @@ -3,10 +3,12 @@ import { writeFile } from 'node:fs/promises' import { createRequire } from 'node:module' import { dirname, join, resolve } from 'node:path' import { loadConfig } from 'c12' +import type { BackendRecord, PackageRecord } from './adapters/adapter.js' +import { adapterFor } from './adapters/index.js' import { DrxError } from './errors.js' import { isLayout, LAYOUTS, type Layout } from './layouts.js' import { partsProblem, type Part } from './parts.js' -import { isNonEmptyString } from './validate.js' +import { isNonEmptyString, isNpmName, isRecord } from './validate.js' const nodeRequire = createRequire(import.meta.url) @@ -27,6 +29,77 @@ export interface ProjectConfig { /** The name of the source its Druxt packages come from. */ source: string parts: Part[] + /** What `drx add` did, so `drx remove` undoes that and no more. */ + modules?: ModuleRecord[] +} + +/** + * One module the CLI added to the project, with what it did to each part. + * What it found in place is recorded as not done, so a remove leaves it. + */ +export interface ModuleRecord { + /** The name of the module in the registry. */ + name: string + /** Its frontend package. */ + package: string + /** + * What was done to each frontend part, by the part's path. Undefined in a + * record written before this was kept, which does not say. + */ + frontend?: ({ path: string } & PackageRecord)[] + /** What was done to each backend part, by the part's path. */ + backend: ({ path: string } & BackendRecord)[] +} + +type Raw = Record +const rawList = (value: unknown): Raw[] => + Array.isArray(value) ? value.filter(isRecord) : [] + +/** + * A record as this version keeps it, read from any version's. An older one + * lists only the backend modules it required, all of which it also enabled, + * and has nothing on the frontend or on which module a patch was for. + */ +function moduleRecord(raw: Raw): ModuleRecord { + return { + name: raw.name as string, + package: raw.package as string, + ...(Array.isArray(raw.frontend) + ? { + frontend: rawList(raw.frontend).map((entry) => ({ + path: String(entry.path), + installed: entry.installed === true, + listed: entry.listed === true, + ...(entry.byHand === true ? { byHand: true } : {}), + })), + } + : {}), + backend: rawList(raw.backend).map((entry) => ({ + path: String(entry.path), + modules: rawList(entry.modules).map((module) => ({ + name: String(module.name), + ...(typeof module.package === 'string' + ? { package: module.package } + : {}), + enabled: module.enabled !== false, + required: module.required !== false, + })), + patches: rawList(entry.patches).map((patch) => ({ + package: String(patch.package), + description: String(patch.description), + url: String(patch.url), + ...(typeof patch.module === 'string' ? { module: patch.module } : {}), + })), + ...(isRecord(entry.patcher) + ? { + patcher: { + required: entry.patcher.required === true, + allowed: entry.patcher.allowed === true, + }, + } + : {}), + })), + } } export async function writeProjectConfig( @@ -58,7 +131,43 @@ function configProblem(config: Record): string | undefined { return `${key} must be a non-empty string` } } - return partsProblem(config.parts, 'parts') + const parts = partsProblem(config.parts, 'parts') + if (parts) return parts + + const modules = config.modules + if (modules === undefined) return undefined + if (!Array.isArray(modules)) return 'modules must be an array' + for (const [index, module] of modules.entries()) { + const at = `modules[${index}]` + for (const key of ['name', 'package']) { + if (!isRecord(module) || !isNonEmptyString(module[key])) { + return `${at}.${key} must be a non-empty string` + } + } + if (!Array.isArray((module as Record).backend)) { + return `${at}.backend must be an array` + } + // The file comes with a clone of the project, and a remove hands what + // the record names to the tools of each part. So every name in it is + // checked here, as the same name is when it is read from a registry. + const record = moduleRecord(module as Raw) + if (!isNpmName(record.package)) { + return `${at}.package must be the name of an npm package` + } + for (const [position, entry] of record.backend.entries()) { + // A record for a path no part is at is never acted on. + const part = (config.parts as Part[]).find( + (candidate) => candidate.path === entry.path + ) + const problem = part + ? adapterFor(part.kind)?.recordProblem?.(entry) + : undefined + if (problem) { + return `${at}.backend[${position}].${problem.field} ${problem.must}` + } + } + } + return undefined } /** Reads and checks the config file of the project rooted at `root`. */ @@ -98,5 +207,8 @@ export async function loadProjectConfig(root: string): Promise { starter: config.starter as string, source: config.source as string, parts: config.parts as Part[], + ...(config.modules + ? { modules: (config.modules as Raw[]).map(moduleRecord) } + : {}), } } diff --git a/packages/cli/src/prompts.ts b/packages/cli/src/prompts.ts index d47c06e..96276d2 100644 --- a/packages/cli/src/prompts.ts +++ b/packages/cli/src/prompts.ts @@ -1,5 +1,12 @@ import type { Readable, Writable } from 'node:stream' -import { autocomplete, confirm, isCancel, select, text } from '@clack/prompts' +import { + autocomplete, + autocompleteMultiselect, + confirm, + isCancel, + select, + text, +} from '@clack/prompts' import type { Choice, Prompter } from './context.js' import { DrxError } from './errors.js' @@ -62,6 +69,18 @@ export function terminalPrompter( return answered(value) as (typeof choices)[number]['value'] }, + pickMany: async ({ message, choices }) => { + const values = await autocompleteMultiselect({ + message, + options: clackOptions(choices), + maxItems: 10, + required: true, + input, + output, + }) + return answered(values) as (typeof choices)[number]['value'][] + }, + confirm: async ({ message, initial }) => answered( await confirm({ message, initialValue: initial, input, output }) diff --git a/packages/cli/test/adapters/adapters.test.ts b/packages/cli/test/adapters/adapters.test.ts index 96780bd..9e6e42b 100644 --- a/packages/cli/test/adapters/adapters.test.ts +++ b/packages/cli/test/adapters/adapters.test.ts @@ -91,12 +91,6 @@ describe('the nuxt adapter', () => { test('reports nothing for a directory with no package.json', async () => { expect(await nuxt.packages(tmp())).toEqual([]) }) - - test('cannot add a module yet', async () => { - await expect(nuxt.addModule(tmp(), 'druxt-site')).rejects.toThrow( - 'Adding a module is not available yet.' - ) - }) }) describe('the drupal adapter', () => { @@ -154,12 +148,6 @@ describe('the drupal adapter', () => { { name: 'drupal/druxt', range: '^1.2', installed: null }, ]) }) - - test('cannot add a module yet', async () => { - await expect(drupal.addModule(tmp(), 'druxt')).rejects.toThrow( - 'Adding a module is not available yet.' - ) - }) }) describe('kindsWithRole', () => { diff --git a/packages/cli/test/adapters/drupal-modules.test.ts b/packages/cli/test/adapters/drupal-modules.test.ts new file mode 100644 index 0000000..11929c6 --- /dev/null +++ b/packages/cli/test/adapters/drupal-modules.test.ts @@ -0,0 +1,1364 @@ +import { readFileSync } from 'node:fs' +import { join } from 'node:path' +import { afterEach, describe, expect, test } from 'vitest' +import { adapterFor } from '../../src/adapters/index.js' +import type { + AddRequest, + Ask, + BackendRecord, + ModuleChange, +} from '../../src/adapters/adapter.js' +import type { BackendModule } from '../../src/modules/entry.js' +import { cleanTmp, tmp, writeTree } from '../helpers/tmp.js' + +afterEach(cleanTmp) + +const drupal = adapterFor('drupal')! +const PLUGIN = 'cweagans/composer-patches' + +const need = ( + name: string, + extra: Partial = {} +): BackendModule => ({ + kind: 'drupal', + name, + label: name, + ...extra, +}) + +/** + * A site that answers what it is asked: which modules are enabled, and what + * uninstalling one would take with it. `asked` keeps the questions. + */ +function answering( + enabled: string[] = [], + dependents: Record = {}, + paths: Record = {}, + /** What a simulated uninstall takes to be enabled, when that differs. */ + cached: string[] = enabled, + /** False when the list of enabled modules cannot be had. */ + lists = true +) { + const asked: string[] = [] + const ask: Ask = async (tool, args) => { + asked.push(`${tool} ${args.join(' ')}`) + if (args[0] === 'pm:list') { + if (!lists) return { code: 1, output: 'No list.' } + const list = Object.fromEntries( + enabled.map((name) => [ + name, + { name, path: paths[name] ?? `modules/contrib/${name}` }, + ]) + ) + return { code: 0, output: JSON.stringify(list) } + } + const name = args.at(-1) as string + if (!cached.includes(name)) { + return { + code: 1, + output: `The following module(s) are not installed: ${name}. No modules to uninstall.`, + } + } + const all = [name, ...(dependents[name] ?? [])].join(', ') + return { + code: 0, + output: `The following extensions will be uninstalled: ${all}\n`, + } + } + return { ask, asked } +} +const silent: Ask = async () => ({ code: 1, output: 'No database.' }) + +/** A site's composer.json, written with four spaces as Composer writes it. */ +function site( + composer: Record = {}, + files: Record = {} +): string { + const dir = tmp('drx-backend-') + writeTree(dir, { + 'composer.json': + JSON.stringify( + { require: { 'drupal/core-recommended': '~11' }, ...composer }, + null, + 4 + ) + '\n', + ...files, + }) + return dir +} + +/** The site each change was planned for, to make an edit's content from. */ +const sites = new WeakMap() +const planned = async (dir: string, change: Promise) => { + sites.set(await change, dir) + return change +} + +const add = ( + dir: string, + needs: BackendModule[], + options: Partial = {} +) => + planned( + dir, + drupal.addModule(dir, { + needs, + patches: true, + registryStatesCore: true, + ask: answering().ask, + ...options, + }) + ) + +const runs = (change: ModuleChange) => + change.steps.flatMap((step) => + 'run' in step ? [`${step.run.tool} ${step.run.args.join(' ')}`] : [] + ) +/** The edit of a change, with the content it makes of the file as it is. */ +const edit = (change: ModuleChange) => + change.steps.flatMap((step) => { + if (!('edit' in step)) return [] + const file = join(sites.get(change) as string, step.edit.file) + const content = step.edit.change(readFileSync(file, 'utf8')) + return [{ ...step.edit, content }] + })[0] +/** What the part says was done, once every step has been taken. */ +const settled = (change: ModuleChange) => + change.settle?.( + change.steps.reduce( + (done, step) => ({ + modules: [...done.modules, ...(step.record?.modules ?? [])], + patches: [...done.patches, ...(step.record?.patches ?? [])], + }), + { modules: [], patches: [] } + ) + ) + +describe('adding the backend modules a Druxt module needs', () => { + test('requires a contributed module and enables it', async () => { + const change = await add(site(), [need('decoupled_router')]) + expect(runs(change)).toEqual([ + 'composer require -- drupal/decoupled_router', + 'drush cr', + 'drush en -y -- decoupled_router', + ]) + expect(change.record).toEqual({ + modules: [ + { + name: 'decoupled_router', + package: 'drupal/decoupled_router', + enabled: true, + required: true, + }, + ], + patches: [], + }) + expect(change.problems).toEqual([]) + }) + + test('only enables a core module', async () => { + const change = await add(site(), [need('jsonapi', { core: true })]) + expect(runs(change)).toEqual(['drush en -y -- jsonapi']) + // It has no package, and the record says it was enabled. + expect(change.record).toEqual({ + modules: [{ name: 'jsonapi', enabled: true, required: false }], + patches: [], + }) + }) + + test('requires the package and constraint the registry names', async () => { + const change = await add(site(), [ + need('menu_items', { + composer: { package: 'drupal/jsonapi_menu_items', constraint: '^1.2' }, + }), + need('views', { core: true }), + ]) + expect(runs(change)).toEqual([ + 'composer require -- drupal/jsonapi_menu_items:^1.2', + 'drush cr', + 'drush en -y -- menu_items views', + ]) + expect(change.record?.modules).toEqual([ + { + name: 'menu_items', + package: 'drupal/jsonapi_menu_items', + enabled: true, + required: true, + }, + { name: 'views', enabled: true, required: false }, + ]) + }) + + test('does not require a package the site has, and records only the enabling', async () => { + const dir = site({ + require: { + 'drupal/core-recommended': '~11', + 'drupal/decoupled_router': '^2', + }, + }) + const change = await add(dir, [need('decoupled_router')]) + expect(runs(change)).toEqual(['drush en -y -- decoupled_router']) + expect(change.notes).toContain( + 'drupal/decoupled_router is already required in composer.json.' + ) + expect(change.record?.modules).toEqual([ + { + name: 'decoupled_router', + package: 'drupal/decoupled_router', + enabled: true, + required: false, + }, + ]) + }) + + test('does not enable a module that is enabled, and does not record it', async () => { + const { ask, asked } = answering(['decoupled_router', 'views']) + const change = await add( + site(), + [need('decoupled_router'), need('views', { core: true })], + { ask } + ) + expect(asked).toEqual([ + 'drush pm:list --type=module --status=enabled --fields=name,path --format=json', + ]) + expect(runs(change)).toEqual([ + 'composer require -- drupal/decoupled_router', + 'drush cr', + ]) + expect(change.notes).toEqual([ + 'decoupled_router is already enabled.', + 'views is already enabled.', + ]) + expect(change.record?.modules).toEqual([ + { + name: 'decoupled_router', + package: 'drupal/decoupled_router', + enabled: false, + required: true, + }, + ]) + }) + + test('records what the site enabled along with it, once the steps have run', async () => { + const enabled = ['views'] + const { ask } = answering(enabled) + const change = await add(site(), [need('jsonapi_defaults')], { ask }) + expect(change.record?.modules.map(({ name }) => name)).toEqual([ + 'jsonapi_defaults', + ]) + // Drush enables what a module depends on with it. + enabled.push('jsonapi_defaults', 'jsonapi_extras') + expect(await settled(change)).toEqual({ + modules: [ + { + name: 'jsonapi_defaults', + package: 'drupal/jsonapi_defaults', + enabled: true, + required: true, + }, + { name: 'jsonapi_extras', enabled: true, required: false }, + ], + patches: [], + }) + }) + + test('records no enabling of a module that did not come up', async () => { + const { ask } = answering([]) + const change = await add(site(), [need('decoupled_router')], { ask }) + // Nothing was enabled by the time it is asked again. + expect((await settled(change))?.modules).toEqual([ + { + name: 'decoupled_router', + package: 'drupal/decoupled_router', + enabled: false, + required: true, + }, + ]) + }) + + test('enables, and records no enabling, when the site cannot say what is enabled', async () => { + const change = await add(site(), [need('views', { core: true })], { + ask: silent, + }) + expect(runs(change)).toEqual(['drush en -y -- views']) + expect(change.record?.modules).toEqual([]) + expect(change.warnings).toEqual([ + 'The backend could not say which modules are enabled. views will be enabled, and drx remove will leave it enabled, since it may have been before.', + ]) + }) + + test('has nothing to do for a module that needs nothing', async () => { + const change = await add(site(), []) + expect(change.steps).toEqual([]) + }) + + test('lists what is left to do, and does not run it', async () => { + const change = await add(site(), [ + need('simple_oauth', { + label: 'Simple OAuth', + setup: [ + { + title: 'Generate the keys', + command: 'drush simple-oauth:generate-keys ../keys', + url: 'https://example.com/keys', + }, + { title: 'Create a consumer' }, + ], + }), + ]) + expect(change.after).toEqual([ + 'Simple OAuth: Generate the keys', + ' drush simple-oauth:generate-keys ../keys', + ' https://example.com/keys', + 'Simple OAuth: Create a consumer', + ]) + expect(runs(change).join('\n')).not.toContain('generate-keys') + }) + + test('fails on a part with no composer.json', async () => { + const change = await add(tmp(), [need('decoupled_router')]) + expect(change.problems).toEqual([ + 'There is no composer.json to add decoupled_router to.', + ]) + expect(change.steps).toEqual([]) + }) +}) + +describe('telling a core module from a contributed one when the registry does not', () => { + const published = { registryStatesCore: false } + + test('looks in the core the site has installed', async () => { + const dir = site( + {}, + { 'web/core/modules/jsonapi/jsonapi.info.yml': 'name: JSON:API\n' } + ) + const change = await add( + dir, + [need('jsonapi'), need('decoupled_router')], + published + ) + expect(runs(change)).toEqual([ + 'composer require -- drupal/decoupled_router', + 'drush cr', + 'drush en -y -- jsonapi decoupled_router', + ]) + }) + + test('finds core under the web root the site names', async () => { + const dir = site( + { + extra: { 'drupal-scaffold': { locations: { 'web-root': 'docroot/' } } }, + }, + { 'docroot/core/modules/views/views.info.yml': 'name: Views\n' } + ) + expect(runs(await add(dir, [need('views')], published))).toEqual([ + 'drush en -y -- views', + ]) + }) + + test('knows a package the site already requires is contributed', async () => { + const dir = site({ + require: { + 'drupal/core-recommended': '~11', + 'drupal/decoupled_router': '^2', + }, + }) + const change = await add(dir, [need('decoupled_router')], published) + expect(change.problems).toEqual([]) + expect(runs(change)).toEqual(['drush en -y -- decoupled_router']) + }) + + test('refuses to guess when core is not installed, and takes no step', async () => { + const change = await add(site(), [need('jsonapi')], published) + expect(change.problems).toEqual([ + 'Cannot tell whether jsonapi is part of core or a package to require: the module registry does not say, and core is not installed in this part to look in. Install the dependencies of the backend, then run this again.', + ]) + expect(change.steps).toEqual([]) + }) +}) + +describe('the patches a backend module needs', () => { + const patched = (extra: Partial = {}) => + need('decoupled_router', { + label: 'Decoupled Router', + patches: [ + { + description: 'Fix the redirect loop', + url: 'https://example.com/mr/12.diff', + issue: 'https://example.com/issue/12', + }, + { + description: 'Fix core', + url: 'https://example.com/mr/9.diff', + package: 'drupal/core', + until: '11.3.0', + }, + ], + ...extra, + }) + + test('are written to extra.patches, with the plugin required and allowed', async () => { + const dir = site() + const change = await add(dir, [patched()]) + const written = JSON.parse(edit(change)?.content ?? '{}') + expect(written.extra.patches).toEqual({ + 'drupal/decoupled_router': { + 'Fix the redirect loop': 'https://example.com/mr/12.diff', + }, + 'drupal/core': { 'Fix core': 'https://example.com/mr/9.diff' }, + }) + expect(written.config['allow-plugins'][PLUGIN]).toBe(true) + expect(written.require).toEqual({ 'drupal/core-recommended': '~11' }) + expect(edit(change)?.file).toBe('composer.json') + expect(edit(change)?.summary).toBe('Add 2 patches to composer.json') + // Composer's own four spaces, and the newline the file ends with. + expect(edit(change)?.content).toMatch(/^\{\n {4}"require"/) + expect(edit(change)?.content.endsWith('}\n')).toBe(true) + + expect(change.steps.map((step) => Object.keys(step)[0])[0]).toBe('edit') + // Neither package is installed yet: each is patched as it is installed. + expect(runs(change)).toEqual([ + `composer require -- ${PLUGIN}:^2.0@beta`, + 'composer patches-relock', + 'composer require -- drupal/decoupled_router', + 'drush cr', + 'drush en -y -- decoupled_router', + ]) + expect(change.record?.patches).toEqual([ + { + package: 'drupal/decoupled_router', + description: 'Fix the redirect loop', + url: 'https://example.com/mr/12.diff', + module: 'decoupled_router', + }, + { + package: 'drupal/core', + description: 'Fix core', + url: 'https://example.com/mr/9.diff', + module: 'decoupled_router', + }, + ]) + }) + + test('are applied in place to a package that is installed, required or not', async () => { + // Another package brought it in: composer.json does not require it. + const dir = site( + {}, + { + 'vendor/composer/installed.json': { + packages: [{ name: 'drupal/decoupled_router', version: '2.0.7' }], + }, + } + ) + const change = await add(dir, [ + patched({ + patches: [ + { + description: 'Fix the redirect loop', + url: 'https://example.com/mr/12.diff', + }, + ], + }), + ]) + expect(runs(change)).toEqual([ + `composer require -- ${PLUGIN}:^2.0@beta`, + 'composer patches-relock', + 'composer require -- drupal/decoupled_router', + 'composer patches-repatch', + 'drush cr', + 'drush en -y -- decoupled_router', + ]) + }) + + test('are refused when one is not served over https, and nothing is planned', async () => { + const change = await add(site(), [ + patched({ + patches: [ + { + description: 'Fix the redirect loop', + url: 'http://example.com/mr/12.diff', + }, + ], + }), + ]) + expect(change.steps).toEqual([]) + expect(change.problems).toEqual([ + 'The patch "Fix the redirect loop" that decoupled_router needs is at http://example.com/mr/12.diff, and Composer only fetches a patch over https. Pass --no-patches to add the module without it.', + ]) + }) + + test('are each shown with the issue they belong to', async () => { + const change = await add(site(), [patched()]) + expect(change.notes).toEqual([ + 'Patch for drupal/decoupled_router: Fix the redirect loop (https://example.com/issue/12)', + 'Patch for drupal/core: Fix core', + ]) + }) + + test('leave the plugin alone when the site has it, and keep its other patches', async () => { + const dir = site({ + require: { 'drupal/core-recommended': '~11', [PLUGIN]: '^2.0' }, + extra: { + patches: { 'drupal/druxt': { 'A local fix': 'patches/a.patch' } }, + }, + }) + const change = await add(dir, [patched()]) + const written = JSON.parse(edit(change)?.content ?? '{}') + expect(written.extra.patches['drupal/druxt']).toEqual({ + 'A local fix': 'patches/a.patch', + }) + expect(written.config).toBeUndefined() + expect(runs(change)).not.toContain( + `composer require -- ${PLUGIN}:^2.0@beta` + ) + }) + + test('skip one whose fix the installed package has', async () => { + const dir = site( + {}, + { + 'vendor/composer/installed.json': { + packages: [{ name: 'drupal/core', version: '11.3.2' }], + }, + } + ) + const change = await add(dir, [patched()]) + expect(JSON.parse(edit(change)?.content ?? '{}').extra.patches).toEqual({ + 'drupal/decoupled_router': { + 'Fix the redirect loop': 'https://example.com/mr/12.diff', + }, + }) + expect(change.notes).toContain( + 'The patch "Fix core" is not needed: drupal/core 11.3.2 has the fix, which came in 11.3.0.' + ) + expect(change.record?.patches).toHaveLength(1) + }) + + test('skip one the site already carries, and do not record it', async () => { + const dir = site( + { + require: { 'drupal/core-recommended': '~11', [PLUGIN]: '^2.0' }, + extra: { + patches: { + 'drupal/decoupled_router': { + Theirs: 'https://example.com/mr/12.diff', + }, + }, + }, + }, + { + 'patches.lock.json': { + patches: { + 'drupal/decoupled_router': [ + { description: 'Theirs', url: 'https://example.com/mr/12.diff' }, + ], + }, + }, + } + ) + const change = await add(dir, [ + patched({ + patches: [ + { + description: 'Fix the redirect loop', + url: 'https://example.com/mr/12.diff', + }, + ], + }), + ]) + expect(edit(change)).toBeUndefined() + expect(change.record?.patches).toEqual([]) + expect(change.notes).toContain( + 'The patch "Fix the redirect loop" is already in composer.json.' + ) + }) + + describe('one that composer.json already lists', () => { + const ONE = { + description: 'Fix the redirect loop', + url: 'https://example.com/mr/12.diff', + } + const listing = { + require: { 'drupal/core-recommended': '~11', [PLUGIN]: '^2.0@beta' }, + extra: { + patches: { 'drupal/decoupled_router': { [ONE.description]: ONE.url } }, + }, + } + const LOCKED = { + 'patches.lock.json': { + patches: { 'drupal/decoupled_router': [{ ...ONE, depth: 1 }] }, + }, + } + const INSTALLED = (extra: Record = {}) => ({ + 'vendor/composer/installed.json': { + packages: [ + { name: 'drupal/decoupled_router', version: '2.0.7', ...extra }, + ], + }, + }) + const again = (dir: string) => add(dir, [patched({ patches: [ONE] })]) + + test('is locked and applied when the lock file does not have it', async () => { + // An earlier run wrote the patch and stopped before it was locked. + const change = await again(site(listing, INSTALLED())) + expect(edit(change)).toBeUndefined() + expect(runs(change)).toEqual([ + 'composer patches-relock', + 'composer require -- drupal/decoupled_router', + 'composer patches-repatch', + 'drush cr', + 'drush en -y -- decoupled_router', + ]) + expect(change.notes).toContain( + 'The patch "Fix the redirect loop" is in composer.json and not in patches.lock.json, so the patches are locked again.' + ) + expect(change.notes).not.toContain( + 'The patch "Fix the redirect loop" is already in composer.json.' + ) + // It was written by the run before, whose record has it. + expect(change.record?.patches).toEqual([]) + }) + + test('is locked with an empty lock file as well', async () => { + const dir = site(listing, { 'patches.lock.json': { patches: [] } }) + expect(runs(await again(dir))).toEqual([ + 'composer patches-relock', + 'composer require -- drupal/decoupled_router', + 'drush cr', + 'drush en -y -- decoupled_router', + ]) + }) + + test('gets the plugin first when that is what the earlier run stopped at', async () => { + const dir = site({ + extra: listing.extra, + config: { 'allow-plugins': { [PLUGIN]: true } }, + }) + const change = await again(dir) + expect(edit(change)).toBeUndefined() + expect(runs(change).slice(0, 2)).toEqual([ + `composer require -- ${PLUGIN}:^2.0@beta`, + 'composer patches-relock', + ]) + expect(change.record?.patcher).toEqual({ required: true, allowed: false }) + }) + + test('has the plugin allowed again when the site no longer allows it', async () => { + const dir = site({ extra: listing.extra }) + const change = await again(dir) + expect(edit(change)?.summary).toBe(`Allow ${PLUGIN} in composer.json`) + const written = JSON.parse(edit(change)?.content ?? '{}') + expect(written.config['allow-plugins']).toEqual({ [PLUGIN]: true }) + expect(written.extra).toEqual(listing.extra) + }) + + test('is installed again on a package nothing says it was applied to', async () => { + const dir = site( + { + ...listing, + require: { ...listing.require, 'drupal/decoupled_router': '^2.0' }, + }, + { ...LOCKED, ...INSTALLED() } + ) + const change = await again(dir) + expect(runs(change)).toEqual([ + 'composer reinstall -- drupal/decoupled_router', + 'drush en -y -- decoupled_router', + ]) + expect(change.notes).toContain( + 'The patch "Fix the redirect loop" is locked, and nothing on the site says drupal/decoupled_router was installed with it, so the package is installed again.' + ) + }) + + test('is left alone once it is locked and the package says it is applied', async () => { + const dir = site(listing, { + ...LOCKED, + ...INSTALLED({ + extra: { patches_applied: { [ONE.description]: ONE.url } }, + }), + }) + const change = await again(dir) + expect(runs(change)).toEqual([ + 'composer require -- drupal/decoupled_router', + 'drush cr', + 'drush en -y -- decoupled_router', + ]) + expect(change.notes).toContain( + 'The patch "Fix the redirect loop" is already in composer.json.' + ) + }) + + test('is left alone once it is locked, for a package still to install', async () => { + const change = await again(site(listing, LOCKED)) + expect(runs(change)).toEqual([ + 'composer require -- drupal/decoupled_router', + 'drush cr', + 'drush en -y -- decoupled_router', + ]) + }) + }) + + describe('the plugin that applies them', () => { + test('is recorded as added, with its permission, on a site without it', async () => { + const change = await add(site(), [patched()]) + expect(change.record?.patcher).toEqual({ required: true, allowed: true }) + // Each step says its own part, for a run that stops between them. + expect(change.steps.map((step) => step.record?.patcher)).toEqual([ + { required: false, allowed: true }, + { required: true, allowed: false }, + undefined, + undefined, + undefined, + undefined, + ]) + }) + + test('is recorded without the permission where every plugin is allowed', async () => { + const dir = site({ config: { 'allow-plugins': true } }) + const change = await add(dir, [patched()]) + expect(change.record?.patcher).toEqual({ required: true, allowed: false }) + }) + + test('is not recorded on a site that had it', async () => { + const dir = site({ + require: { 'drupal/core-recommended': '~11', [PLUGIN]: '^2.0' }, + }) + const change = await add(dir, [patched()]) + expect(change.record).not.toHaveProperty('patcher') + expect(change.steps.some((step) => step.record?.patcher)).toBe(false) + }) + }) + + test('are left out, with a warning, when patches are turned off', async () => { + const change = await add(site(), [patched()], { patches: false }) + expect(edit(change)).toBeUndefined() + expect(runs(change)).toEqual([ + 'composer require -- drupal/decoupled_router', + 'drush cr', + 'drush en -y -- decoupled_router', + ]) + expect(change.warnings).toEqual([ + 'The patch "Fix the redirect loop" for drupal/decoupled_router was not applied. Decoupled Router may not work without it.', + 'The patch "Fix core" for drupal/core was not applied. Decoupled Router may not work without it.', + ]) + }) +}) + +describe('a backend that is not run from here', () => { + // No `ask`: nothing in the part can be looked at. + const elsewhere = (dir: string, needs: BackendModule[]) => + drupal.addModule(dir, { + needs, + patches: true, + registryStatesCore: false, + }) + + test('gets the lines for a module that may be core, and the doubt is said', async () => { + const change = await elsewhere(site(), [ + need('jsonapi_menu_items'), + need('menu_link_content'), + ]) + expect(change.problems).toEqual([]) + expect(runs(change)).toEqual([ + 'composer require -- drupal/jsonapi_menu_items drupal/menu_link_content', + 'drush cr', + 'drush en -y -- jsonapi_menu_items menu_link_content', + ]) + expect(change.manual).toEqual([ + 'The module registry does not say whether jsonapi_menu_items or menu_link_content is part of core. Leave a module that is out of the composer require line: only the enable line applies to it.', + ]) + }) + + test('needs no composer.json to print them', async () => { + const change = await elsewhere(tmp('drx-nothing-'), [ + need('block', { core: true }), + ]) + expect(change.problems).toEqual([]) + expect(runs(change)).toEqual(['drush en -y -- block']) + }) +}) + +describe('taking backend modules out again', () => { + const ROUTER = 'decoupled_router' + const MENU = 'jsonapi_menu_items' + const record: BackendRecord = { + modules: [ + { + name: ROUTER, + package: 'drupal/decoupled_router', + enabled: true, + required: true, + }, + { + name: MENU, + package: 'drupal/jsonapi_menu_items', + enabled: true, + required: true, + }, + ], + patches: [ + { + package: 'drupal/decoupled_router', + description: 'Fix the redirect loop', + url: 'https://example.com/mr/12.diff', + module: ROUTER, + }, + ], + } + const carrying = (files: Record = {}) => + site( + { + extra: { + patches: { + 'drupal/decoupled_router': { + 'Fix the redirect loop': 'https://example.com/mr/12.diff', + 'Their own': 'patches/own.patch', + }, + }, + }, + }, + files + ) + const remove = (dir: string, ask: Ask, given = record) => + planned(dir, drupal.removeModule(dir, { record: given, ask })) + + test('uninstalls and removes what the record says was added', async () => { + const { ask, asked } = answering([ROUTER, MENU]) + const change = await remove(carrying(), ask) + // Each module is asked about twice: the list is asked for once. + expect(asked).toEqual([ + 'drush pm:uninstall --simulate -- decoupled_router', + 'drush pm:list --type=module --status=enabled --fields=name,path --format=json', + 'drush pm:uninstall --simulate -- jsonapi_menu_items', + ]) + expect(runs(change)).toEqual([ + 'drush pmu -y -- decoupled_router jsonapi_menu_items', + 'composer remove --no-update-with-dependencies -- drupal/decoupled_router drupal/jsonapi_menu_items', + 'composer patches-relock', + 'drush cr', + ]) + expect(JSON.parse(edit(change)?.content ?? '{}').extra.patches).toEqual({ + 'drupal/decoupled_router': { 'Their own': 'patches/own.patch' }, + }) + expect(edit(change)?.summary).toBe('Remove 1 patch from composer.json') + expect(change.record).toBeUndefined() + }) + + test('leaves a module an enabled module depends on, with its requirement and patch', async () => { + const { ask } = answering([ROUTER, MENU, 'druxt'], { [ROUTER]: ['druxt'] }) + const change = await remove(carrying(), ask) + expect(runs(change)).toEqual([ + 'drush pmu -y -- jsonapi_menu_items', + 'composer remove --no-update-with-dependencies -- drupal/jsonapi_menu_items', + 'drush cr', + ]) + expect(edit(change)).toBeUndefined() + expect(change.notes).toEqual([ + 'decoupled_router stays enabled: druxt depends on it.', + ]) + expect(change.record).toEqual({ + modules: [record.modules[0]], + patches: record.patches, + }) + }) + + test('uninstalls two modules of the record that depend on each other', async () => { + const { ask } = answering([ROUTER, MENU], { [ROUTER]: [MENU] }) + const change = await remove(carrying(), ask) + expect(runs(change)[0]).toBe( + 'drush pmu -y -- decoupled_router jsonapi_menu_items' + ) + }) + + test('leaves a module whose dependent is itself held', async () => { + // MENU depends on ROUTER, and druxt on MENU: neither can go. + const { ask } = answering([ROUTER, MENU, 'druxt'], { + [ROUTER]: [MENU, 'druxt'], + [MENU]: ['druxt'], + }) + const change = await remove(carrying(), ask) + expect(runs(change)).toEqual([]) + expect(change.record?.modules).toHaveLength(2) + }) + + test('uninstalls nothing it cannot ask about, and gives the command', async () => { + const change = await remove(carrying(), silent) + expect(change.steps).toEqual([]) + expect(change.manual).toEqual([ + 'The backend could not say what depends on decoupled_router, so it was left enabled. Once nothing does: drush pm:uninstall decoupled_router, then composer remove drupal/decoupled_router', + 'The backend could not say what depends on jsonapi_menu_items, so it was left enabled. Once nothing does: drush pm:uninstall jsonapi_menu_items, then composer remove drupal/jsonapi_menu_items', + ]) + expect(change.record).toEqual(record) + }) + + test('does not uninstall a module that is no longer enabled, and removes its package', async () => { + const { ask } = answering([MENU]) + const change = await remove(carrying(), ask) + expect(runs(change)[0]).toBe('drush pmu -y -- jsonapi_menu_items') + expect(change.notes).toContain( + 'decoupled_router is not enabled, so it is not uninstalled.' + ) + expect(runs(change)[1]).toBe( + 'composer remove --no-update-with-dependencies -- drupal/decoupled_router drupal/jsonapi_menu_items' + ) + }) + + describe('a requirement on a module the site had enabled', () => { + const only: BackendRecord = { + modules: [ + { + name: 'jsonapi_views', + package: 'drupal/jsonapi_views', + enabled: false, + required: true, + }, + ], + patches: [], + } + const installed = (requires: Record) => ({ + 'vendor/composer/installed.json': { + packages: [ + { name: 'drupal/jsonapi_views', version: '1.2.0' }, + { name: 'drupal/druxt', version: '1.3.1', require: requires }, + ], + }, + }) + + test('comes out of composer.json alone while another package brings the module in', async () => { + const dir = site({}, installed({ 'drupal/jsonapi_views': '^1.1' })) + const { ask, asked } = answering(['jsonapi_views', 'druxt']) + const change = await remove(dir, ask, only) + // Composer's remove fails on a package that is still installed. + expect(runs(change)).toEqual([ + 'composer remove --no-update -- drupal/jsonapi_views', + 'composer update --lock', + ]) + expect(asked).toEqual([]) + expect(change.record).toBeUndefined() + }) + + test('stays while the module is enabled and nothing else brings it in', async () => { + const dir = site({}, installed({})) + const { ask } = answering(['jsonapi_views']) + const change = await remove(dir, ask, only) + expect(change.steps).toEqual([]) + expect(change.notes).toEqual([ + 'drupal/jsonapi_views stays required: jsonapi_views was enabled before drx add, and nothing else brings it in.', + ]) + expect(change.record).toEqual(only) + }) + + test('goes once the module is no longer enabled', async () => { + const { ask } = answering([]) + const change = await remove(site({}, installed({})), ask, only) + expect(runs(change)).toEqual([ + 'composer remove --no-update-with-dependencies -- drupal/jsonapi_views', + 'drush cr', + ]) + }) + }) + + test('keeps a package that holds a module that is still enabled', async () => { + // jsonapi_extras came up with jsonapi_defaults and is in the same package. + const given: BackendRecord = { + modules: [ + { + name: 'jsonapi_defaults', + package: 'drupal/jsonapi_extras', + enabled: true, + required: true, + }, + ], + patches: [], + } + const dir = site( + {}, + { + 'vendor/composer/installed.json': { + packages: [ + { + name: 'drupal/jsonapi_extras', + version: '3.28.0', + 'install-path': '../../web/modules/contrib/jsonapi_extras', + }, + ], + }, + } + ) + const { ask } = answering( + ['jsonapi_defaults', 'jsonapi_extras'], + {}, + { + jsonapi_defaults: + 'modules/contrib/jsonapi_extras/modules/jsonapi_defaults', + } + ) + const change = await remove(dir, ask, given) + expect(runs(change)).toEqual(['drush pmu -y -- jsonapi_defaults']) + expect(change.notes).toEqual([ + 'drupal/jsonapi_extras stays required: jsonapi_extras is enabled, and its files are in that package.', + ]) + // The requirement stays on the record, and the enabling is undone. + expect(change.record).toEqual({ + modules: [{ ...given.modules[0], enabled: false }], + patches: [], + }) + }) + + test('reinstalls a package that stays installed once its patch is gone', async () => { + const dir = carrying({ + 'vendor/composer/installed.json': { + packages: [ + { name: 'drupal/decoupled_router', version: '2.0.7' }, + { + name: 'drupal/druxt', + version: '1.3.1', + require: { 'drupal/decoupled_router': '^2.0' }, + }, + ], + }, + }) + const { ask } = answering([ROUTER, MENU]) + const change = await remove(dir, ask) + expect(runs(change)).toEqual([ + 'drush pmu -y -- decoupled_router jsonapi_menu_items', + 'composer remove --no-update -- drupal/decoupled_router', + 'composer remove --no-update-with-dependencies -- drupal/jsonapi_menu_items', + 'composer patches-relock', + 'composer reinstall -- drupal/decoupled_router', + 'drush cr', + ]) + }) + + test('keeps every patch of a record that does not say what each was for', async () => { + const old: BackendRecord = { + modules: record.modules, + patches: record.patches.map(({ package: pkg, description, url }) => ({ + package: pkg, + description, + url, + })), + } + const { ask } = answering([ROUTER, MENU, 'druxt'], { [MENU]: ['druxt'] }) + const change = await remove(carrying(), ask, old) + expect(edit(change)).toBeUndefined() + expect(change.record?.patches).toEqual(old.patches) + }) + + test('drops the patches key when its last patch goes', async () => { + const dir = site({ + extra: { + patches: { + 'drupal/decoupled_router': { + 'Fix the redirect loop': 'https://example.com/mr/12.diff', + }, + }, + }, + }) + const change = await remove(dir, answering([ROUTER, MENU]).ask) + // With the key gone `extra` is empty, and goes as well. + expect(JSON.parse(edit(change)?.content ?? '{}').extra).toBeUndefined() + }) + + test('keeps what else the site has under extra', async () => { + const dir = site({ + extra: { + 'drupal-scaffold': { locations: { 'web-root': 'web/' } }, + patches: { + 'drupal/decoupled_router': { + 'Fix the redirect loop': 'https://example.com/mr/12.diff', + }, + }, + }, + }) + const change = await remove(dir, answering([ROUTER, MENU]).ask) + expect(JSON.parse(edit(change)?.content ?? '{}').extra).toEqual({ + 'drupal-scaffold': { locations: { 'web-root': 'web/' } }, + }) + }) + + describe('a site whose two answers about a module differ', () => { + const LEFT = + 'Rebuild its caches with drush cr and run this again, or once nothing depends on it: drush pm:uninstall decoupled_router, then composer remove drupal/decoupled_router' + + test('keeps a module the list has enabled and a simulated uninstall does not', async () => { + // A cached container from before the module was enabled. + const { ask } = answering([ROUTER, MENU], {}, {}, [MENU]) + const change = await remove(carrying(), ask) + expect(runs(change)).toEqual([ + 'drush pmu -y -- jsonapi_menu_items', + 'composer remove --no-update-with-dependencies -- drupal/jsonapi_menu_items', + 'drush cr', + ]) + expect(change.notes).toEqual([]) + expect(change.manual).toEqual([ + `The backend gave two answers about whether decoupled_router is enabled, so it was left as it is. ${LEFT}`, + ]) + expect(edit(change)).toBeUndefined() + // Nothing about it is rewritten: it is still one the add enabled. + expect(change.record).toEqual({ + modules: [record.modules[0]], + patches: record.patches, + }) + }) + + test('keeps a module a simulated uninstall has enabled and the list does not', async () => { + const { ask } = answering([MENU], {}, {}, [ROUTER, MENU]) + const change = await remove(carrying(), ask) + expect(runs(change)[0]).toBe('drush pmu -y -- jsonapi_menu_items') + expect(change.manual).toEqual([ + `The backend gave two answers about whether decoupled_router is enabled, so it was left as it is. ${LEFT}`, + ]) + expect(change.record?.modules).toEqual([record.modules[0]]) + }) + + test('keeps every module when the list cannot be had', async () => { + const { ask } = answering([ROUTER, MENU], {}, {}, [MENU], false) + const change = await remove(carrying(), ask) + expect(change.steps).toEqual([]) + expect(change.manual[0]).toBe( + `The backend could not say whether decoupled_router is enabled, so it was left as it is. ${LEFT}` + ) + expect(change.record).toEqual(record) + }) + + test('keeps the requirement of a module the site had enabled', async () => { + const only: BackendRecord = { + modules: [ + { + name: 'jsonapi_views', + package: 'drupal/jsonapi_views', + enabled: false, + required: true, + }, + ], + patches: [], + } + // The list says it is off now, and a simulated uninstall that it is on. + const { ask } = answering([], {}, {}, ['jsonapi_views']) + const change = await remove(site(), ask, only) + expect(change.steps).toEqual([]) + expect(change.record).toEqual(only) + }) + }) + + describe('the plugin that applies patches', () => { + const added: BackendRecord = { + ...record, + patcher: { required: true, allowed: true }, + } + const patchedSite = ( + extra: Record = {}, + files: Record = {} + ) => + site( + { + require: { + 'drupal/core-recommended': '~11', + [PLUGIN]: '^2.0@beta', + 'drupal/decoupled_router': '^2.0', + }, + config: { + 'sort-packages': true, + 'allow-plugins': { 'composer/installers': true, [PLUGIN]: true }, + }, + extra: { + patches: { + 'drupal/decoupled_router': { + 'Fix the redirect loop': 'https://example.com/mr/12.diff', + }, + }, + }, + ...extra, + }, + files + ) + /** Each edit of a change, made of what the edit before it wrote. */ + const edited = (change: ModuleChange) => { + const file = join(sites.get(change) as string, 'composer.json') + let source = readFileSync(file, 'utf8') + return change.steps.flatMap((step) => { + if (!('edit' in step)) return [] + source = step.edit.change(source) + return [{ summary: step.edit.summary, json: JSON.parse(source) }] + }) + } + + test('goes with the last patch when the record says the add put it there', async () => { + const change = await remove( + patchedSite(), + answering([ROUTER, MENU]).ask, + added + ) + expect(runs(change)).toEqual([ + 'drush pmu -y -- decoupled_router jsonapi_menu_items', + 'composer remove --no-update-with-dependencies -- drupal/decoupled_router drupal/jsonapi_menu_items', + 'composer patches-relock', + `composer remove -- ${PLUGIN}`, + 'drush cr', + ]) + // The permission goes once the plugin has, or Composer would stop it. + const kinds = change.steps.map((step) => Object.keys(step)[0]) + expect(kinds).toEqual([ + 'run', + 'edit', + 'run', + 'run', + 'run', + 'edit', + 'remove', + 'run', + ]) + const [patches, permission] = edited(change) + expect(patches?.summary).toBe('Remove 1 patch from composer.json') + expect(patches?.json.config['allow-plugins'][PLUGIN]).toBe(true) + expect(permission?.summary).toBe( + `Remove ${PLUGIN} from allow-plugins in composer.json` + ) + expect(permission?.json.config).toEqual({ + 'sort-packages': true, + 'allow-plugins': { 'composer/installers': true }, + }) + expect(change.record).toBeUndefined() + }) + + test('takes its lock file with it once that holds no patch', async () => { + const change = await remove( + patchedSite(), + answering([ROUTER, MENU]).ask, + added + ) + const removal = change.steps.flatMap((step) => + 'remove' in step ? [step.remove] : [] + )[0] + expect(removal?.file).toBe('patches.lock.json') + expect(removal?.summary).toBe('Delete patches.lock.json') + expect(removal?.when('{"_hash": "x", "patches": []}')).toBe(true) + expect(removal?.when('{"patches": {}}')).toBe(true) + expect(removal?.when('{"patches": {"a/b": [{"url": "x"}]}}')).toBe(false) + expect(removal?.when('not json')).toBe(false) + }) + + test('takes an allow-plugins it leaves empty, and a config that leaves empty', async () => { + const dir = patchedSite({ + config: { 'allow-plugins': { [PLUGIN]: true } }, + }) + const change = await remove(dir, answering([ROUTER, MENU]).ask, added) + expect(edited(change)[1]?.json.config).toBeUndefined() + }) + + test('stays while composer.json has another patch, and stays on the record', async () => { + const dir = patchedSite({ + extra: { + patches: { + 'drupal/decoupled_router': { + 'Fix the redirect loop': 'https://example.com/mr/12.diff', + }, + 'drupal/druxt': { 'Their own': 'patches/own.patch' }, + }, + }, + }) + const change = await remove(dir, answering([ROUTER, MENU]).ask, added) + expect(runs(change).join('\n')).not.toContain(PLUGIN) + expect(edited(change)).toHaveLength(1) + expect(change.record).toEqual({ + modules: [], + patches: [], + patcher: added.patcher, + }) + }) + + test('stays when the record does not say the add put it there', async () => { + const change = await remove(patchedSite(), answering([ROUTER, MENU]).ask) + expect(runs(change).join('\n')).not.toContain(PLUGIN) + expect(edited(change)).toHaveLength(1) + expect(change.steps.some((step) => 'remove' in step)).toBe(false) + }) + + test('keeps a permission the site had, and takes only the requirement', async () => { + const change = await remove( + patchedSite(), + answering([ROUTER, MENU]).ask, + { + ...record, + patcher: { required: true, allowed: false }, + } + ) + expect(runs(change)).toContain(`composer remove -- ${PLUGIN}`) + expect(edited(change)).toHaveLength(1) + }) + + test('keeps a requirement the site had, and takes only the permission', async () => { + const change = await remove( + patchedSite(), + answering([ROUTER, MENU]).ask, + { + ...record, + patcher: { required: false, allowed: true }, + } + ) + expect(runs(change).join('\n')).not.toContain(`-- ${PLUGIN}`) + expect(edited(change)[1]?.json.config['allow-plugins']).toEqual({ + 'composer/installers': true, + }) + expect(change.steps.some((step) => 'remove' in step)).toBe(false) + }) + + test('comes out of composer.json alone while another package requires it', async () => { + const dir = patchedSite( + {}, + { + 'vendor/composer/installed.json': { + packages: [ + { name: PLUGIN, version: '2.0.0' }, + { + name: 'acme/tools', + version: '1.0.0', + require: { [PLUGIN]: '^2' }, + }, + ], + }, + } + ) + const change = await remove(dir, answering([ROUTER, MENU]).ask, added) + // Composer's remove fails on a package that is still installed. + expect(runs(change)).toEqual([ + 'drush pmu -y -- decoupled_router jsonapi_menu_items', + `composer remove --no-update -- ${PLUGIN}`, + 'composer remove --no-update-with-dependencies -- drupal/decoupled_router drupal/jsonapi_menu_items', + 'composer patches-relock', + 'drush cr', + ]) + // The plugin is still installed, and so its lock file stays. + expect(change.steps.some((step) => 'remove' in step)).toBe(false) + }) + + test('stays with a module that stays, whose patch it applies', async () => { + const { ask } = answering([ROUTER, MENU, 'druxt'], { + [ROUTER]: ['druxt'], + }) + const change = await remove(patchedSite(), ask, added) + expect(runs(change).join('\n')).not.toContain(PLUGIN) + expect(change.record?.patcher).toEqual(added.patcher) + }) + }) + + test('rebuilds the caches after Composer has changed what is installed', async () => { + const change = await remove(carrying(), answering([ROUTER, MENU]).ask) + expect(runs(change).at(-1)).toBe('drush cr') + // Nothing installed changes when only the manifest does. + const kept = await remove( + carrying(), + answering([ROUTER, MENU, 'druxt'], { + [ROUTER]: ['druxt'], + [MENU]: ['druxt'], + }).ask + ) + expect(runs(kept)).toEqual([]) + }) + + test('does nothing with no record', async () => { + const change = await drupal.removeModule(carrying(), {}) + expect(change.steps).toEqual([]) + }) +}) diff --git a/packages/cli/test/adapters/nuxt-modules.test.ts b/packages/cli/test/adapters/nuxt-modules.test.ts new file mode 100644 index 0000000..a3969dd --- /dev/null +++ b/packages/cli/test/adapters/nuxt-modules.test.ts @@ -0,0 +1,456 @@ +import { readFileSync } from 'node:fs' +import { join } from 'node:path' +import { fileURLToPath } from 'node:url' +import { afterEach, describe, expect, test } from 'vitest' +import { adapterFor } from '../../src/adapters/index.js' +import type { ModuleChange } from '../../src/adapters/adapter.js' +import { cleanTmp, tmp, writeTree } from '../helpers/tmp.js' + +afterEach(cleanTmp) + +const nuxt = adapterFor('nuxt')! +/** The quickstart starter's own config, byte for byte. */ +const QUICKSTART = readFileSync( + fileURLToPath( + new URL('../fixtures/quickstart-nuxt.config.js', import.meta.url) + ), + 'utf8' +) +const NUXT_4 = `// https://nuxt.com/docs/api/configuration/nuxt-config +export default defineNuxtConfig({ + compatibilityDate: '2025-07-15', + devtools: { enabled: true }, + modules: ['@nuxt/eslint'], +}) +` + +/** The part each change was planned for, to make an edit's content from. */ +const parts = new WeakMap() +const planned = async (dir: string, change: Promise) => { + parts.set(await change, dir) + return change +} + +const add = (dir: string, name = 'druxt-breadcrumb', root?: string) => + planned( + dir, + nuxt.addModule(dir, { + package: name, + needs: [], + patches: true, + registryStatesCore: false, + ...(root ? { root } : {}), + }) + ) +const DID = { installed: true, listed: true } +const remove = ( + dir: string, + name = 'druxt-breadcrumb', + did = DID, + root?: string +) => + planned( + dir, + nuxt.removeModule(dir, { package: name, did, ...(root ? { root } : {}) }) + ) + +const runs = (change: ModuleChange) => + change.steps.flatMap((step) => ('run' in step ? [step.run] : [])) +/** The edits of a change, each with the content it makes of the file now. */ +const edits = (change: ModuleChange) => + change.steps.flatMap((step) => { + if (!('edit' in step)) return [] + const file = join(parts.get(change) as string, step.edit.file) + const content = step.edit.change(readFileSync(file, 'utf8')) + return [{ ...step.edit, content }] + }) + +function part(files: Record): string { + const dir = tmp('drx-part-') + writeTree(dir, { 'package.json': {}, ...files }) + return dir +} + +describe('the package manager of a frontend part', () => { + test.each([ + [ + 'package-lock.json', + 'npm', + ['install', '--', 'druxt-breadcrumb'], + ['uninstall', '--', 'druxt-breadcrumb'], + ], + [ + 'pnpm-lock.yaml', + 'pnpm', + ['add', '--', 'druxt-breadcrumb'], + ['remove', '--', 'druxt-breadcrumb'], + ], + [ + 'yarn.lock', + 'yarn', + ['add', '--', 'druxt-breadcrumb'], + ['remove', '--', 'druxt-breadcrumb'], + ], + // Not known to take the separator, so it is left out. + [ + 'bun.lock', + 'bun', + ['add', 'druxt-breadcrumb'], + ['remove', 'druxt-breadcrumb'], + ], + [ + 'README.md', + 'npm', + ['install', '--', 'druxt-breadcrumb'], + ['uninstall', '--', 'druxt-breadcrumb'], + ], + ])('with %s is %s', async (lock, tool, installArgs, removeArgs) => { + const dir = part({ + [lock]: '', + 'package.json': { dependencies: { 'druxt-breadcrumb': '^0.1.0' } }, + 'nuxt.config.js': 'export default { modules: [] }\n', + }) + expect(runs(await add(part({ [lock]: '' })))).toEqual([ + { tool, args: installArgs }, + ]) + expect(runs(await remove(dir))).toEqual([{ tool, args: removeArgs }]) + }) + + /** A project whose frontend part is one directory down from its root. */ + function workspace( + rootFiles: Record, + partFiles: Record = {} + ) { + const root = tmp('drx-root-') + writeTree(root, { + ...rootFiles, + 'web/package.json': {}, + ...Object.fromEntries( + Object.entries(partFiles).map(([file, content]) => [ + `web/${file}`, + content, + ]) + ), + }) + return { root, dir: join(root, 'web') } + } + const tool = async ( + rootFiles: Record, + partFiles: Record = {} + ) => { + const { root, dir } = workspace(rootFiles, partFiles) + const added = runs(await add(dir, 'druxt-breadcrumb', root))[0]?.tool + writeTree(dir, { + 'package.json': { + ...(partFiles['package.json'] as object), + dependencies: { 'druxt-breadcrumb': '^0.1.0' }, + }, + }) + const removed = runs(await remove(dir, 'druxt-breadcrumb', DID, root))[0] + expect(removed?.tool).toBe(added) + return added + } + + test('is the one the root of the project declares, with no lock file yet', async () => { + expect( + await tool({ 'package.json': { packageManager: 'pnpm@10.4.1' } }) + ).toBe('pnpm') + }) + + test('is the one of a lock file at the root of a workspace', async () => { + expect(await tool({ 'package.json': {}, 'yarn.lock': '' })).toBe('yarn') + expect(await tool({ 'pnpm-lock.yaml': '' })).toBe('pnpm') + }) + + test('is the declared one before that of any lock file', async () => { + expect( + await tool( + { 'package.json': { packageManager: 'yarn@4.5.0' } }, + { 'package-lock.json': '{}' } + ) + ).toBe('yarn') + expect( + await tool( + { 'yarn.lock': '' }, + { 'package.json': { packageManager: 'pnpm@9.0.0' } } + ) + ).toBe('pnpm') + }) + + test('is the one the root declares before the one the part declares', async () => { + expect( + await tool( + { 'package.json': { packageManager: 'npm@11.0.0' } }, + { 'package.json': { packageManager: 'pnpm@9.0.0' } } + ) + ).toBe('npm') + }) + + test('is npm for a manager it does not know, and with nothing to go by', async () => { + expect( + await tool({ 'package.json': { packageManager: 'vlt@1.0.0' } }) + ).toBe('npm') + expect(await tool({})).toBe('npm') + }) + + test('does not look above the root of the project', async () => { + const outer = tmp('drx-outer-') + writeTree(outer, { + 'package.json': { packageManager: 'pnpm@10.4.1' }, + 'pnpm-lock.yaml': '', + 'site/web/package.json': {}, + }) + const root = join(outer, 'site') + const change = await add(join(root, 'web'), 'druxt-breadcrumb', root) + expect(runs(change)[0]?.tool).toBe('npm') + }) +}) + +describe('adding a module to the Nuxt 2 config of the quickstart', () => { + test('appends it to modules and changes nothing else', async () => { + const dir = part({ 'nuxt.config.js': QUICKSTART }) + const [edit] = edits(await add(dir)) + expect(edit?.file).toBe('nuxt.config.js') + expect(edit?.summary).toBe( + "Add 'druxt-breadcrumb' to modules in nuxt.config.js" + ) + expect(edit?.content).toBe( + QUICKSTART.replace( + ' localhostListenURL\n ],', + " localhostListenURL,\n 'druxt-breadcrumb'\n ]," + ) + ) + expect(edit?.content).not.toBe(QUICKSTART) + }) + + test('installs before it edits', async () => { + const dir = part({ 'nuxt.config.js': QUICKSTART }) + const change = await add(dir) + expect(change.steps.map((step) => Object.keys(step)[0])).toEqual([ + 'run', + 'edit', + ]) + expect(change.manual).toEqual([]) + }) + + test('leaves a module that is already listed, alone or with options', async () => { + const dir = part({ 'nuxt.config.js': QUICKSTART }) + for (const name of ['druxt-site', 'druxt-auth']) { + const change = await add(dir, name) + expect(edits(change)).toEqual([]) + expect(change.notes).toContain( + `${name} is already in modules in nuxt.config.js.` + ) + } + }) + + test('takes a module out again, and gives the file back as it was', async () => { + const dir = part({ 'nuxt.config.js': QUICKSTART }) + const [added] = edits(await add(dir)) + writeTree(dir, { + 'nuxt.config.js': added?.content, + 'package.json': { dependencies: { 'druxt-breadcrumb': '^0.1.0' } }, + }) + const change = await remove(dir) + expect(edits(change)[0]?.content).toBe(QUICKSTART) + expect(edits(change)[0]?.summary).toBe( + "Remove 'druxt-breadcrumb' from modules in nuxt.config.js" + ) + }) + + test('takes out a module listed with its options', async () => { + const dir = part({ + 'nuxt.config.js': QUICKSTART, + 'package.json': { dependencies: { 'druxt-auth': '^0.4.0' } }, + }) + const content = edits(await remove(dir, 'druxt-auth'))[0]?.content + // Its line goes, and every other line stays as it was written. + expect(content).toBe( + QUICKSTART.replace( + " ['druxt-auth', { clientId: process.env.OAUTH_CLIENT_ID }],\n", + '' + ) + ) + }) + + test.each([ + ["modules: ['a', 'druxt-breadcrumb', 'b']", "modules: ['a', 'b']"], + ["modules: ['druxt-breadcrumb', 'b']", "modules: ['b']"], + ["modules: ['a', 'druxt-breadcrumb']", "modules: ['a']"], + ["modules: ['druxt-breadcrumb']", 'modules: []'], + [ + "modules: [\n 'a', // first\n ['druxt-breadcrumb', { x: 1 }],\n 'b',\n ]", + "modules: [\n 'a', // first\n 'b',\n ]", + ], + ])('takes %j out and leaves the rest as written', async (before, after) => { + const wrap = (list: string) => `export default {\n ${list},\n}\n` + const dir = part({ + 'nuxt.config.js': wrap(before), + 'package.json': { dependencies: { 'druxt-breadcrumb': '^0.1.0' } }, + }) + expect(edits(await remove(dir))[0]?.content).toBe(wrap(after)) + }) +}) + +describe('adding a module to a Nuxt 4 config', () => { + test('appends it inside defineNuxtConfig', async () => { + const dir = part({ 'nuxt.config.ts': NUXT_4 }) + const [edit] = edits(await add(dir, '@druxt/site')) + expect(edit?.file).toBe('nuxt.config.ts') + expect(edit?.content).toBe( + NUXT_4.replace("['@nuxt/eslint']", "['@nuxt/eslint', '@druxt/site']") + ) + }) + + test('adds the modules key when the config has none', async () => { + const dir = part({ + 'nuxt.config.ts': 'export default defineNuxtConfig({\n ssr: true,\n})\n', + }) + const content = edits(await add(dir, '@druxt/site'))[0]?.content + // A key the file did not have is written in the printer's own style. + expect(content).toMatch(/modules: \[["']@druxt\/site["']\]/) + expect(content).toContain('ssr: true') + }) +}) + +describe('a config that cannot be edited safely', () => { + test.each([ + ['a function', 'export default () => ({ modules: [] })\n'], + [ + 'modules held in a variable', + "const list = ['a']\nexport default { modules: list }\n", + ], + ['modules built by a call', 'export default { modules: build() }\n'], + ['a file that does not parse', 'export default {{{\n'], + ])( + 'is left alone when it is %s, with the line to add', + async (_name, config) => { + const dir = part({ 'nuxt.config.js': config }) + const change = await add(dir) + expect(edits(change)).toEqual([]) + expect(runs(change)).toHaveLength(1) + expect(change.manual).toEqual([ + "Add 'druxt-breadcrumb' to the modules array in nuxt.config.js. It could not be edited safely.", + ]) + } + ) + + test('is said to be missing when there is no config file', async () => { + const change = await add(part({})) + expect(change.manual).toEqual([ + "Add 'druxt-breadcrumb' to the modules array of the config. No config file was found.", + ]) + }) + + const FUNCTION = 'export default () => ({ modules: [] })\n' + const BY_HAND = { installed: true, listed: false, byHand: true } + + test('is recorded as left to the user, and not as listed', async () => { + const change = await add(part({ 'nuxt.config.js': FUNCTION })) + expect(change.did).toEqual(BY_HAND) + expect((await add(part({}))).did).toEqual(BY_HAND) + // A config that was edited has nothing left to the user. + const edited = await add(part({ 'nuxt.config.js': QUICKSTART })) + expect(edited.did).toEqual({ installed: true, listed: true }) + }) + + test('has its line left to the user on a remove too, and claims nothing', async () => { + const dir = part({ + 'package.json': { dependencies: { 'druxt-breadcrumb': '^0.1.0' } }, + 'nuxt.config.js': FUNCTION, + }) + const change = await remove(dir, 'druxt-breadcrumb', BY_HAND) + expect(runs(change)).toEqual([ + { tool: 'npm', args: ['uninstall', '--', 'druxt-breadcrumb'] }, + ]) + expect(edits(change)).toEqual([]) + expect(change.notes).toEqual([]) + expect(change.manual).toEqual([ + "Remove 'druxt-breadcrumb' from the modules array in nuxt.config.js, if you added it there. drx add could not edit the file and left that line to you, so it is yours to take out.", + ]) + }) + + test('has its line left to the user when there is no config file either', async () => { + const change = await remove(part({}), 'druxt-breadcrumb', BY_HAND) + expect(change.manual).toEqual([ + "Remove 'druxt-breadcrumb' from the modules array of the config, if you added it there. drx add found no config file and left that line to you, so it is yours to take out.", + ]) + }) + + test('has nothing left to do once the config can be read and does not list it', async () => { + const dir = part({ 'nuxt.config.js': QUICKSTART }) + const change = await remove(dir, 'druxt-breadcrumb', BY_HAND) + expect(change.manual).toEqual([]) + expect(change.notes).toEqual([]) + }) + + test('is not said to have been listed before when nothing can tell', async () => { + const dir = part({ 'nuxt.config.js': FUNCTION }) + const change = await remove(dir, 'druxt-breadcrumb', { + installed: false, + listed: false, + }) + expect(change.notes.join('\n')).not.toContain('before drx add') + }) +}) + +describe('a package the part already has', () => { + test('is not installed again', async () => { + const dir = part({ + 'package.json': { dependencies: { 'druxt-breadcrumb': '^0.1.0' } }, + 'nuxt.config.js': QUICKSTART, + }) + const change = await add(dir) + expect(runs(change)).toEqual([]) + expect(change.notes).toContain( + 'druxt-breadcrumb is already a dependency in package.json.' + ) + expect(edits(change)).toHaveLength(1) + }) + + test('is not uninstalled when the part does not have it', async () => { + const dir = part({ 'nuxt.config.js': QUICKSTART }) + const change = await remove(dir) + expect(change.steps).toEqual([]) + }) + + test('is recorded as found, and one that is added as done', async () => { + const had = part({ + 'package.json': { dependencies: { 'druxt-auth': '^0.5.1' } }, + 'nuxt.config.js': QUICKSTART, + }) + expect((await add(had, 'druxt-auth')).did).toEqual({ + installed: false, + listed: false, + }) + expect((await add(had)).did).toEqual({ installed: true, listed: true }) + }) + + test('stays on a remove when the record says the add found it', async () => { + const dir = part({ + 'package.json': { dependencies: { 'druxt-auth': '^0.5.1' } }, + 'nuxt.config.js': QUICKSTART, + }) + const change = await remove(dir, 'druxt-auth', { + installed: false, + listed: false, + }) + expect(change.steps).toEqual([]) + expect(change.notes).toEqual([ + 'druxt-auth was in package.json before drx add, so it stays.', + 'druxt-auth was in modules in nuxt.config.js before drx add, so it stays.', + ]) + }) + + test('stays, with the lines to take it out, when the record does not say', async () => { + const dir = part({ + 'package.json': { dependencies: { 'druxt-auth': '^0.5.1' } }, + 'nuxt.config.js': QUICKSTART, + }) + const change = await nuxt.removeModule(dir, { package: 'druxt-auth' }) + expect(change.steps).toEqual([]) + expect(change.manual).toEqual([ + "The record does not say whether drx add installed druxt-auth, so it was left. To take it out: npm uninstall druxt-auth, and remove 'druxt-auth' from modules in nuxt.config.js.", + ]) + }) +}) diff --git a/packages/cli/test/commands/add.test.ts b/packages/cli/test/commands/add.test.ts new file mode 100644 index 0000000..8245ee9 --- /dev/null +++ b/packages/cli/test/commands/add.test.ts @@ -0,0 +1,2516 @@ +import { createHash } from 'node:crypto' +import { existsSync, readdirSync, readFileSync, writeFileSync } from 'node:fs' +import { join, relative } from 'node:path' +import { fileURLToPath } from 'node:url' +import { afterEach, beforeEach, describe, expect, test } from 'vitest' +import type { CliContext } from '../../src/context.js' +import type { ToolResult } from '../../src/exec.js' +import { answering } from '../helpers/prompter.js' +import { run } from '../helpers/run.js' +import { closedPort, serve, type TestServer } from '../helpers/server.js' +import { cleanTmp, tmp, writeTree } from '../helpers/tmp.js' + +const NUXT_CONFIG = readFileSync( + fileURLToPath( + new URL('../fixtures/quickstart-nuxt.config.js', import.meta.url) + ), + 'utf8' +) +const PATCH = { + description: 'Fix the redirect loop', + url: 'https://example.com/mr/12.diff', + issue: 'https://example.com/issue/12', +} + +/** On the record of a site that got the patches plugin from drx add. */ +const ADDED_PLUGIN = { required: true, allowed: true } + +const entry = (name: string, extra: Record) => ({ + name, + repo: `druxt/${name}`, + category: 'site-and-layout', + status: 'stable', + type: 'official', + archived: false, + description: `The ${name} module`, + npm: `druxt-${name}`, + compatibility: { druxt: '^0.25.0' }, + drupal: [], + ...extra, +}) + +/** A registry with the fields the published one does not have yet. */ +const REGISTRY = { + schemaVersion: 1, + modules: [ + entry('auth', { + compatibility: { druxt: 'unknown' }, + drupal: [ + { + name: 'simple_oauth', + label: 'Simple OAuth', + setup: [ + { + title: 'Generate the keys', + command: 'drush simple-oauth:generate-keys ../keys', + }, + ], + }, + ], + }), + entry('blocks', { + drupal: [{ name: 'block', label: 'Block', core: true }], + }), + entry('breadcrumb', { + drupal: [ + { + name: 'decoupled_router', + label: 'Decoupled Router', + patches: [PATCH], + }, + ], + }), + entry('ckeditor', { npm: undefined, status: 'unreleased' }), + entry('legacy', { archived: true }), + entry('node-preview', { compatibility: { druxt: '>=0.26.0 <1' } }), + entry('router', { + drupal: [{ name: 'decoupled_router', label: 'Decoupled Router' }], + }), + ], +} + +let server: TestServer +let url: string + +beforeEach(async () => { + server = await serve({ '/modules.json': JSON.stringify(REGISTRY) }) + url = `${server.url}/modules.json` +}) + +afterEach(async () => { + await server.close() + cleanTmp() +}) + +/** A project like one `drx init` makes from the quickstart. */ +function project( + backend: Record = { engine: 'ddev' }, + files: Record = {} +): string { + const root = tmp('drx-project-') + writeTree(root, { + 'drx.config.json': { + layout: 'monorepo', + line: '0.x', + starter: 'quickstart', + source: 'npm', + parts: [ + { role: 'frontend', kind: 'nuxt', path: 'nuxt' }, + { role: 'backend', kind: 'drupal', path: 'drupal', ...backend }, + ], + }, + 'nuxt/package.json': { + dependencies: { nuxt: '2.15.8', 'druxt-site': '^0.15.1' }, + }, + 'nuxt/package-lock.json': '{}', + 'nuxt/nuxt.config.js': NUXT_CONFIG, + 'nuxt/node_modules/druxt/package.json': { version: '0.25.2' }, + 'drupal/composer.json': + JSON.stringify( + { require: { 'drupal/core-recommended': '~11' } }, + null, + 4 + ) + '\n', + ...files, + }) + return root +} + +/** Every file under a directory with a hash of its content. */ +function snapshot(root: string): Record { + return Object.fromEntries( + readdirSync(root, { recursive: true, withFileTypes: true }) + .filter((file) => file.isFile()) + .map((file) => join(file.parentPath, file.name)) + .sort() + .map((file) => [ + relative(root, file), + createHash('sha256').update(readFileSync(file)).digest('hex'), + ]) + ) +} + +const MANAGERS = ['npm', 'pnpm', 'yarn', 'bun'] + +/** What the stand-in backend has enabled, and what depends on what. */ +interface Backend { + enabled?: string[] + /** For a module, the enabled modules that depend on it. */ + dependents?: Record + /** True when the backend cannot be asked anything. */ + unreadable?: boolean + /** For a module, what the backend enables along with it. */ + brings?: Record + /** + * Enabled modules its container does not know of, until its caches are + * rebuilt: a simulated uninstall says each is not installed. + */ + stale?: string[] +} + +/** + * A stand-in for the tools: it records each command line, and an install of + * a frontend package writes the dependency as the package manager would. A + * question to the backend is answered from `backend` and kept in `asked`, + * apart from the commands that change something. + */ +function tools( + root: string, + fail?: { on: string; output: string }, + backend: Backend = {} +) { + const calls: string[] = [] + const asked: string[] = [] + const enabled = new Set(backend.enabled ?? []) + const stale = new Set(backend.stale ?? []) + const exec: CliContext['exec'] = async (command, args, { cwd }) => { + const line = `${relative(root, cwd)}$ ${command} ${args.join(' ')}` + if (args.includes('pm:list')) { + asked.push(line) + if (backend.unreadable) return { code: 1, output: 'No database.' } + const list = Object.fromEntries( + [...enabled].map((name) => [ + name, + { name, path: `modules/contrib/${name}` }, + ]) + ) + return { code: 0, output: JSON.stringify(list) } + } + if (args.includes('--simulate')) { + asked.push(line) + const name = args.findLast((arg) => !arg.startsWith('-')) as string + if (backend.unreadable) return { code: 1, output: 'No database.' } + if (!enabled.has(name) || stale.has(name)) { + return { + code: 1, + output: `The following module(s) are not installed: ${name}. No modules to uninstall.`, + } + } + const all = [name, ...(backend.dependents?.[name] ?? [])] + return { + code: 0, + output: `The following extensions will be uninstalled: ${all.join(', ')}\n`, + } + } + calls.push(line) + if (fail && line.includes(fail.on)) return { code: 1, output: fail.output } + if (args.at(-1) === 'cr') stale.clear() + if (MANAGERS.includes(command)) { + const file = join(cwd, 'package.json') + const manifest = JSON.parse(readFileSync(file, 'utf8')) + const name = args.at(-1) as string + if (['install', 'add'].includes(args[0] as string)) { + manifest.dependencies[name] = '^1.0.0' + } else delete manifest.dependencies[name] + writeFileSync(file, JSON.stringify(manifest, null, 2)) + } + // Composer reads composer.json as it is, changes `require` and writes + // the whole file again in its own layout. + const composer = args.slice(args.indexOf('composer') + 1) + if ( + (command === 'composer' || args.includes('composer')) && + ['require', 'remove'].includes(composer[0] as string) + ) { + const file = join(cwd, 'composer.json') + const manifest = JSON.parse(readFileSync(file, 'utf8')) + const require: Record = manifest.require ?? {} + for (const named of composer.slice(1)) { + if (named.startsWith('-')) continue + const [name, constraint] = named.split(/:(.*)/) as [string, string?] + if (composer[0] === 'require') require[name] = constraint ?? '^1.0' + else delete require[name] + } + manifest.require = Object.fromEntries( + Object.entries(require).sort(([a], [b]) => a.localeCompare(b)) + ) + writeFileSync(file, JSON.stringify(manifest, null, 4) + '\n') + } + // The patches plugin locks what the manifest lists, in a file of its own. + if (composer[0] === 'patches-relock') { + const manifest = JSON.parse( + readFileSync(join(cwd, 'composer.json'), 'utf8') + ) + const listed: Record> = manifest.extra + ?.patches ?? {} + const patches = Object.fromEntries( + Object.entries(listed).map(([name, each]) => [ + name, + Object.entries(each).map(([description, url]) => ({ + package: name, + description, + url, + })), + ]) + ) + writeFileSync( + join(cwd, 'patches.lock.json'), + JSON.stringify( + { patches: Object.keys(patches).length > 0 ? patches : [] }, + null, + 4 + ) + '\n' + ) + } + const names = args + .slice(args.indexOf('-y') + 1) + .filter((name) => name !== '--') + if (args.includes('en')) { + for (const name of names) { + enabled.add(name) + for (const other of backend.brings?.[name] ?? []) enabled.add(other) + } + } + if (args.includes('pmu')) for (const name of names) enabled.delete(name) + return { code: 0, output: '' } satisfies ToolResult + } + return { calls, asked, exec, enabled } +} + +/** Answers what the backend is asked, and fails on anything that changes it. */ +const asking = (root: string, backend: Backend = {}): CliContext['exec'] => { + const { exec } = tools(root, undefined, backend) + return async (command, args, options) => { + if (args.includes('pm:list') || args.includes('--simulate')) { + return exec(command, args, options) + } + throw new Error(`A command was run: ${command} ${args.join(' ')}`) + } +} + +const drx = ( + argv: string[], + cwd: string, + overrides: Partial = {} +) => + run(argv, { + cwd, + defaultModuleRegistry: url, + // Asking the backend what it has enabled changes nothing. + exec: asking(cwd), + ...overrides, + }) + +const config = (root: string) => + JSON.parse(readFileSync(join(root, 'drx.config.json'), 'utf8')) + +const DRY_RUN = [ + 'Add breadcrumb (druxt-breadcrumb)', + ' nuxt/', + ' run npm install -- druxt-breadcrumb', + " edit Add 'druxt-breadcrumb' to modules in nuxt.config.js", + ' drupal/', + ' edit Add 1 patch to composer.json', + ' run ddev composer require -- cweagans/composer-patches:^2.0@beta', + ' run ddev composer patches-relock', + ' run ddev composer require -- drupal/decoupled_router', + ' run ddev drush cr', + ' run ddev drush en -y -- decoupled_router', + '', + 'Nothing was changed: this was a dry run.', + '', +].join('\n') + +describe('drx add --dry-run', () => { + test('prints every step and each command line', async () => { + const root = project() + const result = await drx(['add', 'breadcrumb', '--dry-run'], root) + expect(result.code).toBe(0) + expect(result.stdout).toBe(DRY_RUN) + expect(result.stderr).toContain( + 'Patch for drupal/decoupled_router: Fix the redirect loop (https://example.com/issue/12)' + ) + }) + + test('changes nothing and runs nothing', async () => { + const root = project() + const before = snapshot(root) + // `never` throws on any command, and the snapshot would show any write. + const result = await drx(['add', 'breadcrumb', 'auth', '--dry-run'], root) + expect(result.code).toBe(0) + expect(result.stderr).not.toContain('A command was run') + expect(snapshot(root)).toEqual(before) + }) + + test('is the same through drx module add, and by package name', async () => { + const root = project() + for (const argv of [ + ['module', 'add', 'breadcrumb', '--dry-run'], + ['add', 'druxt-breadcrumb', '--dry-run'], + ]) { + expect((await drx(argv, root)).stdout).toBe(DRY_RUN) + } + }) + + test('--json lists the steps as data', async () => { + const root = project() + const result = await drx(['add', 'blocks', '--dry-run', '--json'], root) + expect(JSON.parse(result.stdout)).toMatchObject({ + ok: true, + dryRun: true, + modules: [ + { + name: 'blocks', + package: 'druxt-blocks', + steps: [ + { part: 'nuxt', run: 'npm install -- druxt-blocks' }, + { + part: 'nuxt', + edit: "Add 'druxt-blocks' to modules in nuxt.config.js", + }, + { part: 'drupal', run: 'ddev drush en -y -- block' }, + ], + }, + ], + }) + }) +}) + +describe('drx add', () => { + test('installs the package, lists it in the config, and sets up the backend', async () => { + const root = project() + const { calls, exec } = tools(root) + const result = await drx(['add', 'breadcrumb'], root, { exec }) + + expect(result.code).toBe(0) + expect(calls).toEqual([ + 'nuxt$ npm install -- druxt-breadcrumb', + 'drupal$ ddev composer require -- cweagans/composer-patches:^2.0@beta', + 'drupal$ ddev composer patches-relock', + 'drupal$ ddev composer require -- drupal/decoupled_router', + 'drupal$ ddev drush cr', + 'drupal$ ddev drush en -y -- decoupled_router', + ]) + expect(readFileSync(join(root, 'nuxt/nuxt.config.js'), 'utf8')).toContain( + " localhostListenURL,\n 'druxt-breadcrumb'\n ]," + ) + const composer = JSON.parse( + readFileSync(join(root, 'drupal/composer.json'), 'utf8') + ) + expect(composer.extra.patches).toEqual({ + 'drupal/decoupled_router': { [PATCH.description]: PATCH.url }, + }) + expect(result.stdout).toBe('Added breadcrumb.\n') + }) + + test('records what it did in drx.config.json', async () => { + const root = project() + await drx(['add', 'breadcrumb'], root, { exec: tools(root).exec }) + expect(config(root).modules).toEqual([ + { + name: 'breadcrumb', + package: 'druxt-breadcrumb', + frontend: [{ path: 'nuxt', installed: true, listed: true }], + backend: [ + { + path: 'drupal', + modules: [ + { + name: 'decoupled_router', + package: 'drupal/decoupled_router', + enabled: true, + required: true, + }, + ], + patches: [ + { + package: 'drupal/decoupled_router', + description: PATCH.description, + url: PATCH.url, + module: 'decoupled_router', + }, + ], + patcher: ADDED_PLUGIN, + }, + ], + }, + ]) + }) + + test('runs the backend tools as the engine of the part does', async () => { + const root = project({ engine: 'php' }) + const { calls, exec } = tools(root) + await drx(['add', 'blocks'], root, { exec }) + expect(calls).toEqual([ + 'nuxt$ npm install -- druxt-blocks', + 'drupal$ vendor/bin/drush en -y -- block', + ]) + }) + + test('adds several modules, one after the other', async () => { + const root = project() + const { calls, exec } = tools(root) + const result = await drx(['add', 'blocks', 'router'], root, { exec }) + expect(result.stdout).toBe('Added blocks.\nAdded router.\n') + expect(calls.filter((line) => line.startsWith('nuxt$'))).toEqual([ + 'nuxt$ npm install -- druxt-blocks', + 'nuxt$ npm install -- druxt-router', + ]) + expect(config(root).modules.map((m: { name: string }) => m.name)).toEqual([ + 'blocks', + 'router', + ]) + }) + + test('prints what is left to do, and does not run it', async () => { + const root = project() + const { calls, exec } = tools(root) + const result = await drx(['add', 'auth'], root, { exec }) + expect(result.stdout).toBe( + [ + 'Added auth.', + '', + 'Left to do:', + ' Simple OAuth: Generate the keys', + ' drush simple-oauth:generate-keys ../keys', + '', + ].join('\n') + ) + expect(calls.join('\n')).not.toContain('generate-keys') + // The config lists druxt-auth already, with its options. + expect(result.stderr).toContain( + 'druxt-auth is already in modules in nuxt.config.js.' + ) + }) + + test('--no-patches leaves the patches out and warns', async () => { + const root = project() + const { calls, exec } = tools(root) + const result = await drx(['add', 'breadcrumb', '--no-patches'], root, { + exec, + }) + expect(result.code).toBe(0) + expect(calls).not.toContain('drupal$ ddev composer patches-relock') + expect(result.stderr).toContain( + 'Warning: The patch "Fix the redirect loop" for drupal/decoupled_router was not applied. Decoupled Router may not work without it.' + ) + expect( + readFileSync(join(root, 'drupal/composer.json'), 'utf8') + ).not.toContain('patches') + }) + + test('prints the line to add when the config cannot be edited safely', async () => { + const root = project( + { engine: 'ddev' }, + { + 'nuxt/nuxt.config.js': 'export default () => ({ modules: [] })\n', + } + ) + const result = await drx(['add', 'blocks'], root, { + exec: tools(root).exec, + }) + expect(result.code).toBe(0) + expect(result.stdout).toContain( + [ + 'Left to do:', + " Add 'druxt-blocks' to the modules array in nuxt.config.js. It could not be edited safely.", + ].join('\n') + ) + // The record says the line was left to the user, and not that it is there. + expect(config(root).modules[0].frontend).toEqual([ + { path: 'nuxt', installed: true, listed: false, byHand: true }, + ]) + }) + + test('drx remove leaves that line to the user too, and claims nothing', async () => { + const root = project( + { engine: 'ddev' }, + { + 'nuxt/nuxt.config.js': 'export default () => ({ modules: [] })\n', + } + ) + const { calls, exec } = tools(root) + await drx(['add', 'blocks'], root, { exec }) + calls.length = 0 + const result = await drx(['remove', 'blocks'], root, { exec }) + expect(result.code, result.stderr).toBe(0) + expect(calls).toEqual(['nuxt$ npm uninstall -- druxt-blocks']) + expect(result.stderr).not.toContain('before drx add') + expect(result.stdout).toBe( + [ + 'Removed blocks.', + '', + 'Left to do:', + " Remove 'druxt-blocks' from the modules array in nuxt.config.js, if you added it there. drx add could not edit the file and left that line to you, so it is yours to take out.", + ' The backend was left as it is. drx remove blocks --backend takes out what drx add put in drupal/: block.', + '', + ].join('\n') + ) + }) + + test('a second add keeps the line left to the user on the record', async () => { + const root = project( + { engine: 'ddev' }, + { + 'nuxt/nuxt.config.js': 'export default () => ({ modules: [] })\n', + } + ) + const { exec } = tools(root) + await drx(['add', 'blocks'], root, { exec }) + await drx(['add', 'blocks'], root, { exec }) + expect(config(root).modules[0].frontend).toEqual([ + { path: 'nuxt', installed: true, listed: false, byHand: true }, + ]) + }) +}) + +describe('drx add when the backend is not run from here', () => { + test('with the none engine does the frontend and prints the rest', async () => { + const root = project({ engine: 'none', baseUrl: 'https://example.com' }) + const { calls, exec } = tools(root) + const result = await drx(['add', 'breadcrumb'], root, { exec }) + expect(result.code).toBe(0) + expect(calls).toEqual(['nuxt$ npm install -- druxt-breadcrumb']) + expect(result.stdout).toBe( + [ + 'Added breadcrumb.', + '', + 'Left to do:', + ' The backend of this project is not on this machine. Where it is:', + ' Patch drupal/decoupled_router with https://example.com/mr/12.diff (Fix the redirect loop)', + ' composer require -- cweagans/composer-patches:^2.0@beta', + ' composer patches-relock', + ' composer require -- drupal/decoupled_router', + ' drush cr', + ' drush en -y -- decoupled_router', + '', + ].join('\n') + ) + expect(config(root).modules[0].backend).toEqual([]) + expect( + readFileSync(join(root, 'drupal/composer.json'), 'utf8') + ).not.toContain('patches') + }) + + test('says so when the project does not record an engine', async () => { + const root = project({}) + const { calls, exec } = tools(root) + const result = await drx(['add', 'blocks'], root, { exec }) + expect(calls).toEqual(['nuxt$ npm install -- druxt-blocks']) + expect(result.stdout).toContain( + ' This project does not record how drupal/ is run. In it:\n drush en -y -- block' + ) + }) +}) + +describe('what drx add refuses', () => { + test.each([ + ['legacy', 'legacy is archived.', true], + [ + 'node-preview', + 'node-preview works with druxt >=0.26.0 <1, and nuxt/ has druxt 0.25.2.', + true, + ], + [ + 'ckeditor', + 'ckeditor has no package to install: it is not released.', + false, + ], + ])( + '%s, and --force goes ahead only where it can', + async (name, reason, forceable) => { + const root = project() + const before = snapshot(root) + const refused = await drx(['add', name], root) + expect(refused.code).toBe(1) + expect(refused.stderr).toContain(`Cannot add ${name}: ${reason}`) + expect( + refused.stderr.includes('Pass --force to add it all the same.') + ).toBe(forceable) + expect(snapshot(root)).toEqual(before) + + const forced = await drx(['add', name, '--force'], root, { + exec: tools(root).exec, + }) + expect(forced.code).toBe(forceable ? 0 : 1) + if (forceable) expect(forced.stderr).toContain(`Warning: ${reason}`) + } + ) + + test('warns, and goes ahead, when the compatibility is unknown', async () => { + const root = project() + const result = await drx(['add', 'auth'], root, { exec: tools(root).exec }) + expect(result.code).toBe(0) + expect(result.stderr).toContain( + 'Warning: auth does not say which druxt it works with, so it may not work with the one in nuxt/.' + ) + }) + + test('adds nothing when one of several is refused', async () => { + const root = project() + const before = snapshot(root) + const result = await drx(['add', 'blocks', 'legacy'], root) + expect(result.code).toBe(1) + expect(snapshot(root)).toEqual(before) + }) + + test('a name the registry does not have, with the closest', async () => { + const result = await drx(['add', 'blok'], project()) + expect(result.code).toBe(1) + expect(result.stderr).toContain( + 'There is no module named "blok". Closest: blocks.' + ) + }) + + test('running outside a project', async () => { + const cwd = tmp() + const result = await drx(['add', 'blocks'], cwd) + expect(result.code).toBe(1) + expect(result.stderr).toContain( + `drx add works inside a project, and there is no drx.config.json in ${cwd} or above it.` + ) + }) + + test('no name, with nobody to ask', async () => { + const result = await drx(['add'], project()) + expect(result.code).toBe(1) + expect(result.stderr).toContain( + 'Give the name of a module, as in "drx add blocks".' + ) + }) +}) + +describe('drx add when a tool fails', () => { + test('stops, shows the output, and says what was and was not done', async () => { + const root = project() + const { calls, exec } = tools(root, { + on: 'composer require -- drupal/decoupled_router', + output: 'Your requirements could not be resolved.', + }) + const result = await drx(['add', 'breadcrumb'], root, { exec }) + + expect(result.code).toBe(1) + expect(calls.at(-1)).toBe( + 'drupal$ ddev composer require -- drupal/decoupled_router' + ) + expect(result.stderr).toContain( + [ + 'Error: ddev composer require -- drupal/decoupled_router failed in drupal/ with exit code 1.', + 'Your requirements could not be resolved.', + 'Done:', + ' nuxt/: npm install -- druxt-breadcrumb', + " nuxt/: Add 'druxt-breadcrumb' to modules in nuxt.config.js", + ' drupal/: Add 1 patch to composer.json', + ' drupal/: ddev composer require -- cweagans/composer-patches:^2.0@beta', + ' drupal/: ddev composer patches-relock', + 'Not done:', + ' drupal/: ddev composer require -- drupal/decoupled_router', + ' drupal/: ddev drush cr', + ' drupal/: ddev drush en -y -- decoupled_router', + ].join('\n') + ) + // What was done is on the record, for a second run or a remove. + expect(config(root).modules).toEqual([ + { + name: 'breadcrumb', + package: 'druxt-breadcrumb', + frontend: [{ path: 'nuxt', installed: true, listed: true }], + backend: [ + { + path: 'drupal', + modules: [], + patches: [ + { + package: 'drupal/decoupled_router', + description: PATCH.description, + url: PATCH.url, + module: 'decoupled_router', + }, + ], + patcher: ADDED_PLUGIN, + }, + ], + }, + ]) + }) +}) + +describe('telling core from contributed with the published registry', () => { + // The registry as it is published today: no module is marked as core. + const published = () => { + const modules = [ + entry('menu', { + drupal: [ + { name: 'jsonapi_menu_items', label: 'JSON:API Menu Items' }, + { name: 'menu_link_content', label: 'Custom Menu Links' }, + ], + }), + ] + server.files['/modules.json'] = JSON.stringify({ + schemaVersion: 1, + modules, + }) + } + + test('refuses before any step when core is not installed to look in', async () => { + published() + const root = project() + const before = snapshot(root) + const result = await drx(['add', 'menu'], root) + expect(result.code).toBe(1) + expect(result.stderr).toContain( + 'Cannot add menu: Cannot tell whether jsonapi_menu_items is part of core or a package to require' + ) + expect(snapshot(root)).toEqual(before) + }) + + test('looks in the installed core, enables what is there and requires the rest', async () => { + published() + const root = project( + { engine: 'ddev' }, + { + 'drupal/web/core/modules/menu_link_content/menu_link_content.info.yml': + '', + } + ) + const { calls, exec } = tools(root) + const result = await drx(['add', 'menu'], root, { exec }) + expect(result.code).toBe(0) + expect(calls.slice(1)).toEqual([ + 'drupal$ ddev composer require -- drupal/jsonapi_menu_items', + 'drupal$ ddev drush cr', + 'drupal$ ddev drush en -y -- jsonapi_menu_items menu_link_content', + ]) + }) +}) + +describe('drx add in a terminal with no name', () => { + const answers = { + 'Which modules?': ['breadcrumb', 'blocks'], + 'Make these changes?': true, + } + const picking = ( + root: string, + given: Record, + exec = tools(root).exec + ) => { + const { prompter, asked } = answering(given) + return run( + ['add'], + { + cwd: root, + env: { XDG_CONFIG_HOME: tmp(), NO_COLOR: '1' }, + defaultModuleRegistry: url, + exec, + prompter, + }, + { columns: 100 } + ).then((result) => ({ ...result, asked })) + } + + test('offers the modules that can be added, then a summary and a confirm', async () => { + const root = project() + const result = await picking(root, answers) + expect(result.code).toBe(0) + expect(result.asked.map(({ message }) => message)).toEqual([ + 'Which modules?', + 'Make these changes?', + ]) + expect(result.asked[0]?.choices?.map(({ value }) => value)).toEqual([ + 'auth', + 'blocks', + 'breadcrumb', + 'node-preview', + 'router', + ]) + expect(result.stderr).toContain('Add breadcrumb (druxt-breadcrumb)') + expect(result.stderr).toContain(' run ddev drush en -y -- block') + expect(result.stdout).toBe('Added breadcrumb.\nAdded blocks.\n') + }) + + test('ends with the command that repeats it', async () => { + const result = await picking(project(), answers) + expect(result.stderr.trimEnd().split('\n').at(-1)).toBe( + 'Repeat this with: drx add breadcrumb blocks --yes' + ) + }) + + test('changes nothing when the answer is no', async () => { + const root = project() + const before = snapshot(root) + const result = await picking( + root, + { ...answers, 'Make these changes?': false }, + asking(root) + ) + expect(result.code).toBe(1) + expect(result.stderr).toContain('Error: Cancelled. Nothing was changed.') + expect(snapshot(root)).toEqual(before) + }) +}) + +describe('drx remove', () => { + /** The backend once breadcrumb is added. */ + const ENABLED = { enabled: ['decoupled_router'] } + + /** A project with breadcrumb added by `drx add`. */ + async function added(names = ['breadcrumb']) { + const root = project() + const result = await drx(['add', ...names], root, { + exec: tools(root).exec, + }) + expect(result.code).toBe(0) + return root + } + + test('takes the module out of the config and uninstalls the package', async () => { + const root = await added() + const { calls, exec } = tools(root) + const result = await drx(['remove', 'breadcrumb'], root, { exec }) + expect(result.code).toBe(0) + expect(calls).toEqual(['nuxt$ npm uninstall -- druxt-breadcrumb']) + expect(readFileSync(join(root, 'nuxt/nuxt.config.js'), 'utf8')).toBe( + NUXT_CONFIG + ) + expect(result.stdout).toBe( + [ + 'Removed breadcrumb.', + '', + 'Left to do:', + ' The backend was left as it is. drx remove breadcrumb --backend takes out what drx add put in drupal/: decoupled_router, 1 patch.', + '', + ].join('\n') + ) + // The record stays, so the backend can still be undone. + expect(config(root).modules).toHaveLength(1) + }) + + test('--backend undoes what the record says drx add did, and drops the record', async () => { + const root = await added() + const { calls, exec } = tools(root, undefined, ENABLED) + const result = await drx(['remove', 'breadcrumb', '--backend'], root, { + exec, + }) + expect(result.code).toBe(0) + expect(calls).toEqual([ + 'nuxt$ npm uninstall -- druxt-breadcrumb', + 'drupal$ ddev drush pmu -y -- decoupled_router', + 'drupal$ ddev composer remove --no-update-with-dependencies -- drupal/decoupled_router', + 'drupal$ ddev composer patches-relock', + 'drupal$ ddev composer remove -- cweagans/composer-patches', + 'drupal$ ddev drush cr', + ]) + const composer = JSON.parse( + readFileSync(join(root, 'drupal/composer.json'), 'utf8') + ) + // The patches were all that was under `extra`, so it went with them. + expect(composer.extra).toBeUndefined() + // The plugin drx add brought went with the last patch. + expect(composer).toEqual({ require: { 'drupal/core-recommended': '~11' } }) + expect(existsSync(join(root, 'drupal/patches.lock.json'))).toBe(false) + expect(config(root).modules).toBeUndefined() + expect(result.stdout).toBe('Removed breadcrumb.\n') + }) + + test('--backend changes nothing of a module the backend gives two answers about', async () => { + const root = await added() + const record = config(root).modules + const composer = readFileSync(join(root, 'drupal/composer.json'), 'utf8') + // The list has the module enabled, and the container does not know it. + const backend = { ...ENABLED, stale: ['decoupled_router'] } + const { calls, exec, enabled } = tools(root, undefined, backend) + const result = await drx(['remove', 'breadcrumb', '--backend'], root, { + exec, + }) + expect(result.code, result.stderr).toBe(0) + expect(calls).toEqual(['nuxt$ npm uninstall -- druxt-breadcrumb']) + expect(result.stderr).not.toContain('is not enabled') + expect(result.stdout).toBe( + [ + 'Removed breadcrumb.', + '', + 'Left to do:', + ' The backend gave two answers about whether decoupled_router is enabled, so it was left as it is. Rebuild its caches with drush cr and run this again, or once nothing depends on it: drush pm:uninstall decoupled_router, then composer remove drupal/decoupled_router', + '', + ].join('\n') + ) + // The module is still enabled and required, and the record still says + // that drx add enabled it. + expect([...enabled]).toEqual(['decoupled_router']) + expect(readFileSync(join(root, 'drupal/composer.json'), 'utf8')).toBe( + composer + ) + expect(config(root).modules).toEqual([{ ...record[0], frontend: [] }]) + + // Once the caches are rebuilt, the same command finishes the job. + await exec('ddev', ['drush', 'cr'], { cwd: join(root, 'drupal') }) + calls.length = 0 + const again = await drx(['remove', 'breadcrumb', '--backend'], root, { + exec, + }) + expect(again.code, again.stderr).toBe(0) + expect(calls).toEqual([ + 'drupal$ ddev drush pmu -y -- decoupled_router', + 'drupal$ ddev composer remove --no-update-with-dependencies -- drupal/decoupled_router', + 'drupal$ ddev composer patches-relock', + 'drupal$ ddev composer remove -- cweagans/composer-patches', + 'drupal$ ddev drush cr', + ]) + expect(config(root).modules).toBeUndefined() + }) + + test('--backend keeps a backend module another installed module needs', async () => { + // router needs decoupled_router too, and is installed without drx add. + const root = await added() + const file = join(root, 'nuxt/package.json') + const manifest = JSON.parse(readFileSync(file, 'utf8')) + manifest.dependencies['druxt-router'] = '^0.25.0' + writeFileSync(file, JSON.stringify(manifest)) + + const { calls, exec } = tools(root, undefined, ENABLED) + const result = await drx(['remove', 'breadcrumb', '--backend'], root, { + exec, + }) + expect(calls).toEqual(['nuxt$ npm uninstall -- druxt-breadcrumb']) + expect(result.stderr).toContain('decoupled_router stays: router needs it.') + // router has no record to take it, so it stays on this one. + expect(config(root).modules[0].name).toBe('breadcrumb') + expect(config(root).modules[0].backend[0].modules).toHaveLength(1) + }) + + test('--dry-run prints the steps and changes nothing', async () => { + const root = await added() + const before = snapshot(root) + const result = await drx( + ['remove', 'breadcrumb', '--backend', '--dry-run'], + root, + { exec: asking(root, ENABLED) } + ) + expect(result.code).toBe(0) + expect(result.stdout).toBe( + [ + 'Remove breadcrumb (druxt-breadcrumb)', + ' nuxt/', + ' run npm uninstall -- druxt-breadcrumb', + " edit Remove 'druxt-breadcrumb' from modules in nuxt.config.js", + ' drupal/', + ' run ddev drush pmu -y -- decoupled_router', + ' edit Remove 1 patch from composer.json', + ' run ddev composer remove --no-update-with-dependencies -- drupal/decoupled_router', + ' run ddev composer patches-relock', + ' run ddev composer remove -- cweagans/composer-patches', + ' edit Remove cweagans/composer-patches from allow-plugins in composer.json', + ' edit Delete patches.lock.json', + ' run ddev drush cr', + '', + 'Nothing was changed: this was a dry run.', + '', + ].join('\n') + ) + expect(snapshot(root)).toEqual(before) + }) + + test('fails on a module the project does not have', async () => { + const result = await drx(['remove', 'blocks'], project()) + expect(result.code).toBe(1) + expect(result.stderr).toContain( + 'Cannot remove blocks: druxt-blocks is not in this project.' + ) + }) +}) + +/** The project with one more dependency in the frontend's package.json. */ +function depend(root: string, name: string) { + const file = join(root, 'nuxt/package.json') + const manifest = JSON.parse(readFileSync(file, 'utf8')) + manifest.dependencies[name] = '^0.25.0' + writeFileSync(file, JSON.stringify(manifest)) +} + +describe('what drx add records', () => { + test('says what it did to each part, and what it found in place', async () => { + const root = project() + // The site has the Decoupled Router module enabled, and not required. + const backend = { enabled: ['decoupled_router'] } + const { calls, exec } = tools(root, undefined, backend) + const result = await drx(['add', 'router'], root, { exec }) + expect(result.code).toBe(0) + expect(calls).toEqual([ + 'nuxt$ npm install -- druxt-router', + 'drupal$ ddev composer require -- drupal/decoupled_router', + 'drupal$ ddev drush cr', + ]) + expect(result.stderr).toContain('decoupled_router is already enabled.') + expect(config(root).modules).toEqual([ + { + name: 'router', + package: 'druxt-router', + frontend: [{ path: 'nuxt', installed: true, listed: true }], + backend: [ + { + path: 'drupal', + modules: [ + { + name: 'decoupled_router', + package: 'drupal/decoupled_router', + enabled: false, + required: true, + }, + ], + patches: [], + }, + ], + }, + ]) + }) + + test('records a module the backend enabled along with the one it was asked for', async () => { + const root = project() + const { calls, exec } = tools(root, undefined, { + brings: { decoupled_router: ['path_alias'] }, + dependents: { path_alias: ['decoupled_router'] }, + }) + await drx(['add', 'router'], root, { exec }) + expect(config(root).modules[0].backend[0].modules).toEqual([ + { + name: 'decoupled_router', + package: 'drupal/decoupled_router', + enabled: true, + required: true, + }, + { name: 'path_alias', enabled: true, required: false }, + ]) + + calls.length = 0 + await drx(['remove', 'router', '--backend'], root, { exec }) + expect(calls).toContain( + 'drupal$ ddev drush pmu -y -- decoupled_router path_alias' + ) + expect(config(root).modules).toBeUndefined() + }) + + test('a second add keeps what the first recorded', async () => { + const root = project() + const { exec } = tools(root) + await drx(['add', 'breadcrumb'], root, { exec }) + const first = config(root).modules + expect(first[0].backend[0].modules).toHaveLength(1) + + const again = await drx(['add', 'breadcrumb'], root, { exec }) + expect(again.code).toBe(0) + expect(config(root).modules).toEqual(first) + }) + + test('add, remove, add, then remove --backend undoes the backend', async () => { + const root = project() + const { calls, exec } = tools(root) + await drx(['add', 'router'], root, { exec }) + await drx(['remove', 'router'], root, { exec }) + await drx(['add', 'router'], root, { exec }) + calls.length = 0 + const result = await drx(['remove', 'router', '--backend'], root, { exec }) + expect(result.code).toBe(0) + expect(calls).toEqual([ + 'nuxt$ npm uninstall -- druxt-router', + 'drupal$ ddev drush pmu -y -- decoupled_router', + 'drupal$ ddev composer remove --no-update-with-dependencies -- drupal/decoupled_router', + 'drupal$ ddev drush cr', + ]) + expect(config(root).modules).toBeUndefined() + }) + + test('reads a record written before the parts were told apart', async () => { + const root = project() + const file = join(root, 'drx.config.json') + const old = JSON.parse(readFileSync(file, 'utf8')) + old.modules = [ + { + name: 'router', + package: 'druxt-router', + backend: [ + { + path: 'drupal', + modules: [ + { name: 'decoupled_router', package: 'drupal/decoupled_router' }, + ], + patches: [], + }, + ], + }, + ] + writeFileSync(file, JSON.stringify(old)) + depend(root, 'druxt-router') + const { calls, exec } = tools(root, undefined, { + enabled: ['decoupled_router'], + }) + const result = await drx(['remove', 'router', '--backend'], root, { exec }) + expect(result.code).toBe(0) + // The record does not say who installed the package, so it stays. + expect(calls).toEqual([ + 'drupal$ ddev drush pmu -y -- decoupled_router', + 'drupal$ ddev composer remove --no-update-with-dependencies -- drupal/decoupled_router', + 'drupal$ ddev drush cr', + ]) + expect(result.stdout).toContain( + 'The record does not say whether drx add installed druxt-router, so it was left. To take it out: npm uninstall druxt-router.' + ) + }) +}) + +describe('drx remove of what the site already had', () => { + test('keeps a package and a config entry that drx add found in place', async () => { + const root = project( + { engine: 'ddev' }, + { + 'drupal/composer.json': JSON.stringify({ + require: { + 'drupal/core-recommended': '~11', + 'drupal/simple_oauth': '^6', + }, + }), + } + ) + depend(root, 'druxt-auth') + const before = snapshot(root) + const { calls, exec } = tools(root, undefined, { + enabled: ['simple_oauth'], + }) + await drx(['add', 'auth'], root, { exec }) + expect(config(root).modules[0].frontend).toEqual([ + { path: 'nuxt', installed: false, listed: false }, + ]) + calls.length = 0 + + const result = await drx(['remove', 'auth', '--backend'], root, { exec }) + expect(result.code).toBe(0) + expect(calls).toEqual([]) + expect(result.stderr).toContain( + 'druxt-auth was in package.json before drx add, so it stays.' + ) + expect(result.stdout).toBe( + 'Nothing to remove for auth: drx add found it in place.\n' + ) + expect(config(root).modules).toBeUndefined() + const after = snapshot(root) + delete after['drx.config.json'] + delete before['drx.config.json'] + expect(after).toEqual(before) + }) + + test('refuses a module that is installed and has no record', async () => { + const root = project() + depend(root, 'druxt-blocks') + const before = snapshot(root) + const result = await drx(['remove', 'blocks'], root) + expect(result.code).toBe(1) + expect(result.stderr).toContain( + 'Cannot remove blocks: drx add did not put druxt-blocks in this project, so there is nothing of its own to undo. Uninstall the package and take it out of the config by hand.' + ) + expect(snapshot(root)).toEqual(before) + }) + + test('refuses a module that is only in node_modules', async () => { + const root = project( + { engine: 'ddev' }, + { 'nuxt/node_modules/druxt-blocks/package.json': { version: '0.18.1' } } + ) + const result = await drx(['remove', 'blocks'], root) + expect(result.code).toBe(1) + expect(result.stderr).toContain( + 'Cannot remove blocks: druxt-blocks is not in this project.' + ) + }) +}) + +describe('drx remove --backend and what the backend still needs', () => { + test('leaves a module another enabled module depends on, and says which', async () => { + const root = project() + const { calls, asked, exec, enabled } = tools(root, undefined, { + dependents: { decoupled_router: ['druxt'] }, + }) + await drx(['add', 'router'], root, { exec }) + calls.length = 0 + + const result = await drx(['remove', 'router', '--backend'], root, { exec }) + expect(result.code).toBe(0) + expect(asked).toContain( + 'drupal$ ddev drush pm:uninstall --simulate -- decoupled_router' + ) + expect(calls).toEqual(['nuxt$ npm uninstall -- druxt-router']) + expect(enabled.has('decoupled_router')).toBe(true) + expect(result.stderr).toContain( + 'decoupled_router stays enabled: druxt depends on it.' + ) + // What stays keeps its record. + expect(config(root).modules).toEqual([ + { + name: 'router', + package: 'druxt-router', + frontend: [], + backend: [ + { + path: 'drupal', + modules: [ + { + name: 'decoupled_router', + package: 'drupal/decoupled_router', + enabled: true, + required: true, + }, + ], + patches: [], + }, + ], + }, + ]) + }) + + test('uninstalls nothing when the backend cannot say what depends on it', async () => { + const root = project() + const { exec } = tools(root) + await drx(['add', 'router'], root, { exec }) + + const silent = tools(root, undefined, { unreadable: true }) + const result = await drx(['remove', 'router', '--backend'], root, { + exec: silent.exec, + }) + expect(result.code).toBe(0) + expect(silent.calls).toEqual(['nuxt$ npm uninstall -- druxt-router']) + expect(result.stdout).toBe( + [ + 'Removed router.', + '', + 'Left to do:', + ' The backend could not say what depends on decoupled_router, so it was left enabled. Once nothing does: drush pm:uninstall decoupled_router, then composer remove drupal/decoupled_router', + '', + ].join('\n') + ) + expect(config(root).modules[0].backend[0].modules).toHaveLength(1) + }) + + test('hands over what came up with a module that stays, and takes it all out last', async () => { + // Enabling decoupled_router brings path_alias up with it. + const root = project() + const { calls, exec } = tools(root, undefined, { + brings: { decoupled_router: ['path_alias'] }, + dependents: { path_alias: ['decoupled_router'] }, + }) + await drx(['add', 'breadcrumb', '--no-patches'], root, { exec }) + await drx(['add', 'router'], root, { exec }) + + await drx(['remove', 'breadcrumb', '--backend'], root, { exec }) + // Nothing is left on the record of the module that is gone. + expect(config(root).modules).toHaveLength(1) + expect( + config(root).modules[0].backend[0].modules.map( + (module: { name: string }) => module.name + ) + ).toEqual(['decoupled_router', 'path_alias']) + + calls.length = 0 + const last = await drx(['remove', 'router', '--backend'], root, { exec }) + expect(last.code).toBe(0) + expect(calls).toEqual([ + 'nuxt$ npm uninstall -- druxt-router', + 'drupal$ ddev drush pmu -y -- decoupled_router path_alias', + 'drupal$ ddev composer remove --no-update-with-dependencies -- drupal/decoupled_router', + 'drupal$ ddev drush cr', + ]) + expect(config(root).modules).toBeUndefined() + }) + + test('a module that was removed no longer holds what it needed', async () => { + const root = project() + const { calls, exec } = tools(root) + await drx(['add', 'breadcrumb', '--no-patches'], root, { exec }) + // router was removed, and something of it was left on its record. + const file = join(root, 'drx.config.json') + const saved = JSON.parse(readFileSync(file, 'utf8')) + saved.modules.push({ + name: 'router', + package: 'druxt-router', + frontend: [], + backend: [ + { + path: 'drupal', + modules: [{ name: 'path_alias', enabled: true, required: false }], + patches: [], + }, + ], + }) + writeFileSync(file, JSON.stringify(saved)) + + calls.length = 0 + const result = await drx(['remove', 'breadcrumb', '--backend'], root, { + exec, + }) + expect(result.stderr).not.toContain('router needs it') + expect(calls).toContain('drupal$ ddev drush pmu -y -- decoupled_router') + }) + + test('hands what stays to the module that still needs it', async () => { + // breadcrumb and router both need decoupled_router. + const root = project() + const { calls, exec } = tools(root) + await drx(['add', 'breadcrumb'], root, { exec }) + await drx(['add', 'router'], root, { exec }) + calls.length = 0 + + const first = await drx(['remove', 'breadcrumb', '--backend'], root, { + exec, + }) + expect(first.code).toBe(0) + expect(calls).toEqual(['nuxt$ npm uninstall -- druxt-breadcrumb']) + expect(first.stderr).toContain('decoupled_router stays: router needs it.') + expect(config(root).modules).toEqual([ + { + name: 'router', + package: 'druxt-router', + frontend: [{ path: 'nuxt', installed: true, listed: true }], + backend: [ + { + path: 'drupal', + modules: [ + { + name: 'decoupled_router', + package: 'drupal/decoupled_router', + enabled: true, + required: true, + }, + ], + patches: [ + { + package: 'drupal/decoupled_router', + description: PATCH.description, + url: PATCH.url, + module: 'decoupled_router', + }, + ], + patcher: ADDED_PLUGIN, + }, + ], + }, + ]) + + calls.length = 0 + const second = await drx(['remove', 'router', '--backend'], root, { exec }) + expect(second.code).toBe(0) + expect(calls).toEqual([ + 'nuxt$ npm uninstall -- druxt-router', + 'drupal$ ddev drush pmu -y -- decoupled_router', + 'drupal$ ddev composer remove --no-update-with-dependencies -- drupal/decoupled_router', + 'drupal$ ddev composer patches-relock', + // The plugin came with breadcrumb's patch, and goes with it here. + 'drupal$ ddev composer remove -- cweagans/composer-patches', + 'drupal$ ddev drush cr', + ]) + expect( + JSON.parse(readFileSync(join(root, 'drupal/composer.json'), 'utf8')) + ).toEqual({ require: { 'drupal/core-recommended': '~11' } }) + expect(config(root).modules).toBeUndefined() + }) +}) + +describe('drx add with no backend to look in', () => { + // The registry as it is published: no module is marked as core. + const published = () => { + server.files['/modules.json'] = JSON.stringify({ + schemaVersion: 1, + modules: [ + entry('menu', { + drupal: [ + { name: 'jsonapi_menu_items', label: 'JSON:API Menu Items' }, + { name: 'menu_link_content', label: 'Custom Menu Links' }, + ], + }), + ], + }) + } + + test('plans the frontend and leaves the backend lines to the user', async () => { + published() + const root = project({ engine: 'none', baseUrl: 'https://example.com' }) + const before = snapshot(root) + const result = await drx(['add', 'menu', '--dry-run'], root) + expect(result.code).toBe(0) + expect(result.stdout).toBe( + [ + 'Add menu (druxt-menu)', + ' nuxt/', + ' run npm install -- druxt-menu', + " edit Add 'druxt-menu' to modules in nuxt.config.js", + ' drupal/', + ' The backend of this project is not on this machine. Where it is:', + ' composer require -- drupal/jsonapi_menu_items drupal/menu_link_content', + ' drush cr', + ' drush en -y -- jsonapi_menu_items menu_link_content', + '', + 'Left to do:', + ' The module registry does not say whether jsonapi_menu_items or menu_link_content is part of core. Leave a module that is out of the composer require line: only the enable line applies to it.', + '', + 'Nothing was changed: this was a dry run.', + '', + ].join('\n') + ) + expect(snapshot(root)).toEqual(before) + }) +}) + +describe('drx add and a patch that is not served over https', () => { + test('refuses before anything is written, naming the entry', async () => { + server.files['/modules.json'] = JSON.stringify({ + schemaVersion: 1, + modules: [ + entry('blocks', { + drupal: [{ name: 'block', label: 'Block', core: true }], + }), + entry('breadcrumb', { + drupal: [ + { + name: 'decoupled_router', + label: 'Decoupled Router', + patches: [{ ...PATCH, url: 'http://example.com/mr/12.diff' }], + }, + ], + }), + ], + }) + const root = project() + const before = snapshot(root) + const result = await drx(['add', 'breadcrumb'], root) + expect(result.code).toBe(1) + expect(result.stderr).toContain( + 'Cannot add breadcrumb: The patch "Fix the redirect loop" that decoupled_router needs is at http://example.com/mr/12.diff, and Composer only fetches a patch over https.' + ) + expect(snapshot(root)).toEqual(before) + + const without = await drx(['add', 'breadcrumb', '--no-patches'], root, { + exec: tools(root).exec, + }) + expect(without.code).toBe(0) + }) +}) + +describe('drx add --dry-run and what is left to the user', () => { + test('prints the line of a config that cannot be edited', async () => { + const root = project( + { engine: 'ddev' }, + { 'nuxt/nuxt.config.js': 'export default () => ({ modules: [] })\n' } + ) + const result = await drx(['add', 'blocks', '--dry-run'], root) + expect(result.code).toBe(0) + expect(result.stdout).toContain( + [ + 'Left to do:', + " Add 'druxt-blocks' to the modules array in nuxt.config.js. It could not be edited safely.", + '', + 'Nothing was changed: this was a dry run.', + ].join('\n') + ) + }) +}) + +describe('the JSON of a step that failed', () => { + test('has the step, its exit code and what was and was not done', async () => { + const root = project() + const { exec } = tools(root, { + on: 'composer require -- drupal/decoupled_router', + output: 'Your requirements could not be resolved.', + }) + const result = await drx(['add', 'router', '--json'], root, { exec }) + expect(result.code).toBe(1) + expect(JSON.parse(result.stdout)).toEqual({ + ok: false, + error: { + code: 'step-failed', + message: expect.stringContaining( + 'ddev composer require -- drupal/decoupled_router failed in drupal/ with exit code 1.' + ), + failed: { + part: 'drupal', + step: 'ddev composer require -- drupal/decoupled_router', + exitCode: 1, + output: 'Your requirements could not be resolved.', + }, + done: [ + 'nuxt/: npm install -- druxt-router', + "nuxt/: Add 'druxt-router' to modules in nuxt.config.js", + ], + notDone: [ + 'drupal/: ddev composer require -- drupal/decoupled_router', + 'drupal/: ddev drush cr', + 'drupal/: ddev drush en -y -- decoupled_router', + ], + }, + }) + }) +}) + +const patchOf = (name: string) => ({ + description: `Fix ${name}`, + url: `https://example.com/${name}.diff`, +}) +const patched = (name: string) => ({ + name: `mod_${name}`, + label: `Mod ${name}`, + patches: [patchOf(name)], +}) + +/** Modules that each need a backend module of their own, with a patch. */ +const PAIR = { + schemaVersion: 1, + modules: [ + entry('alpha', { drupal: [patched('alpha')] }), + entry('beta', { drupal: [patched('beta')] }), + // Needs the backend module alpha needs, and nothing of its own. + entry('gamma', { drupal: [{ name: 'mod_alpha', label: 'Mod alpha' }] }), + // A registry that marks one module as core is taken to mark them all. + entry('delta', { drupal: [{ name: 'block', label: 'Block', core: true }] }), + ], +} + +/** Serves another registry next to the usual one, and names it. */ +const registryOf = (registry: unknown, path = '/other.json') => { + server.files[path] = JSON.stringify(registry) + return { defaultModuleRegistry: `${server.url}${path}` } +} + +const read = (root: string, file: string) => + readFileSync(join(root, file), 'utf8') +const json = (root: string, file: string) => JSON.parse(read(root, file)) + +/** A site that has the patches plugin, so a patch changes nothing else. */ +const PLUGIN = 'cweagans/composer-patches' +const withPlugin = () => + project( + { engine: 'ddev' }, + { + 'drupal/composer.json': + JSON.stringify( + { + require: { + [PLUGIN]: '^2.0@beta', + 'drupal/core-recommended': '~11', + }, + config: { 'allow-plugins': { [PLUGIN]: true } }, + }, + null, + 4 + ) + '\n', + // The plugin keeps a lock file from the day it is installed. + 'drupal/patches.lock.json': + JSON.stringify({ patches: [] }, null, 4) + '\n', + } + ) + +/** The files of a project but its own record, which a run always rewrites. */ +const files = (root: string) => + Object.fromEntries( + Object.entries(snapshot(root)).filter( + ([file]) => file !== 'drx.config.json' + ) + ) + +const backendRecord = (name: string) => ({ + path: 'drupal', + modules: [ + { + name: `mod_${name}`, + package: `drupal/mod_${name}`, + enabled: true, + required: true, + }, + ], + patches: [ + { package: `drupal/mod_${name}`, ...patchOf(name), module: `mod_${name}` }, + ], +}) + +describe('several modules in one run', () => { + test('drx add a b leaves the files with what both wrote', async () => { + const root = project() + const { exec, enabled } = tools(root) + const result = await drx(['add', 'alpha', 'beta'], root, { + exec, + ...registryOf(PAIR), + }) + expect(result.code, result.stderr).toBe(0) + + const config = read(root, 'nuxt/nuxt.config.js') + expect(config).toContain("'druxt-alpha'") + expect(config).toContain("'druxt-beta'") + expect(json(root, 'nuxt/package.json').dependencies).toMatchObject({ + 'druxt-alpha': '^1.0.0', + 'druxt-beta': '^1.0.0', + }) + const composer = json(root, 'drupal/composer.json') + expect(Object.keys(composer.require)).toEqual([ + PLUGIN, + 'drupal/core-recommended', + 'drupal/mod_alpha', + 'drupal/mod_beta', + ]) + expect(composer.extra.patches).toEqual({ + 'drupal/mod_alpha': { 'Fix alpha': 'https://example.com/alpha.diff' }, + 'drupal/mod_beta': { 'Fix beta': 'https://example.com/beta.diff' }, + }) + expect([...enabled]).toEqual(['mod_alpha', 'mod_beta']) + }) + + test('each record holds what its own module did, and no more', async () => { + const root = project() + await drx(['add', 'alpha', 'beta'], root, { + exec: tools(root).exec, + ...registryOf(PAIR), + }) + expect(json(root, 'drx.config.json').modules).toEqual([ + { + name: 'alpha', + package: 'druxt-alpha', + frontend: [{ path: 'nuxt', installed: true, listed: true }], + // The first to need a patch brought the plugin that applies them. + backend: [{ ...backendRecord('alpha'), patcher: ADDED_PLUGIN }], + }, + { + name: 'beta', + package: 'druxt-beta', + frontend: [{ path: 'nuxt', installed: true, listed: true }], + backend: [backendRecord('beta')], + }, + ]) + }) + + test('drx remove a b --backend takes both out and leaves the files as they were', async () => { + const root = withPlugin() + const before = files(root) + const { exec, enabled } = tools(root) + const overrides = { exec, ...registryOf(PAIR) } + await drx(['add', 'alpha', 'beta'], root, overrides) + expect(files(root)).not.toEqual(before) + + const result = await drx( + ['remove', 'alpha', 'beta', '--backend'], + root, + overrides + ) + expect(result.code, result.stderr).toBe(0) + expect(result.stdout).toBe('Removed alpha.\nRemoved beta.\n') + expect(read(root, 'nuxt/nuxt.config.js')).toBe(NUXT_CONFIG) + expect(json(root, 'nuxt/package.json').dependencies).toEqual({ + nuxt: '2.15.8', + 'druxt-site': '^0.15.1', + }) + const composer = json(root, 'drupal/composer.json') + expect(Object.keys(composer.require)).toEqual([ + PLUGIN, + 'drupal/core-recommended', + ]) + expect(composer.extra).toBeUndefined() + expect([...enabled]).toEqual([]) + expect(json(root, 'drx.config.json').modules).toBeUndefined() + expect(files(root)).toEqual(before) + }) + + test.each([[['alpha', 'beta']], [['beta', 'alpha']]])( + 'the plugin drx add brought goes with the last patch, removing %j in turn', + async (order) => { + const root = project() + const before = files(root) + const { calls, exec } = tools(root) + const overrides = { exec, ...registryOf(PAIR) } + await drx(['add', 'alpha', 'beta'], root, overrides) + expect(json(root, 'drupal/composer.json').require).toHaveProperty(PLUGIN) + + const [first, second] = order as [string, string] + calls.length = 0 + await drx(['remove', first, '--backend'], root, overrides) + // A patch is left, so the plugin is, on the record of that module. + expect(calls.join('\n')).not.toContain(`-- ${PLUGIN}`) + expect(json(root, 'drupal/composer.json').require).toHaveProperty(PLUGIN) + expect(json(root, 'drx.config.json').modules).toEqual([ + { + name: second, + package: `druxt-${second}`, + frontend: [{ path: 'nuxt', installed: true, listed: true }], + backend: [{ ...backendRecord(second), patcher: ADDED_PLUGIN }], + }, + ]) + + calls.length = 0 + const last = await drx(['remove', second, '--backend'], root, overrides) + expect(last.code, last.stderr).toBe(0) + expect(calls.slice(-2)).toEqual([ + `drupal$ ddev composer remove -- ${PLUGIN}`, + 'drupal$ ddev drush cr', + ]) + expect(json(root, 'drx.config.json').modules).toBeUndefined() + expect(files(root)).toEqual(before) + } + ) + + test('a plugin the site had stays when the last patch goes', async () => { + const root = withPlugin() + const { calls, exec } = tools(root) + const overrides = { exec, ...registryOf(PAIR) } + await drx(['add', 'alpha'], root, overrides) + expect(json(root, 'drx.config.json').modules[0].backend[0]).toEqual( + backendRecord('alpha') + ) + await drx(['remove', 'alpha', '--backend'], root, overrides) + expect(calls.join('\n')).not.toContain(`-- ${PLUGIN}`) + const composer = json(root, 'drupal/composer.json') + expect(composer.require).toHaveProperty(PLUGIN) + expect(composer.config['allow-plugins']).toEqual({ [PLUGIN]: true }) + expect(existsSync(join(root, 'drupal/patches.lock.json'))).toBe(true) + }) + + test('a backend module two of them need is done once, by the first', async () => { + const root = project() + const { calls, exec } = tools(root) + const overrides = { exec, ...registryOf(PAIR) } + const result = await drx(['add', 'alpha', 'gamma'], root, overrides) + expect(result.code, result.stderr).toBe(0) + expect(calls.filter((line) => line.includes('mod_alpha'))).toEqual([ + 'drupal$ ddev composer require -- drupal/mod_alpha', + 'drupal$ ddev drush en -y -- mod_alpha', + ]) + const [alpha, gamma] = json(root, 'drx.config.json').modules + expect(alpha.backend).toEqual([ + { ...backendRecord('alpha'), patcher: ADDED_PLUGIN }, + ]) + expect(gamma.backend).toEqual([]) + + calls.length = 0 + const removed = await drx( + ['remove', 'alpha', 'gamma', '--backend'], + root, + overrides + ) + expect(removed.code, removed.stderr).toBe(0) + expect(calls.filter((line) => line.includes('mod_alpha'))).toEqual([ + 'drupal$ ddev drush pmu -y -- mod_alpha', + 'drupal$ ddev composer remove --no-update-with-dependencies -- drupal/mod_alpha', + ]) + expect(json(root, 'drx.config.json').modules).toBeUndefined() + }) + + test('the JSON of a run lists the steps that were taken', async () => { + const root = project() + const result = await drx(['add', 'alpha', 'gamma', '--json'], root, { + exec: tools(root).exec, + ...registryOf(PAIR), + }) + const [, gamma] = JSON.parse(result.stdout).modules + expect(gamma.steps).toEqual([ + { part: 'nuxt', run: 'npm install -- druxt-gamma' }, + { part: 'nuxt', edit: "Add 'druxt-gamma' to modules in nuxt.config.js" }, + ]) + }) +}) + +describe('drx add when a tool fails part way', () => { + const FAILS = { on: 'drush en', output: 'Drush could not start.' } + const DONE = [ + { + name: 'breadcrumb', + package: 'druxt-breadcrumb', + frontend: [{ path: 'nuxt', installed: true, listed: true }], + backend: [ + { + path: 'drupal', + modules: [ + { + name: 'decoupled_router', + package: 'drupal/decoupled_router', + enabled: false, + required: true, + }, + ], + patches: [ + { + package: 'drupal/decoupled_router', + description: PATCH.description, + url: PATCH.url, + module: 'decoupled_router', + }, + ], + patcher: ADDED_PLUGIN, + }, + ], + }, + ] + + test('records the steps that were done, and not the one that failed', async () => { + const root = project() + const result = await drx(['add', 'breadcrumb'], root, { + exec: tools(root, FAILS).exec, + }) + expect(result.code).toBe(1) + expect(result.stderr).toContain('Drush could not start.') + expect(config(root).modules).toEqual(DONE) + }) + + test('records nothing when nothing was done', async () => { + const root = project() + const result = await drx(['add', 'breadcrumb'], root, { + exec: tools(root, { on: 'npm install', output: 'E404' }).exec, + }) + expect(result.code).toBe(1) + expect(config(root).modules).toBeUndefined() + }) + + test('keeps the record of a module added before the one that failed', async () => { + const root = project() + const result = await drx(['add', 'blocks', 'breadcrumb'], root, { + exec: tools(root, { ...FAILS, on: 'decoupled_router' }).exec, + }) + expect(result.code).toBe(1) + expect(config(root).modules.map((m: { name: string }) => m.name)).toEqual([ + 'blocks', + 'breadcrumb', + ]) + expect(result.stderr).toContain( + [ + 'Done:', + ' nuxt/: npm install -- druxt-blocks', + " nuxt/: Add 'druxt-blocks' to modules in nuxt.config.js", + ' drupal/: ddev drush en -y -- block', + ' nuxt/: npm install -- druxt-breadcrumb', + ].join('\n') + ) + // blocks is whole, and breadcrumb is what its steps did. + expect(config(root).modules[1].backend[0].patches).toHaveLength(1) + expect(config(root).modules[1].backend[0].modules).toEqual([]) + }) + + test('a second run finishes the job, with the record of a run that never failed', async () => { + const clean = project() + await drx(['add', 'breadcrumb'], clean, { exec: tools(clean).exec }) + + const root = project() + await drx(['add', 'breadcrumb'], root, { exec: tools(root, FAILS).exec }) + const { calls, exec } = tools(root) + const again = await drx(['add', 'breadcrumb'], root, { exec }) + expect(again.code, again.stderr).toBe(0) + // Only the step that failed was left to take. + expect(calls).toEqual(['drupal$ ddev drush en -y -- decoupled_router']) + expect(config(root).modules).toEqual(config(clean).modules) + expect(files(root)).toEqual(files(clean)) + }) + + test('a second run locks and applies a patch the first could not lock', async () => { + // The package is installed already: another package brought it in. + const there = { + 'drupal/vendor/composer/installed.json': { + packages: [{ name: 'drupal/decoupled_router', version: '2.0.7' }], + }, + } + const clean = project({ engine: 'ddev' }, there) + await drx(['add', 'breadcrumb'], clean, { exec: tools(clean).exec }) + + const root = project({ engine: 'ddev' }, there) + const failed = await drx(['add', 'breadcrumb'], root, { + exec: tools(root, { on: 'patches-relock', output: 'HTTP 404' }).exec, + }) + expect(failed.code).toBe(1) + expect(existsSync(join(root, 'drupal/patches.lock.json'))).toBe(false) + + const { calls, exec } = tools(root) + const again = await drx(['add', 'breadcrumb'], root, { exec }) + expect(again.code, again.stderr).toBe(0) + expect(again.stderr).toContain( + 'The patch "Fix the redirect loop" is in composer.json and not in patches.lock.json, so the patches are locked again.' + ) + expect(calls).toEqual([ + 'drupal$ ddev composer patches-relock', + 'drupal$ ddev composer require -- drupal/decoupled_router', + 'drupal$ ddev composer patches-repatch', + 'drupal$ ddev drush cr', + 'drupal$ ddev drush en -y -- decoupled_router', + ]) + expect(config(root).modules).toEqual(config(clean).modules) + expect(files(root)).toEqual(files(clean)) + + // And a remove ends where the project started. + const removed = await drx(['remove', 'breadcrumb', '--backend'], root, { + exec, + }) + expect(removed.code, removed.stderr).toBe(0) + expect(files(root)).toEqual(files(project({ engine: 'ddev' }, there))) + }) + + test('a remove after the failure undoes what was done', async () => { + const root = withPlugin() + const before = files(root) + await drx(['add', 'breadcrumb'], root, { exec: tools(root, FAILS).exec }) + expect(files(root)).not.toEqual(before) + + const { calls, exec } = tools(root) + const result = await drx(['remove', 'breadcrumb', '--backend'], root, { + exec, + }) + expect(result.code, result.stderr).toBe(0) + expect(calls).toEqual([ + 'nuxt$ npm uninstall -- druxt-breadcrumb', + 'drupal$ ddev composer remove --no-update-with-dependencies -- drupal/decoupled_router', + 'drupal$ ddev composer patches-relock', + 'drupal$ ddev drush cr', + ]) + expect(config(root).modules).toBeUndefined() + expect(files(root)).toEqual(before) + }) + + test('a failure, a second run and a remove end where the project started', async () => { + const root = withPlugin() + const before = files(root) + await drx(['add', 'breadcrumb'], root, { exec: tools(root, FAILS).exec }) + const { exec } = tools(root) + expect((await drx(['add', 'breadcrumb'], root, { exec })).code).toBe(0) + const result = await drx(['remove', 'breadcrumb', '--backend'], root, { + exec, + }) + expect(result.code, result.stderr).toBe(0) + expect(config(root).modules).toBeUndefined() + expect(files(root)).toEqual(before) + }) +}) + +describe('drx add and the plugins a site allows', () => { + const composerWith = (config: Record | undefined) => + project( + { engine: 'ddev' }, + { + 'drupal/composer.json': + JSON.stringify( + { + require: { 'drupal/core-recommended': '~11' }, + ...(config ? { config } : {}), + }, + null, + 4 + ) + '\n', + } + ) + const allowed = async (config: Record | undefined) => { + const root = composerWith(config) + const result = await drx(['add', 'breadcrumb'], root, { + exec: tools(root).exec, + }) + expect(result.code, result.stderr).toBe(0) + return json(root, 'drupal/composer.json').config?.['allow-plugins'] + } + + test('leaves allow-plugins alone when it is true, which allows every plugin', async () => { + expect(await allowed({ 'allow-plugins': true })).toBe(true) + }) + + test('adds one key to a list of allowed plugins', async () => { + expect( + await allowed({ + 'allow-plugins': { 'composer/installers': true, 'a/b': false }, + }) + ).toEqual({ 'composer/installers': true, 'a/b': false, [PLUGIN]: true }) + }) + + test('starts the list when the site has none', async () => { + expect(await allowed(undefined)).toEqual({ [PLUGIN]: true }) + expect(await allowed({ 'sort-packages': true })).toEqual({ + [PLUGIN]: true, + }) + }) + + test('refuses the patch when allow-plugins is false, and writes nothing', async () => { + const root = composerWith({ 'allow-plugins': false }) + const before = snapshot(root) + const result = await drx(['add', 'breadcrumb'], root) + expect(result.code).toBe(1) + expect(result.stderr).toContain( + 'Cannot add breadcrumb: composer.json sets allow-plugins to false, which turns every Composer plugin off, and the patch "Fix the redirect loop" needs cweagans/composer-patches. Allow the plugin there, or pass --no-patches to add the module without the patch.' + ) + expect(snapshot(root)).toEqual(before) + }) + + test('--no-patches adds the module whatever allow-plugins is', async () => { + const root = composerWith({ 'allow-plugins': false }) + const result = await drx(['add', 'breadcrumb', '--no-patches'], root, { + exec: tools(root).exec, + }) + expect(result.code, result.stderr).toBe(0) + expect(json(root, 'drupal/composer.json').config).toEqual({ + 'allow-plugins': false, + }) + }) +}) + +describe("drx add and a site's own patch of the same name", () => { + const OWN = 'https://example.com/the-sites-own.patch' + const owning = (patches: Record>) => + project( + { engine: 'ddev' }, + { + 'drupal/composer.json': + JSON.stringify( + { + require: { + [PLUGIN]: '^2.0@beta', + 'drupal/core-recommended': '~11', + 'drupal/decoupled_router': '^2.0', + }, + extra: { patches }, + }, + null, + 4 + ) + '\n', + } + ) + + test('is refused before anything is written, naming the package and the patch', async () => { + const root = owning({ + 'drupal/decoupled_router': { [PATCH.description]: OWN }, + }) + const before = snapshot(root) + const result = await drx(['add', 'breadcrumb', '--json'], root) + expect(result.code).toBe(1) + expect(JSON.parse(result.stdout).error.code).toBe('refused') + expect(result.stderr).toContain( + `Cannot add breadcrumb: composer.json already has a patch for drupal/decoupled_router named "Fix the redirect loop", from ${OWN}. It is the site's own, and drx add does not replace it. Rename it, or pass --no-patches to add the module without the patch from the registry.` + ) + expect(snapshot(root)).toEqual(before) + }) + + test('goes in beside a patch of another name', async () => { + const root = owning({ 'drupal/decoupled_router': { 'Our fix': OWN } }) + const result = await drx(['add', 'breadcrumb'], root, { + exec: tools(root, undefined, { enabled: ['decoupled_router'] }).exec, + }) + expect(result.code, result.stderr).toBe(0) + expect(json(root, 'drupal/composer.json').extra.patches).toEqual({ + 'drupal/decoupled_router': { + 'Our fix': OWN, + [PATCH.description]: PATCH.url, + }, + }) + }) + + test('drx remove --backend leaves a patch the record does not own', async () => { + const root = owning({ 'drupal/decoupled_router': { 'Our fix': OWN } }) + const { exec } = tools(root, undefined, { enabled: ['decoupled_router'] }) + await drx(['add', 'breadcrumb'], root, { exec }) + // The site's owner then points the registry's patch at a copy of it. + const composer = json(root, 'drupal/composer.json') + composer.extra.patches['drupal/decoupled_router'][PATCH.description] = OWN + writeFileSync( + join(root, 'drupal/composer.json'), + JSON.stringify(composer, null, 4) + '\n' + ) + const result = await drx(['remove', 'breadcrumb', '--backend'], root, { + exec, + }) + expect(result.code, result.stderr).toBe(0) + expect(json(root, 'drupal/composer.json').extra.patches).toEqual({ + 'drupal/decoupled_router': { + 'Our fix': OWN, + [PATCH.description]: OWN, + }, + }) + }) +}) + +describe('drx add and the version of the patches plugin', () => { + const installed = (version: string) => ({ + 'drupal/composer.json': + JSON.stringify( + { + require: { [PLUGIN]: '^1.7', 'drupal/core-recommended': '~11' }, + config: { 'allow-plugins': { [PLUGIN]: true } }, + }, + null, + 4 + ) + '\n', + 'drupal/vendor/composer/installed.json': { + packages: [{ name: PLUGIN, version, 'install-path': `../${PLUGIN}` }], + }, + }) + + test('refuses a patch on a site with version 1 of the plugin, naming the version', async () => { + const root = project({ engine: 'ddev' }, installed('1.7.3')) + const before = snapshot(root) + const result = await drx(['add', 'breadcrumb'], root) + expect(result.code).toBe(1) + expect(result.stderr).toContain( + 'Cannot add breadcrumb: This site has cweagans/composer-patches 1.7.3, and the patch "Fix the redirect loop" is written for version 2 of the plugin, which keeps patches in a lock file. Update the plugin to version 2, or pass --no-patches to add the module without the patch.' + ) + expect(snapshot(root)).toEqual(before) + }) + + test('goes by what is installed, and not by what the site asks for', async () => { + const { 'drupal/composer.json': manifest } = installed('1.7.3') + const root = project( + { engine: 'ddev' }, + { 'drupal/composer.json': manifest } + ) + const result = await drx(['add', 'breadcrumb'], root, { + exec: tools(root).exec, + }) + expect(result.code, result.stderr).toBe(0) + }) + + test.each(['2.0.0-beta2', '2.0.0', 'v2.1.0'])( + 'writes the patch with version %s', + async (version) => { + const root = project({ engine: 'ddev' }, installed(version)) + const result = await drx(['add', 'breadcrumb'], root, { + exec: tools(root).exec, + }) + expect(result.code, result.stderr).toBe(0) + expect(json(root, 'drupal/composer.json').extra.patches).toBeDefined() + } + ) + + test('adds a module with no patch whatever the version', async () => { + const root = project({ engine: 'ddev' }, installed('1.7.3')) + const result = await drx(['add', 'router'], root, { + exec: tools(root).exec, + }) + expect(result.code, result.stderr).toBe(0) + }) + + test('--no-patches adds the module on version 1', async () => { + const root = project({ engine: 'ddev' }, installed('1.7.3')) + const result = await drx(['add', 'breadcrumb', '--no-patches'], root, { + exec: tools(root).exec, + }) + expect(result.code, result.stderr).toBe(0) + }) +}) + +describe('drx remove with a registry that does not have the module', () => { + /** A project with breadcrumb added while the registry had it. */ + async function added() { + const root = withPlugin() + const before = files(root) + const { exec } = tools(root) + expect((await drx(['add', 'breadcrumb'], root, { exec })).code).toBe(0) + return { root, before, exec } + } + const WITHOUT = { + schemaVersion: 1, + modules: REGISTRY.modules.filter(({ name }) => name !== 'breadcrumb'), + } + + test.each([['breadcrumb'], ['druxt-breadcrumb']])( + 'works from the record alone, by %s', + async (name) => { + const { root, before, exec } = await added() + const result = await drx(['remove', name, '--backend'], root, { + exec, + ...registryOf(WITHOUT), + }) + expect(result.code, result.stderr).toBe(0) + expect(result.stdout).toBe('Removed breadcrumb.\n') + expect(config(root).modules).toBeUndefined() + expect(files(root)).toEqual(before) + } + ) + + test('works when the registry cannot be read and there is no copy of it', async () => { + const { root, before, exec } = await added() + const result = await drx(['remove', 'breadcrumb', '--backend'], root, { + exec, + defaultModuleRegistry: `${await closedPort()}/modules.json`, + cacheDir: tmp('drx-cache-'), + }) + expect(result.code, result.stderr).toBe(0) + expect(result.stderr).toContain( + 'drx remove goes by the record in drx.config.json.' + ) + expect(result.stderr).toContain( + 'Warning: Without the module registry, drx remove cannot tell whether another module of the project needs what it takes out of the backend.' + ) + expect(config(root).modules).toBeUndefined() + expect(files(root)).toEqual(before) + }) + + test('works when the registry is invalid', async () => { + const { root, exec } = await added() + const result = await drx(['remove', 'breadcrumb'], root, { + exec, + ...registryOf({ schemaVersion: 1, modules: [{ name: 'broken' }] }), + }) + expect(result.code, result.stderr).toBe(0) + }) + + test('still refuses a name that neither the registry nor the record has', async () => { + const { root, exec } = await added() + const result = await drx(['remove', 'nothing'], root, { + exec, + ...registryOf(WITHOUT), + }) + expect(result.code).toBe(1) + expect(result.stderr).toContain('There is no module named "nothing"') + const offline = await drx(['remove', 'nothing'], root, { + exec, + defaultModuleRegistry: `${await closedPort()}/modules.json`, + cacheDir: tmp('drx-cache-'), + }) + expect(offline.code).toBe(1) + expect(offline.stderr).toContain( + 'drx add recorded no module named "nothing" in this project.' + ) + }) + + test('drx add still needs the registry', async () => { + const root = project() + const result = await drx(['add', 'breadcrumb'], root, { + defaultModuleRegistry: `${await closedPort()}/modules.json`, + cacheDir: tmp('drx-cache-'), + }) + expect(result.code).toBe(1) + expect(result.stderr).toContain('There is no cached copy to use.') + }) +}) + +describe('drx add when no part takes what the module needs', () => { + const parts = (...list: Record[]) => ({ + 'drx.config.json': { + layout: 'monorepo', + line: '0.x', + starter: 'quickstart', + source: 'npm', + parts: list, + }, + }) + const NUXT = { role: 'frontend', kind: 'nuxt', path: 'nuxt' } + const DRUPAL = { role: 'backend', kind: 'drupal', path: 'drupal' } + + test('refuses when the frontend part is of a kind it has no way to add to', async () => { + const root = project( + undefined, + parts({ role: 'frontend', kind: 'astro', path: 'nuxt' }, DRUPAL) + ) + const before = snapshot(root) + const result = await drx(['add', 'blocks', '--json'], root) + expect(result.code).toBe(1) + expect(JSON.parse(result.stdout)).toMatchObject({ + ok: false, + error: { code: 'refused' }, + }) + expect(result.stderr).toContain( + 'Cannot add blocks: No frontend part of this project can take druxt-blocks. nuxt/ is of the kind astro, which this version cannot add a module to.' + ) + expect(snapshot(root)).toEqual(before) + }) + + test('refuses when the directory of the frontend part is not there', async () => { + const root = project( + undefined, + parts({ role: 'frontend', kind: 'nuxt', path: 'web' }, DRUPAL) + ) + const result = await drx(['add', 'blocks'], root) + expect(result.code).toBe(1) + expect(result.stderr).toContain( + 'Cannot add blocks: No frontend part of this project can take druxt-blocks. web/ does not exist.' + ) + expect(config(root).modules).toBeUndefined() + }) + + test('--force does not add it either', async () => { + const root = project(undefined, parts(DRUPAL)) + const result = await drx(['add', 'blocks', '--force'], root) + expect(result.code).toBe(1) + expect(result.stderr).toContain( + 'Cannot add blocks: No frontend part of this project can take druxt-blocks. The project has no frontend part.' + ) + }) + + test('lists what the module needs of a backend the project does not have', async () => { + const root = project(undefined, parts(NUXT)) + const { calls, exec } = tools(root) + const result = await drx(['add', 'breadcrumb'], root, { exec }) + expect(result.code, result.stderr).toBe(0) + expect(calls).toEqual(['nuxt$ npm install -- druxt-breadcrumb']) + expect(result.stdout).toBe( + [ + 'Added breadcrumb.', + '', + 'Left to do:', + ' breadcrumb needs a backend, and this project has no backend part that can take what it needs. Where the backend is:', + ' Enable Decoupled Router (decoupled_router)', + ' Patch Decoupled Router with https://example.com/mr/12.diff (Fix the redirect loop)', + '', + ].join('\n') + ) + }) + + test('a dry run lists it too', async () => { + const root = project(undefined, parts(NUXT)) + const result = await drx(['add', 'auth', '--dry-run', '--json'], root) + expect(JSON.parse(result.stdout).modules[0].leftToDo).toEqual([ + 'auth needs a backend, and this project has no backend part that can take what it needs. Where the backend is:', + ' Enable Simple OAuth (simple_oauth)', + ' Simple OAuth: Generate the keys', + ' drush simple-oauth:generate-keys ../keys', + ]) + }) + + test('says nothing of a backend for a module that needs none', async () => { + const root = project(undefined, parts(NUXT)) + const result = await drx(['add', 'node-preview', '--force'], root, { + exec: tools(root).exec, + }) + expect(result.stdout).toBe('Added node-preview.\n') + }) +}) + +describe('a file that changes between the plan and the step', () => { + /** Tools whose install also writes to the config, as a script of it may. */ + const installing = (root: string, write: (source: string) => string) => { + const { exec } = tools(root) + const wrapped: CliContext['exec'] = async (command, args, options) => { + const result = await exec(command, args, options) + if (command === 'npm') { + const file = join(root, 'nuxt/nuxt.config.js') + writeFileSync(file, write(readFileSync(file, 'utf8'))) + } + return result + } + return wrapped + } + + test('an edit is made to the file as the step finds it', async () => { + const root = project() + const result = await drx(['add', 'blocks'], root, { + exec: installing(root, (source) => + source.replace( + ' localhostListenURL', + " 'by-the-install',\n localhostListenURL" + ) + ), + }) + expect(result.code, result.stderr).toBe(0) + const config = read(root, 'nuxt/nuxt.config.js') + expect(config).toContain("'by-the-install'") + expect(config).toContain("'druxt-blocks'") + }) + + test('a file that no longer takes the edit fails the step, and the record says what was done', async () => { + const root = project() + const result = await drx(['add', 'blocks', '--json'], root, { + exec: installing(root, () => 'export default () => ({ modules: [] })\n'), + }) + expect(result.code).toBe(1) + expect(JSON.parse(result.stdout).error).toMatchObject({ + code: 'step-failed', + failed: { + part: 'nuxt', + step: "Add 'druxt-blocks' to modules in nuxt.config.js", + exitCode: 1, + output: + 'nuxt.config.js has changed since it was read, and its modules can no longer be edited safely.', + }, + done: ['nuxt/: npm install -- druxt-blocks'], + notDone: [ + "nuxt/: Add 'druxt-blocks' to modules in nuxt.config.js", + 'drupal/: ddev drush en -y -- block', + ], + }) + expect(config(root).modules).toEqual([ + { + name: 'blocks', + package: 'druxt-blocks', + frontend: [{ path: 'nuxt', installed: true, listed: false }], + backend: [], + }, + ]) + }) + + test('the record is added to the config file as it is by then', async () => { + const root = project() + const { exec } = tools(root) + // Something else writes to the file while the tools run. + const wrapped: CliContext['exec'] = async (command, args, options) => { + if (command === 'npm') { + const file = join(root, 'drx.config.json') + const now = JSON.parse(readFileSync(file, 'utf8')) + writeFileSync(file, JSON.stringify({ ...now, line: '2.x' })) + } + return exec(command, args, options) + } + await drx(['add', 'blocks'], root, { exec: wrapped }) + expect(config(root).line).toBe('2.x') + expect(config(root).modules).toHaveLength(1) + }) +}) + +describe('a record that names something no tool should be given', () => { + test('is refused as the file is read, and nothing is run', async () => { + const root = project() + const file = join(root, 'drx.config.json') + const hostile = JSON.parse(readFileSync(file, 'utf8')) + hostile.modules = [ + { + name: 'blocks', + package: 'druxt-blocks', + frontend: [{ path: 'nuxt', installed: true, listed: true }], + backend: [ + { + path: 'drupal', + modules: [ + { + name: 'block', + package: '--working-dir=/', + enabled: true, + required: true, + }, + ], + patches: [], + }, + ], + }, + ] + writeFileSync(file, JSON.stringify(hostile)) + const before = snapshot(root) + const result = await drx(['remove', 'blocks', '--backend', '--json'], root) + expect(result.code).toBe(1) + expect(JSON.parse(result.stdout).error).toMatchObject({ + code: 'config', + message: `${file} is invalid: modules[0].backend[0].modules[0].package must be the name of a Composer package, as in vendor/name.`, + }) + expect(result.stderr).not.toContain('A command was run') + expect(snapshot(root)).toEqual(before) + }) +}) + +describe('drx remove in a terminal with no name', () => { + test('offers what is on the record, in the registry or not', async () => { + const root = project() + const { exec } = tools(root) + await drx(['add', 'breadcrumb', 'blocks'], root, { exec }) + const { prompter, asked } = answering({ + 'Which modules?': ['breadcrumb'], + 'Make these changes?': true, + }) + const result = await run( + ['remove'], + { + cwd: root, + env: { XDG_CONFIG_HOME: tmp(), NO_COLOR: '1' }, + exec, + prompter, + ...registryOf({ + schemaVersion: 1, + modules: REGISTRY.modules.filter(({ name }) => name !== 'breadcrumb'), + }), + }, + { columns: 100 } + ) + expect(result.code, result.stderr).toBe(0) + expect(asked[0]?.choices?.map(({ value }) => value)).toEqual([ + 'blocks', + 'breadcrumb', + ]) + expect(result.stdout).toContain('Removed breadcrumb.') + expect(json(root, 'nuxt/package.json').dependencies).not.toHaveProperty( + 'druxt-breadcrumb' + ) + }) +}) diff --git a/packages/cli/test/commands/init-engines.test.ts b/packages/cli/test/commands/init-engines.test.ts index ee03631..ac5201d 100644 --- a/packages/cli/test/commands/init-engines.test.ts +++ b/packages/cli/test/commands/init-engines.test.ts @@ -83,6 +83,7 @@ function answering(answers: Record) { } const prompter: Prompter = { search: async ({ message, choices }) => answer(message, choices) as never, + pickMany: async ({ message, choices }) => answer(message, choices) as never, text: async ({ message }) => answer(message) as string, select: async ({ message, choices }) => answer(message, choices) as never, confirm: async ({ message }) => answer(message) as boolean, @@ -439,6 +440,70 @@ describe('drx init --engine --force, into a directory that holds files', () => { expect(has('drupal/.ddev/config.yaml')).toBe(true) }) + const RECORD = { + name: 'breadcrumb', + package: 'druxt-breadcrumb', + frontend: [{ path: 'nuxt', installed: true, listed: true }], + backend: [ + { + path: 'drupal', + modules: [ + { + name: 'decoupled_router', + package: 'drupal/decoupled_router', + enabled: true, + required: true, + }, + ], + patches: [], + }, + ], + } + const existing = (extra: Record) => ({ + layout: 'monorepo', + line: '0.x', + starter: 'quickstart', + source: 'npm', + parts: [ + { role: 'frontend', kind: 'nuxt', path: 'nuxt' }, + { role: 'backend', kind: 'drupal', path: 'drupal', engine: 'lando' }, + ], + ...extra, + }) + + test('keeps the record of the modules drx add put in the project', async () => { + writeTree(cwd, { + 'site/drx.config.json': existing({ modules: [RECORD] }), + }) + const result = await init(['--yes', '--engine', 'ddev', '--force']) + expect(result.code).toBe(0) + expect(config().modules).toEqual([RECORD]) + // The rest of the file is what this run settled. + expect(backend().engine).toBe('ddev') + expect(result.stderr).toContain( + 'Kept the record of the 1 module drx add put in this project.' + ) + }) + + test('writes no record where the project had none', async () => { + writeTree(cwd, { 'site/drx.config.json': existing({}) }) + const result = await init(['--yes', '--engine', 'ddev', '--force']) + expect(result.code).toBe(0) + expect(config().modules).toBeUndefined() + expect(result.stderr).not.toContain('Kept the record') + }) + + test('says so when the file that was there cannot be read', async () => { + writeTree(cwd, { 'site/drx.config.json': '{ not json' }) + const result = await init(['--yes', '--engine', 'ddev', '--force']) + expect(result.code).toBe(0) + expect(config().modules).toBeUndefined() + expect(result.stderr).toContain('Warning: The drx.config.json that was in') + expect(result.stderr).toContain( + 'could not be read, so no record of added modules was kept from it.' + ) + }) + test('still removes them from a directory that exists and is empty', async () => { writeTree(cwd, { 'site/.keep': '' }) rmSync(site('.keep')) diff --git a/packages/cli/test/commands/init.test.ts b/packages/cli/test/commands/init.test.ts index 4724340..d89008b 100644 --- a/packages/cli/test/commands/init.test.ts +++ b/packages/cli/test/commands/init.test.ts @@ -55,6 +55,7 @@ function scripted(answers: unknown[]) { } const prompter: Prompter = { search: async ({ message }) => next(message) as never, + pickMany: async ({ message }) => next(message) as never, text: async ({ message }) => next(message) as string, select: async ({ message }) => next(message) as never, confirm: async ({ message }) => next(message) as boolean, diff --git a/packages/cli/test/commands/menu.test.ts b/packages/cli/test/commands/menu.test.ts index 3a3d03a..88516a7 100644 --- a/packages/cli/test/commands/menu.test.ts +++ b/packages/cli/test/commands/menu.test.ts @@ -159,8 +159,8 @@ describe('bare drx in a terminal, inside a project', () => { { value: 'search', label: 'Search the modules' }, { value: 'show', label: "View a module's details" }, { value: 'info', label: "View this project's details" }, - { value: 'add', label: 'Add a module', ...unavailable }, - { value: 'remove', label: 'Remove a module', ...unavailable }, + { value: 'add', label: 'Add a module' }, + { value: 'remove', label: 'Remove a module' }, { value: 'configure', label: 'Configure a module', ...unavailable }, { value: 'patches', label: 'Manage patches', ...unavailable }, { value: 'quit', label: 'Quit' }, @@ -211,7 +211,42 @@ describe('bare drx in a terminal, inside a project', () => { expect(menu.stderr).toContain('Repeat this with: drx info') }) - test.each(['add', 'remove', 'configure', 'patches'])( + test('adds the modules picked from a list, as drx add does', async () => { + const cwd = project() + writeTree(cwd, { + 'nuxt/nuxt.config.js': 'export default { modules: [] }\n', + }) + const calls: string[] = [] + const result = await terminal( + [], + { + [MENU]: 'add', + 'Which modules?': ['blocks'], + 'Make these changes?': true, + }, + { + cwd, + exec: async (command, args) => { + calls.push([command, ...args].join(' ')) + return { code: 0, output: '' } + }, + } + ) + expect(result.code).toBe(0) + expect(calls[0]).toBe('npm install -- druxt-blocks') + expect(result.stdout).toContain('Added blocks.') + expect(result.stderr).toContain('Repeat this with: drx add blocks --yes') + }) + + test('offers to remove only what the project has', async () => { + const result = await terminal([], { [MENU]: 'remove' }, { cwd: project() }) + expect(result.code).toBe(1) + expect(result.stderr).toContain( + 'There is no module to remove in this project.' + ) + }) + + test.each(['configure', 'patches'])( 'says %s is not available yet if it is chosen all the same', async (choice) => { const result = await terminal([], { [MENU]: choice }, { cwd: project() }) @@ -323,8 +358,10 @@ describe('--json in a terminal, with the banner settings at their defaults', () [['module', 'search', 'block', '--json']], [['module', 'info', 'blocks', '--json']], [['module', 'info', 'nothing-like-it', '--json']], - [['module', 'add', 'blocks', '--json']], - [['module', 'remove', 'blocks', '--json']], + [['add', 'blocks', '--dry-run', '--json']], + [['module', 'add', 'blocks', '--dry-run', '--json']], + [['remove', 'blocks', '--dry-run', '--json']], + [['add', '--json']], [['module', 'configure', 'blocks', '--json']], [['module', '--json']], [['init', 'site', '--yes', '--json']], diff --git a/packages/cli/test/commands/module.test.ts b/packages/cli/test/commands/module.test.ts index 5303e67..4a05489 100644 --- a/packages/cli/test/commands/module.test.ts +++ b/packages/cli/test/commands/module.test.ts @@ -462,7 +462,7 @@ describe('the module registry the commands read', () => { }) describe('the module commands that are not built', () => { - test.each(['add', 'remove', 'configure'])( + test.each(['configure'])( 'drx module %s says it is not available yet', async (command) => { const result = await drx(['module', command, 'blocks', '--json']) diff --git a/packages/cli/test/engines/engines.test.ts b/packages/cli/test/engines/engines.test.ts index 8d72eed..b402464 100644 --- a/packages/cli/test/engines/engines.test.ts +++ b/packages/cli/test/engines/engines.test.ts @@ -49,6 +49,19 @@ describe.each(['ddev', 'lando'])('the %s engine', (name) => { }) }) +describe('whether an engine runs on this machine', () => { + test('is true for all but the one for a backend that is elsewhere', () => { + expect( + knownEngines().map((name) => [name, engineFor(name)!.local]) + ).toEqual([ + ['php', true], + ['ddev', true], + ['lando', true], + ['none', false], + ]) + }) +}) + describe('the none engine', () => { test('cannot run a tool, and says the backend is elsewhere', () => { const attempt = () => engineFor('none')!.run(part, 'drush', ['en', 'druxt']) diff --git a/packages/cli/test/exec.test.ts b/packages/cli/test/exec.test.ts new file mode 100644 index 0000000..042ac7d --- /dev/null +++ b/packages/cli/test/exec.test.ts @@ -0,0 +1,179 @@ +import { join } from 'node:path' +import { afterEach, describe, expect, test } from 'vitest' +import { findCommandFile } from '../src/commands-on-path.js' +import { runTool, runToolOn, spawnOf } from '../src/exec.js' +import { cleanTmp, tmp, writeTree } from './helpers/tmp.js' + +afterEach(cleanTmp) + +describe.skipIf(process.platform === 'win32')('runTool', () => { + test('returns the exit code and everything the tool printed', async () => { + const cwd = tmp() + const result = await runTool( + 'sh', + ['-c', 'echo out; echo err >&2; pwd; exit 3'], + { cwd } + ) + expect(result.code).toBe(3) + expect(result.output).toContain('out\n') + expect(result.output).toContain('err\n') + expect(result.output).toContain(cwd) + }) + + test('reports a tool that is not installed as a failure, with the reason', async () => { + const result = await runTool('no-such-tool-here', ['x'], { cwd: tmp() }) + expect(result.code).not.toBe(0) + expect(result.output).toContain('no-such-tool-here') + }) + + test('hands an argument over as it is, whatever characters it holds', async () => { + const cwd = tmp() + const hostile = + '$(touch made); `touch made`; touch made & echo "%PATH%" > made' + const result = await runTool('printf', ['%s', hostile], { cwd }) + expect(result).toEqual({ code: 0, output: hostile }) + expect(await runTool('ls', [], { cwd })).toEqual({ code: 0, output: '' }) + }) +}) + +// The Windows rules, with the platform passed in. They are checked here for +// the command line they build, and have not been run on Windows. +describe('the command line of a tool on Windows', () => { + const NPM = String.raw`C:\Program Files\nodejs\npm.cmd` + const on = (file: string | undefined, shell?: string) => ({ + platform: 'win32', + find: () => file, + ...(shell ? { shell } : {}), + }) + + test('anywhere else is the command and its arguments, with no shell', () => { + expect( + spawnOf('npm', ['install', '--', 'a&b'], { + platform: 'linux', + find: () => { + throw new Error('Nothing is looked up.') + }, + }) + ).toEqual({ file: 'npm', args: ['install', '--', 'a&b'], verbatim: false }) + }) + + test('runs a program by its file, with no shell', () => { + const file = String.raw`C:\tools\ddev.exe` + expect( + spawnOf('ddev', ['composer', 'require', '^2 & calc'], on(file)) + ).toEqual({ + file, + args: ['composer', 'require', '^2 & calc'], + verbatim: false, + }) + }) + + test('leaves a command it cannot find to fail as one that is not installed', () => { + expect(spawnOf('ddev', ['start'], on(undefined))).toEqual({ + file: 'ddev', + args: ['start'], + verbatim: false, + }) + }) + + test('runs a batch file through the command interpreter, every argument quoted', () => { + expect(spawnOf('npm', ['install', '--', 'druxt-a'], on(NPM))).toEqual({ + file: 'cmd.exe', + args: ['/d', '/s', '/c', `""${NPM}" "install" "--" "druxt-a""`], + verbatim: true, + }) + }) + + test('uses the interpreter the system names', () => { + const shell = String.raw`C:\Windows\System32\cmd.exe` + expect(spawnOf('npm', [], on(NPM, shell))).toMatchObject({ file: shell }) + }) + + test.each(['.cmd', '.CMD', '.bat', '.BAT'])( + 'takes %s for a batch file', + (extension) => { + const file = String.raw`C:\php\composer` + extension + expect(spawnOf('composer', ['install'], on(file))).toMatchObject({ + file: 'cmd.exe', + verbatim: true, + }) + } + ) + + test('keeps what the interpreter would read inside the quotes', () => { + const plan = spawnOf( + 'composer', + ['require', '--', 'cweagans/composer-patches:^2.0@beta', 'a&b|c>dd { + const plan = spawnOf('npm', [String.raw`C:\site\ `.trim()], on(NPM)) + expect(plan).toMatchObject({ + args: ['/d', '/s', '/c', String.raw`""${NPM}" "C:\site\\""`], + }) + }) + + test.each([ + ['a quote', 'x" & calc & "'], + ['a percent sign', '%PATH%'], + ['a line break', 'x\ncalc'], + ['a carriage return', 'x\rcalc'], + ])('refuses an argument with %s for a batch file', (_name, argument) => { + const plan = spawnOf('npm', ['install', argument], on(NPM)) + expect(plan).toEqual({ + refused: `npm is a batch file on Windows, and ${JSON.stringify(argument)} cannot be handed to one as it is: it has a quote, a percent sign or a line break in it.`, + }) + }) + + test('hands the same argument to a program, which reads no such thing', () => { + expect( + spawnOf('ddev', ['%PATH%', '"'], on(String.raw`C:\tools\ddev.exe`)) + ).toMatchObject({ args: ['%PATH%', '"'], verbatim: false }) + }) + + test('a refused argument is a failed tool, and nothing is started', async () => { + const dir = tmp('drx-path-') + writeTree(dir, { 'npm.cmd': '@echo off\n' }) + const run = runToolOn('win32', { PATH: dir }) + const result = await run('npm', ['install', '%PATH%'], { cwd: tmp() }) + expect(result.code).toBe(126) + expect(result.output).toContain('cannot be handed to one as it is') + }) +}) + +describe('finding the file of a command on Windows', () => { + test('looks a name up on PATH, with the extensions of PATHEXT', () => { + const dir = tmp('drx-path-') + writeTree(dir, { 'npm.cmd': '' }) + expect(findCommandFile('npm', tmp(), { PATH: dir }, 'win32')).toBe( + join(dir, 'npm.cmd') + ) + }) + + test('looks a path up from the directory the tool runs in', () => { + const cwd = tmp('drx-part-') + writeTree(cwd, { 'vendor/bin/drush.bat': '', 'vendor/bin/drush': '' }) + expect(findCommandFile('vendor/bin/drush', cwd, {}, 'win32')).toBe( + join(cwd, 'vendor/bin/drush.bat') + ) + expect(findCommandFile('vendor/bin/drush.bat', cwd, {}, 'win32')).toBe( + join(cwd, 'vendor/bin/drush.bat') + ) + }) + + test('is undefined for a path that names no file', () => { + expect( + findCommandFile('vendor/bin/drush', tmp(), {}, 'win32') + ).toBeUndefined() + }) +}) diff --git a/packages/cli/test/fixtures/quickstart-nuxt.config.js b/packages/cli/test/fixtures/quickstart-nuxt.config.js new file mode 100644 index 0000000..63022e4 --- /dev/null +++ b/packages/cli/test/fixtures/quickstart-nuxt.config.js @@ -0,0 +1,149 @@ +require('dotenv').config({ path: '../.env' }) +const baseUrl = process.env.BASE_URL || '' + + +// Bound to 0.0.0.0, Nuxt reports the container-internal interface IP as +// its listen URL - unreachable from the host. Rewrite the reported URL +// only: the bind stays 0.0.0.0 so container port forwarding keeps working. +const localhostListenURL = function () { + this.nuxt.hook('listen', (server, listener) => { + listener.host = 'localhost' + listener.url = `http://localhost:${listener.port}/` + }) +} + +export default { + target: process.env.NUXT_TARGET, + + // Nuxt 2 defaults to binding 'localhost' (loopback only), which is not + // reachable through devcontainer/DevPod port forwarding - the forwarded + // port maps to the container's network interface, not its loopback. + // https://v2.nuxt.com/docs/configuration-glossary/configuration-server/ + server: { + host: process.env.HOST || '0.0.0.0', + port: process.env.PORT || 3000 + }, + + // Global page headers: https://go.nuxtjs.dev/config-head + head: { + title: 'quickstart-druxt-site', + htmlAttrs: { + lang: 'en' + }, + meta: [ + { charset: 'utf-8' }, + { name: 'viewport', content: 'width=device-width, initial-scale=1' }, + { hid: 'description', name: 'description', content: '' }, + { name: 'format-detection', content: 'telephone=no' } + ], + link: [ + { rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' } + ] + }, + + // Global CSS: https://go.nuxtjs.dev/config-css + css: [ + ], + + // Plugins to run before rendering page: https://go.nuxtjs.dev/config-plugins + plugins: [ + ], + + // Auto import components: https://go.nuxtjs.dev/config-components + components: true, + + // Modules for dev and build (recommended): https://go.nuxtjs.dev/config-modules + buildModules: [ + // https://go.nuxtjs.dev/eslint + '@nuxtjs/eslint-module' + ], + + // Modules: https://go.nuxtjs.dev/config-modules + // + // Druxt belongs in `modules`, NOT `buildModules`: Nuxt 2 does not load + // buildModules on `nuxt start`, so anything runtime the module + // registers - the @nuxtjs/proxy serverMiddleware behind + // `druxt.proxy.api`, the axios defaults - silently vanishes from + // production. The visible symptom: client-side /jsonapi requests get + // the app's own HTML shell back, and hydration wipes the SSR-rendered + // menus. Matches the druxt.js monorepo's own example placement. + modules: [ + ['druxt-auth', { clientId: process.env.OAUTH_CLIENT_ID }], + 'druxt-site', + localhostListenURL + ], + + // DruxtJS: https://druxtjs.org + druxt: { + // The baseUrl of the Druxt enabled Drupal JSON:API server. + baseUrl, + + // Set the JSON:API endpoint, `/jsonapi` by default. + // endpoint: '/jsonapi' + + // DruxtEntity module settings; https://druxtjs.org/modules/entity + entity: { + // Disable the deprecated DruxtField components. + components: { fields: false }, + + query: { + // Enable Drupal display mode schema based filtering of the JSON:API + // resource to reduce query size. + // schema: true, + }, + }, + + // DruxtMenu module settings; https://druxtjs.org/modules/menu + menu: { + // Disable JSON:API Menu Items support. Enabled by the DruxtSite module. + // jsonApiMenuItems: false + }, + + // Druxt proxy settings. + proxy: { + // Proxy the JSON:API request via the Nuxt proxy to prevent CORS issues. + api: true + + // Proxy the Drupal files system, using `sites/default/files` by default. + // Disable the proxy, or set a specific site to proxy. + // files: 'domain.tld' + }, + + // DruxtRouter module settings; https://druxtjs.org/modules/router + router: { + // Experimental; Disable the DruxtRouter page middleware, removing routing + // requests and server side redirects. Doing this allows Full Static + // builds without the need of a live Drupal backend. The Route is still + // is retrieved by the fetch hook instead. + middleware: false + + // Disable the wildcard router, which is enabled by default in the + // DruxtSite module. This allows more fine grained control over your + // routing. + // wildcard: false + }, + + // DruxtSite module settings; https://druxtjs.org/modules/site + site: { + // Disable the DruxtSite default layout. + // layout: false, + + // Set the backend theme for DruxtBlock layouts. + theme: 'olivero' + }, + + // DruxtViews module settings; https://druxtjs.org/modules/views + views: { + query: { + // Filter the View results using the Views bundle filter, if available. + // This reduces requests to just ID and type, and can be done manually + // if the bundle filter has not been set in Drupal. + bundleFilter: true, + } + } + }, + + // Build Configuration: https://go.nuxtjs.dev/config-build + build: { + } +} diff --git a/packages/cli/test/helpers/prompter.ts b/packages/cli/test/helpers/prompter.ts index bd144f6..c278434 100644 --- a/packages/cli/test/helpers/prompter.ts +++ b/packages/cli/test/helpers/prompter.ts @@ -31,6 +31,8 @@ export function answering( text: async ({ message }) => answer(message) as string, select: async ({ message, choices }) => answer(message, choices) as never, search: async ({ message, choices }) => answer(message, choices) as never, + pickMany: async ({ message, choices }) => + answer(message, choices) as never, confirm: async ({ message }) => answer(message) as boolean, }, } diff --git a/packages/cli/test/helpers/run.ts b/packages/cli/test/helpers/run.ts index f54ec43..3f9a14f 100644 --- a/packages/cli/test/helpers/run.ts +++ b/packages/cli/test/helpers/run.ts @@ -29,6 +29,12 @@ export async function run( cwd: tmp(), env: { XDG_CONFIG_HOME: tmp('drx-config-') }, cacheDir: tmp('drx-cache-'), + // A test that expects a tool to run passes its own stand-in. + exec: async (command, args) => { + throw new Error( + `A real command was about to run: ${command} ${args.join(' ')}` + ) + }, stdout: { write: (chunk) => (stdout += chunk), ...tty }, stderr: { write: (chunk) => (stderr += chunk), ...tty }, interactive: terminal !== undefined, diff --git a/packages/cli/test/modules/entry.test.ts b/packages/cli/test/modules/entry.test.ts index fd0aba4..afd6946 100644 --- a/packages/cli/test/modules/entry.test.ts +++ b/packages/cli/test/modules/entry.test.ts @@ -5,6 +5,9 @@ import { moduleRegistry, moduleRegistryWith } from '../helpers/modules.js' const AT = 'https://example.com/modules.json' const NPM_NAME = 'modules[1].npm must be the name of an npm package' +const PACKAGE = + 'package must be the name of a Composer package, as in vendor/name' +const CONSTRAINT = 'constraint must be a Composer version constraint' const MODULE_NAME = 'modules[1].drupal[0].name must be a machine name: lower-case letters, digits and underscores, starting with a letter' @@ -182,4 +185,247 @@ describe('parseModuleRegistry', () => { `The module registry at ${AT} is invalid: ${message}.` ) }) + + test('reads what a backend module needs done to add it', () => { + const registry = moduleRegistryWith(1, (module) => { + module.drupal = [ + { + name: 'jsonapi_menu', + label: 'Menu items', + composer: { + package: 'drupal/jsonapi_menu_items', + constraint: '^1.2', + }, + setup: [ + { + title: 'Create a consumer', + command: 'drush x', + url: 'https://example.com/doc', + }, + { title: 'Save the keys' }, + ], + patches: [ + { + description: 'Fix a crash', + url: 'https://example.com/1.diff', + package: 'drupal/core', + issue: 'https://example.com/issue/1', + until: '11.3.0', + }, + { description: 'Another', url: 'https://example.com/2.diff' }, + ], + }, + ] + }) + expect(parseModuleRegistry(registry, AT)[1]?.backend).toEqual([ + { + kind: 'drupal', + name: 'jsonapi_menu', + label: 'Menu items', + composer: { package: 'drupal/jsonapi_menu_items', constraint: '^1.2' }, + setup: [ + { + title: 'Create a consumer', + command: 'drush x', + url: 'https://example.com/doc', + }, + { title: 'Save the keys' }, + ], + patches: [ + { + description: 'Fix a crash', + url: 'https://example.com/1.diff', + package: 'drupal/core', + issue: 'https://example.com/issue/1', + until: '11.3.0', + }, + { description: 'Another', url: 'https://example.com/2.diff' }, + ], + }, + ]) + }) + + test.each([ + [{ composer: 'drupal/x' }, 'composer must be an object'], + [{ composer: {} }, 'composer.package must be a non-empty string'], + [ + { composer: { package: 'drupal/x', constraint: 1 } }, + 'composer.constraint must be a string', + ], + [{ setup: 'x' }, 'setup must be an array'], + [{ setup: [{}] }, 'setup[0].title must be a non-empty string'], + [ + { setup: [{ title: 'x', command: 1 }] }, + 'setup[0].command must be a string', + ], + [{ patches: {} }, 'patches must be an array'], + [ + { patches: [{ url: 'https://example.com/a.diff' }] }, + 'patches[0].description must be a non-empty string', + ], + [ + { patches: [{ description: 'x', url: 'ftp://example.com/a.diff' }] }, + 'patches[0].url must be an http or https URL', + ], + [ + { + patches: [ + { description: 'x', url: 'https://example.com/a.diff', until: 1 }, + ], + }, + 'patches[0].until must be a string', + ], + [{ composer: { package: '--working-dir=/tmp' } }, `composer.${PACKAGE}`], + [{ composer: { package: 'decoupled_router' } }, `composer.${PACKAGE}`], + [{ composer: { package: 'Drupal/Token' } }, `composer.${PACKAGE}`], + [{ composer: { package: 'drupal/a b' } }, `composer.${PACKAGE}`], + [{ composer: { package: 'drupal/x:^1 | calc' } }, `composer.${PACKAGE}`], + [ + { composer: { package: 'drupal/x', constraint: '--no-plugins' } }, + `composer.${CONSTRAINT}`, + ], + [ + { composer: { package: 'drupal/x', constraint: '^1 & calc' } }, + `composer.${CONSTRAINT}`, + ], + [ + { composer: { package: 'drupal/x', constraint: '"^1"' } }, + `composer.${CONSTRAINT}`, + ], + [ + { composer: { package: 'drupal/x', constraint: '' } }, + `composer.${CONSTRAINT}`, + ], + ...[ + '^3.26 --no-plugins', + '^1.0 -W', + '^1.0 -', + '- 1.0', + '1.0 -2.0', + '1.0 - -2.0', + '^1.0 - 2.0', + '^1.0 nonsense', + 'nonsense', + '^', + '>=', + '>= <2', + '^1.0 ||', + '|| ^1.0', + '^1.0 ||| ^2.0', + '^1.0,,^2.0', + ',^1.0', + '^^1.0', + '1..0', + '^1.0 as', + 'as 1.0', + '^1.0@nightly', + 'dev-', + '1.0/2.0', + ].map((constraint): [Record, string] => [ + { composer: { package: 'drupal/x', constraint } }, + `composer.${CONSTRAINT}`, + ]), + [ + { + patches: [ + { + description: 'x', + url: 'https://example.com/a.diff', + package: '-d', + }, + ], + }, + `patches[0].${PACKAGE}`, + ], + ])('names the bad field of a backend module in %j', (extra, message) => { + const registry = moduleRegistryWith(1, (module) => { + module.drupal = [{ name: 'block', label: 'Block', ...extra }] + }) + expect(() => parseModuleRegistry(registry, AT)).toThrow( + `The module registry at ${AT} is invalid: modules[1].drupal[0].${message}.` + ) + }) + + test.each([ + '^1.2', + '~2.0@beta', + '>=1.0 <2.0 || ^3', + '1.0 - 2.0', + 'dev-main', + '1.x-dev#abc123', + 'dev-feature/thing as 1.0.0', + '*', + '!=1.3.0, >=1.2', + '^3.26 || ^4.0', + '^3.26||^4.0', + '^1 | ^2', + '>=1.0 <2.0', + '>=1.0,<2.0', + '>= 1.0', + '1.0.0-beta1', + '^2.0@beta', + '~1.2.3@RC', + '2.x-dev', + '1.2.*', + 'v1.2.3', + '1.0.0+build.5', + '1.0.x-dev as 1.0.0', + 'dev-main#a1b2c3', + '@dev', + '<>1.4', + '==1.2.3', + ])('takes %j as a constraint', (constraint) => { + const registry = moduleRegistryWith(1, (module) => { + module.drupal = [ + { + name: 'block', + label: 'Block', + composer: { package: 'drupal/jsonapi_menu_items', constraint }, + }, + ] + }) + expect( + parseModuleRegistry(registry, AT)[1]?.backend[0]?.composer?.constraint + ).toBe(constraint) + }) + + test.each(['drupal/core', 'cweagans/composer-patches', 'a/b', 'my.org/a--b'])( + 'takes %j as a package', + (name) => { + const registry = moduleRegistryWith(1, (module) => { + module.drupal = [ + { + name: 'block', + label: 'Block', + composer: { package: name }, + patches: [ + { + description: 'x', + url: 'https://example.com/a.diff', + package: name, + }, + ], + }, + ] + }) + expect( + parseModuleRegistry(registry, AT)[1]?.backend[0]?.composer?.package + ).toBe(name) + } + ) + + test('checks a long name in no more time than a short one', () => { + const registry = moduleRegistryWith(1, (module) => { + module.drupal = [ + { + name: 'block', + label: 'Block', + composer: { package: `a/${'a-'.repeat(50_000)}!` }, + }, + ] + }) + const started = performance.now() + expect(() => parseModuleRegistry(registry, AT)).toThrow(PACKAGE) + expect(performance.now() - started).toBeLessThan(200) + }) }) diff --git a/packages/cli/test/non-interactive.test.ts b/packages/cli/test/non-interactive.test.ts index e75fffb..fd87303 100644 --- a/packages/cli/test/non-interactive.test.ts +++ b/packages/cli/test/non-interactive.test.ts @@ -1,13 +1,13 @@ -import { existsSync } from 'node:fs' +import { existsSync, readFileSync, writeFileSync } from 'node:fs' import { join } from 'node:path' import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest' -import type { Prompter } from '../src/context.js' +import type { CliContext, Prompter } from '../src/context.js' import { validEngines } from './helpers/engines.js' import { moduleRegistry } from './helpers/modules.js' import { run } from './helpers/run.js' import { serve, type TestServer } from './helpers/server.js' import { fixtureRegistry, type FixtureRegistry } from './helpers/starter.js' -import { cleanTmp, tmp } from './helpers/tmp.js' +import { cleanTmp, tmp, writeTree } from './helpers/tmp.js' let modules: TestServer let starters: FixtureRegistry @@ -81,8 +81,19 @@ const COMMANDS: { argv: string[]; code: number; says?: string }[] = [ { argv: ['module', 'search'], code: 1, says: 'Give the text to search for' }, { argv: ['module', 'info', 'blocks'], code: 0 }, { argv: ['module', 'info'], code: 1, says: 'Give the name of a module' }, - { argv: ['module', 'add', 'blocks'], code: 1, says: 'not available yet' }, - { argv: ['module', 'remove', 'blocks'], code: 1, says: 'not available yet' }, + { argv: ['add', 'blocks'], code: 1, says: 'works inside a project' }, + { argv: ['add'], code: 1, says: 'works inside a project' }, + { argv: ['remove', 'blocks'], code: 1, says: 'works inside a project' }, + { + argv: ['module', 'add', 'blocks'], + code: 1, + says: 'works inside a project', + }, + { + argv: ['module', 'remove', 'blocks'], + code: 1, + says: 'works inside a project', + }, { argv: ['module', 'configure', 'blocks'], code: 1, @@ -131,6 +142,156 @@ describe.each(CONDITIONS)('with $name', (condition) => { ) }) +/** A project with one frontend and one backend part, and nothing added. */ +function project(): string { + const root = tmp('drx-project-') + writeTree(root, { + 'drx.config.json': { + layout: 'monorepo', + line: '0.x', + starter: 'quickstart', + source: 'npm', + parts: [ + { role: 'frontend', kind: 'nuxt', path: 'nuxt' }, + { role: 'backend', kind: 'drupal', path: 'drupal', engine: 'ddev' }, + ], + }, + 'nuxt/package.json': { dependencies: { druxt: '^0.25.1' } }, + 'nuxt/node_modules/druxt/package.json': { version: '0.25.2' }, + 'nuxt/nuxt.config.js': 'export default {\n modules: [],\n}\n', + 'drupal/composer.json': { require: { 'drupal/core-recommended': '~11' } }, + }) + return root +} + +/** Stand-ins for the tools: a package manager and a backend with a memory. */ +function tools() { + const calls: string[] = [] + const enabled = new Set() + const exec: CliContext['exec'] = async (command, args, { cwd }) => { + if (args.includes('pm:list')) { + const list = [...enabled].map((name) => [name, { name, path: '' }]) + return { code: 0, output: JSON.stringify(Object.fromEntries(list)) } + } + const name = args.at(-1) as string + if (args.includes('--simulate')) { + return enabled.has(name) + ? { + code: 0, + output: `The following extensions will be uninstalled: ${name}\n`, + } + : { code: 1, output: `not installed: ${name}` } + } + calls.push(`${command} ${args.join(' ')}`) + if (command === 'npm') { + const file = join(cwd, 'package.json') + const manifest = JSON.parse(readFileSync(file, 'utf8')) + if (args[0] === 'install') manifest.dependencies[name] = '^1.0.0' + else delete manifest.dependencies[name] + writeFileSync(file, JSON.stringify(manifest, null, 2)) + } + if (args.includes('en')) enabled.add(name) + if (args.includes('pmu')) enabled.delete(name) + return { code: 0, output: '' } + } + return { calls, exec } +} + +describe.each(CONDITIONS)( + 'adding and removing a module with $name', + (condition) => { + const ask = vi.fn(() => { + throw new Error('A prompt was shown.') + }) + const unattended = ( + argv: string[], + cwd: string, + exec: CliContext['exec'] + ) => + run( + [...argv, ...condition.flag], + { + cwd, + env: { XDG_CONFIG_HOME: tmp('drx-config-'), ...condition.env }, + defaultModuleRegistry: `${modules.url}/modules.json`, + prompter: { + text: ask, + select: ask, + search: ask, + pickMany: ask, + confirm: ask, + } as unknown as Prompter, + exec, + }, + condition.terminal ? { columns: 100 } : undefined + ) + const recorded = (root: string) => + JSON.parse(readFileSync(join(root, 'drx.config.json'), 'utf8')).modules + + // Braces, so the mock is not handed back to be called as a cleanup. + beforeEach(() => { + ask.mockClear() + }) + + test('drx add and drx remove run to the end and ask nothing', async () => { + const root = project() + const { calls, exec } = tools() + const added = await unattended(['add', 'blocks'], root, exec) + expect(added.code, added.stderr).toBe(0) + expect(added.stdout).toBe('Added blocks.\n') + expect(recorded(root)).toHaveLength(1) + expect(readFileSync(join(root, 'nuxt/nuxt.config.js'), 'utf8')).toContain( + 'druxt-blocks' + ) + + const removed = await unattended( + ['remove', 'blocks', '--backend'], + root, + exec + ) + expect(removed.code, removed.stderr).toBe(0) + expect(removed.stdout).toBe('Removed blocks.\n') + expect(recorded(root)).toBeUndefined() + expect(calls).toEqual([ + 'npm install -- druxt-blocks', + 'ddev drush en -y -- block', + 'npm uninstall -- druxt-blocks', + 'ddev drush pmu -y -- block', + ]) + expect(ask).not.toHaveBeenCalled() + expect(added.stderr + removed.stderr).not.toContain('A prompt was shown.') + }) + + test('drx module add --json prints one document and asks nothing', async () => { + const root = project() + const result = await unattended( + ['module', 'add', 'blocks', '--json'], + root, + tools().exec + ) + expect(result.code, result.stderr).toBe(0) + expect(JSON.parse(result.stdout)).toMatchObject({ + ok: true, + dryRun: false, + modules: [{ name: 'blocks', package: 'druxt-blocks' }], + }) + expect(ask).not.toHaveBeenCalled() + }) + + test.each([ + [['add'], 'Give the name of a module, as in "drx add blocks".'], + [['remove'], 'Give the name of a module, as in "drx remove blocks".'], + [['remove', 'blocks'], 'Cannot remove blocks: druxt-blocks is not in'], + [['add', 'legacy'], 'Cannot add legacy: legacy is archived.'], + ])('drx %j fails with a message, and asks nothing', async (argv, says) => { + const result = await unattended(argv, project(), tools().exec) + expect(result.code).toBe(1) + expect(result.stderr).toContain(says) + expect(ask).not.toHaveBeenCalled() + }) + } +) + describe('an option given before the command of a group', () => { let cwd: string beforeEach(() => { @@ -237,6 +398,32 @@ describe('an option given before the command of a group', () => { } }) + test('drx module add takes its registry and --json from before the command', async () => { + const other = await serve({ + '/other.json': JSON.stringify({ + schemaVersion: 1, + modules: [moduleRegistry().modules[1]], + }), + }) + try { + const url = `${other.url}/other.json` + const result = await run( + ['module', '--module-registry', url, '--json', 'add', 'blocks'], + { + cwd: project(), + defaultModuleRegistry: `${modules.url}/modules.json`, + exec: tools().exec, + } + ) + expect(result.code, result.stderr).toBe(0) + expect(JSON.parse(result.stdout).modules[0].name).toBe('blocks') + expect(other.requests).toHaveLength(1) + expect(modules.requests).toHaveLength(0) + } finally { + await other.close() + } + }) + test('a filter before the command leaves out what it does after it', async () => { for (const form of [ ['module', '--type', 'contrib', 'list'], diff --git a/packages/cli/test/project.test.ts b/packages/cli/test/project.test.ts index 1de3c09..d5e3ed8 100644 --- a/packages/cli/test/project.test.ts +++ b/packages/cli/test/project.test.ts @@ -23,6 +23,17 @@ const config: ProjectConfig = { ], } +const MACHINE_NAME = + 'must be a machine name: lower-case letters, digits and underscores, starting with a letter' +const COMPOSER_NAME = + 'must be the name of a Composer package, as in vendor/name' +/** A record of what was done to the backend part of the project. */ +const recordOf = (backend: Record, path = 'drupal') => ({ + name: 'x', + package: 'druxt-x', + backend: [{ path, modules: [], patches: [], ...backend }], +}) + describe('writeProjectConfig', () => { test('writes drx.config.json at the project root', async () => { const root = tmp() @@ -77,6 +88,186 @@ describe('loadProjectConfig', () => { ) }) + test('keeps the record of the modules that were added', async () => { + const root = tmp() + const recorded: ProjectConfig = { + ...config, + modules: [ + { + name: 'breadcrumb', + package: 'druxt-breadcrumb', + frontend: [{ path: 'nuxt', installed: true, listed: false }], + backend: [ + { + path: 'drupal', + modules: [ + { + name: 'decoupled_router', + package: 'drupal/decoupled_router', + enabled: false, + required: true, + }, + { name: 'block', enabled: true, required: false }, + ], + patches: [ + { + package: 'drupal/core', + description: 'Fix', + url: 'https://example.com/1.diff', + module: 'decoupled_router', + }, + ], + }, + ], + }, + ], + } + await writeProjectConfig(root, recorded) + expect(await loadProjectConfig(root)).toEqual(recorded) + }) + + test('reads the record an older version wrote', async () => { + const root = tmp() + const patch = { + package: 'drupal/core', + description: 'Fix', + url: 'https://example.com/1.diff', + } + writeTree(root, { + 'drx.config.json': { + ...config, + modules: [ + { + name: 'breadcrumb', + package: 'druxt-breadcrumb', + backend: [ + { + path: 'drupal', + modules: [ + { + name: 'decoupled_router', + package: 'drupal/decoupled_router', + }, + ], + patches: [patch], + }, + ], + }, + { name: 'blocks', package: 'druxt-blocks', backend: [] }, + ], + }, + }) + // It required and enabled every module it listed, and kept nothing on + // the frontend, which stays absent: the record does not say. + expect((await loadProjectConfig(root)).modules).toEqual([ + { + name: 'breadcrumb', + package: 'druxt-breadcrumb', + backend: [ + { + path: 'drupal', + modules: [ + { + name: 'decoupled_router', + package: 'drupal/decoupled_router', + enabled: true, + required: true, + }, + ], + patches: [patch], + }, + ], + }, + { name: 'blocks', package: 'druxt-blocks', backend: [] }, + ]) + }) + + test.each([ + [{ modules: 'breadcrumb' }, 'modules must be an array'], + [ + { modules: [{ package: 'x' }] }, + 'modules[0].name must be a non-empty string', + ], + [ + { modules: [{ name: 'x' }] }, + 'modules[0].package must be a non-empty string', + ], + [ + { modules: [{ name: 'x', package: 'y', backend: {} }] }, + 'modules[0].backend must be an array', + ], + [ + { modules: [{ name: 'x', package: '--global', backend: [] }] }, + 'modules[0].package must be the name of an npm package', + ], + [ + { modules: [{ name: 'x', package: 'y & calc', backend: [] }] }, + 'modules[0].package must be the name of an npm package', + ], + [ + { modules: [recordOf({ modules: [{ name: 'a,b' }] })] }, + `modules[0].backend[0].modules[0].name ${MACHINE_NAME}`, + ], + [ + { modules: [recordOf({ modules: [{ name: '--root=/' }] })] }, + `modules[0].backend[0].modules[0].name ${MACHINE_NAME}`, + ], + [ + { + modules: [ + { name: 'w', package: 'w', backend: [] }, + recordOf({ modules: [{ name: 'a' }, { name: 'b', package: '-W' }] }), + ], + }, + `modules[1].backend[0].modules[1].package ${COMPOSER_NAME}`, + ], + [ + { + modules: [ + recordOf({ + patches: [ + { package: '| calc', description: 'x', url: 'https://e.org/x' }, + ], + }), + ], + }, + `modules[0].backend[0].patches[0].package ${COMPOSER_NAME}`, + ], + [ + { + modules: [ + recordOf({ + patches: [ + { + package: 'drupal/core', + description: 'x', + url: 'https://e.org/x', + module: 'a b', + }, + ], + }), + ], + }, + `modules[0].backend[0].patches[0].module ${MACHINE_NAME}`, + ], + ])('names the bad field of the record in %j', async (extra, message) => { + const root = tmp() + writeTree(root, { 'drx.config.json': { ...config, ...extra } }) + await expect(loadProjectConfig(root)).rejects.toThrow( + `${join(root, 'drx.config.json')} is invalid: ${message}.` + ) + }) + + test('keeps a record for a part the project no longer has, unread', async () => { + const root = tmp() + const record = recordOf({ modules: [{ name: 'not a name' }] }, 'gone') + writeTree(root, { 'drx.config.json': { ...config, modules: [record] } }) + // No part is at that path, so no tool is ever handed what it holds. + expect((await loadProjectConfig(root)).modules?.[0]?.backend[0]?.path).toBe( + 'gone' + ) + }) + test('reads a file again after it has changed', async () => { const root = tmp() await writeProjectConfig(root, config)