From 1b0640857a4c95c56170478e77018d22734a16c1 Mon Sep 17 00:00:00 2001 From: Stuart Clark Date: Wed, 18 Nov 2026 03:26:25 +0000 Subject: [PATCH 1/4] feat(cli): add drx add and drx remove drx add installs a Druxt module in a project, and drx remove takes it out again. - The module registry says how a module's backend half is added. - The Nuxt adapter installs the package and adds it to the framework's configuration file. - The Drupal adapter requires the Drupal modules with Composer and enables them with Drush. - `--dry-run` prints the steps and runs none of them. --- .changeset/first-release-cli.md | 1 + .cspell.json | 3 +- .prettierignore | 3 + README.md | 65 +- eslint.config.mjs | 1 + knip.jsonc | 2 + package-lock.json | 7 +- packages/cli/README.md | 1 + packages/cli/package.json | 3 +- packages/cli/src/adapters/adapter.ts | 82 +- packages/cli/src/adapters/drupal-modules.ts | 315 ++++++++ packages/cli/src/adapters/drupal.ts | 10 +- packages/cli/src/adapters/nuxt-config.ts | 72 ++ packages/cli/src/adapters/nuxt.ts | 84 +- packages/cli/src/cli.ts | 8 +- packages/cli/src/commands/change.ts | 266 ++++++ packages/cli/src/commands/init.ts | 1 + packages/cli/src/commands/menu.ts | 6 +- packages/cli/src/commands/module.ts | 23 +- packages/cli/src/context.ts | 9 + packages/cli/src/engines/engine.ts | 3 + packages/cli/src/engines/none.ts | 1 + packages/cli/src/engines/php.ts | 1 + packages/cli/src/errors.ts | 2 + packages/cli/src/exec.ts | 37 + packages/cli/src/modules/change.ts | 475 +++++++++++ packages/cli/src/modules/entry.ts | 91 ++- packages/cli/src/project.ts | 35 +- packages/cli/src/prompts.ts | 21 +- packages/cli/test/adapters/adapters.test.ts | 12 - .../cli/test/adapters/drupal-modules.test.ts | 424 ++++++++++ .../cli/test/adapters/nuxt-modules.test.ts | 225 ++++++ packages/cli/test/commands/add.test.ts | 764 ++++++++++++++++++ .../cli/test/commands/init-engines.test.ts | 1 + packages/cli/test/commands/init.test.ts | 1 + packages/cli/test/commands/menu.test.ts | 47 +- packages/cli/test/commands/module.test.ts | 2 +- packages/cli/test/engines/engines.test.ts | 13 + packages/cli/test/exec.test.ts | 26 + .../test/fixtures/quickstart-nuxt.config.js | 149 ++++ packages/cli/test/helpers/prompter.ts | 2 + packages/cli/test/helpers/run.ts | 6 + packages/cli/test/modules/entry.test.ts | 99 +++ packages/cli/test/non-interactive.test.ts | 15 +- packages/cli/test/project.test.ts | 55 ++ 45 files changed, 3410 insertions(+), 59 deletions(-) create mode 100644 packages/cli/src/adapters/drupal-modules.ts create mode 100644 packages/cli/src/adapters/nuxt-config.ts create mode 100644 packages/cli/src/commands/change.ts create mode 100644 packages/cli/src/exec.ts create mode 100644 packages/cli/src/modules/change.ts create mode 100644 packages/cli/test/adapters/drupal-modules.test.ts create mode 100644 packages/cli/test/adapters/nuxt-modules.test.ts create mode 100644 packages/cli/test/commands/add.test.ts create mode 100644 packages/cli/test/exec.test.ts create mode 100644 packages/cli/test/fixtures/quickstart-nuxt.config.js 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 ed754f7..9b1780a 100644 --- a/README.md +++ b/README.md @@ -128,6 +128,52 @@ 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 package manager of the part's lock file, 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. +- **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. + +| Option | What it does | +| ------------------------------------------------ | ---------------------------------------------------------------------------------- | +| `--dry-run` | Print every step, with each command line, 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: + +- 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. + +**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. + +**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`. When the site lacks `cweagans/composer-patches`, it allows the plugin and requires it. A patch is skipped when the installed package is at or past the version that has the fix, and when the site already has the same patch. + +**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. Nothing is recorded for that module. + +**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. + +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 ` + +Takes a module out of the `modules` array and uninstalls its package. `drx module remove` is the same command. It takes `--dry-run`, `--yes`, `--module-registry`, `--refresh` and `--json`. + +The backend is left alone unless `--backend` is given. With it, `remove` uninstalls and removes only the Drupal modules that `drx add` required, and only the patches it wrote, which it knows from the record in `drx.config.json`. A Drupal module that another installed Druxt module needs stays. + ### `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. @@ -153,7 +199,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 show modules, and show the project. Adding, removing and configuring a module and managing patches are listed as not available yet. +- Inside one: list, search or show modules, and show the project. 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. @@ -259,6 +305,8 @@ 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. An entry has the package, and for each backend part the Drupal modules `add` required and the patches it wrote. `drx remove --backend` undoes that and nothing else. + 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 @@ -372,6 +420,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 @@ -403,7 +460,11 @@ 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. +- A check that a Drupal module is already enabled. `drush en` is run for each one, and only the modules `drx add` required are recorded as its own. - 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 60af4ad..5efaf1b 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 5f3958b..10c1426 100644 --- a/package-lock.json +++ b/package-lock.json @@ -62,7 +62,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" @@ -72,7 +71,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" @@ -82,7 +80,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" @@ -98,7 +95,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", @@ -5469,7 +5465,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", @@ -6884,7 +6879,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" @@ -7485,6 +7479,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 6242616..fafe93d 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" @@ -42,6 +42,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 0dfb700..2ab56d6 100644 --- a/packages/cli/src/adapters/adapter.ts +++ b/packages/cli/src/adapters/adapter.ts @@ -1,4 +1,4 @@ -import { DrxError } from '../errors.js' +import type { BackendModule } from '../modules/entry.js' import type { Role } from '../parts.js' /** One package a part depends on. */ @@ -33,11 +33,81 @@ 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[] +} + +/** A file of the part to write, with its whole new content. */ +export interface FileEdit { + /** Relative to the part. */ + file: string + content: string + /** What the edit does, as one line. */ + summary: string +} + +/** 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 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 +} + +export interface RemoveRequest { + package?: string + /** What an earlier add did to this part, from the project's record. */ + record?: BackendRecord + /** Backend modules another installed module needs, which must stay. */ + stillNeeded: string[] +} + +/** What an add did to a backend part, kept so a remove undoes that and no more. */ +export interface BackendRecord { + /** The modules it required and enabled, which were not there before. */ + modules: { name: string; package: string }[] + /** The patches it wrote. */ + patches: { package: string; description: string; url: string }[] +} + +/** The steps of a change to one part, in the order to take them. */ +export interface ModuleChange { + steps: ({ run: ToolRun } | { edit: FileEdit })[] + /** 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[] + /** What to keep in the project's record. */ + record?: BackendRecord } -/** 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-modules.ts b/packages/cli/src/adapters/drupal-modules.ts new file mode 100644 index 0000000..919631c --- /dev/null +++ b/packages/cli/src/adapters/drupal-modules.ts @@ -0,0 +1,315 @@ +import { existsSync } from 'node:fs' +import { readFile } from 'node:fs/promises' +import { join } from 'node:path' +import semver from 'semver' +import type { BackendModule } from '../modules/entry.js' +import { isRecord } from '../validate.js' +import { + emptyChange, + type AddRequest, + 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' + +type Json = Record +type Patches = Record> + +interface Manifest { + source: string + json: Json + require: Record + patches: Patches +} + +async function readManifest(dir: string): Promise { + try { + const source = await readFile(join(dir, 'composer.json'), 'utf8') + const json: unknown = JSON.parse(source) + if (!isRecord(json)) return undefined + const extra = isRecord(json.extra) ? json.extra : {} + return { + source, + json, + require: isRecord(json.require) ? json.require : {}, + patches: (isRecord(extra.patches) ? extra.patches : {}) as Patches, + } + } catch { + return undefined + } +} + +/** The manifest as text, with the indent and final newline it had. */ +function write(manifest: Manifest, json: Json): string { + const indent = /^([ \t]+)"/m.exec(manifest.source)?.[1] ?? ' ' + const text = JSON.stringify(json, null, indent) + return manifest.source.endsWith('\n') ? `${text}\n` : text +} + +/** The directory core keeps its modules in, under the web root the site names. */ +function coreModulesDir(dir: string, manifest: Manifest): 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 join( + dir, + typeof webRoot === 'string' ? webRoot : 'web', + 'core', + 'modules' + ) +} + +/** The version of each package Composer has installed. */ +async function installedVersions(dir: string): Promise> { + const versions = 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') { + versions.set(entry.name, String(entry.version)) + } + } + } catch { + // Nothing is installed yet. + } + return versions +} + +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 (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' +} + +/** 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 } = request + if (needs.length === 0) return change + + const manifest = await readManifest(dir) + 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 versions = await installedVersions(dir) + const record: BackendRecord = { modules: [], patches: [] } + const toRequire: string[] = [] + const patches: Patches = structuredClone(manifest.patches) + let repatch = false + + for (const need of needs) { + const pkg = packageOf(need) + const from = origin(need, request, manifest, coreDir) + if (from === 'unknown') { + 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 + } + 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 + ) + record.modules.push({ name: need.name, package: pkg }) + } + } + + 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 + } + const has = versions.get(target) + const fixed = patch.until ? semver.coerce(patch.until) : null + const installed = has ? semver.coerce(has) : null + if (fixed && installed && semver.gte(installed, 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)) { + change.notes.push( + `The patch "${patch.description}" is already in composer.json.` + ) + continue + } + patches[target] = { ...patches[target], [patch.description]: patch.url } + record.patches.push({ + package: target, + description: patch.description, + url: patch.url, + }) + change.notes.push( + `Patch for ${target}: ${patch.description}${patch.issue ? ` (${patch.issue})` : ''}` + ) + // A package that is installed already has to be patched in place. + if (target !== pkg || pkg in manifest.require) 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}`) + } + } + + if (change.problems.length > 0) return change + const composer = (...args: string[]) => + change.steps.push({ run: { tool: 'composer', args } }) + + if (record.patches.length > 0) { + const json = structuredClone(manifest.json) + json.extra = { ...(isRecord(json.extra) ? json.extra : {}), patches } + const hasPlugin = PATCHES_PLUGIN in manifest.require + if (!hasPlugin) { + // Allowed before it is required, or Composer stops to ask. + const config = isRecord(json.config) ? json.config : {} + const allowed = isRecord(config['allow-plugins']) + ? config['allow-plugins'] + : {} + json.config = { + ...config, + 'allow-plugins': { ...allowed, [PATCHES_PLUGIN]: true }, + } + } + const count = record.patches.length + change.steps.push({ + edit: { + file: 'composer.json', + content: write(manifest, json), + summary: `Add ${count} patch${count === 1 ? '' : 'es'} to composer.json`, + }, + }) + if (!hasPlugin) { + composer('require', `${PATCHES_PLUGIN}:${PATCHES_PLUGIN_CONSTRAINT}`) + } + composer('patches-relock') + } + if (toRequire.length > 0) composer('require', ...toRequire) + if (record.patches.length > 0 && repatch) composer('patches-repatch') + change.steps.push({ + run: { + tool: 'drush', + args: ['en', '-y', ...needs.map(({ name }) => name)], + }, + }) + + change.record = record + return change +} + +/** + * The steps that undo what an add did to the part: the modules it required + * and the patches it wrote, and nothing the site's owner put there. + */ +export async function planBackendRemove( + dir: string, + request: RemoveRequest +): Promise { + const change = emptyChange() + const record = request.record + if (!record) return change + + const going = record.modules.filter( + ({ name }) => !request.stillNeeded.includes(name) + ) + for (const { name } of record.modules) { + if (!going.some((module) => module.name === name)) { + change.notes.push(`${name} stays: another installed module needs it.`) + } + } + if (going.length > 0) { + change.steps.push({ + run: { + tool: 'drush', + args: ['pmu', '-y', ...going.map(({ name }) => name)], + }, + }) + } + + // The record does not say which module a patch was for, so while any of + // them stays, every patch does. + const manifest = await readManifest(dir) + let relock = false + if (manifest && going.length === record.modules.length) { + const patches: Patches = structuredClone(manifest.patches) + let removed = 0 + for (const patch of record.patches) { + 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] + removed += 1 + } + if (removed > 0) { + const json = structuredClone(manifest.json) + const extra = { ...(isRecord(json.extra) ? json.extra : {}) } + if (Object.keys(patches).length === 0) delete extra.patches + else extra.patches = patches + json.extra = extra + change.steps.push({ + edit: { + file: 'composer.json', + content: write(manifest, json), + summary: `Remove ${removed} patch${removed === 1 ? '' : 'es'} from composer.json`, + }, + }) + relock = true + } + } + + if (going.length > 0) { + change.steps.push({ + run: { + tool: 'composer', + args: ['remove', ...going.map((module) => module.package)], + }, + }) + } + if (relock) { + change.steps.push({ run: { tool: 'composer', args: ['patches-relock'] } }) + } + return change +} diff --git a/packages/cli/src/adapters/drupal.ts b/packages/cli/src/adapters/drupal.ts index bf42f4f..e114b89 100644 --- a/packages/cli/src/adapters/drupal.ts +++ b/packages/cli/src/adapters/drupal.ts @@ -1,10 +1,7 @@ import { join } from 'node:path' import { isRecord } from '../validate.js' -import { - addModuleNotAvailable, - type KindAdapter, - type PackageVersion, -} from './adapter.js' +import type { KindAdapter, PackageVersion } from './adapter.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. */ @@ -60,5 +57,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..0ecd56a --- /dev/null +++ b/packages/cli/src/adapters/nuxt-config.ts @@ -0,0 +1,72 @@ +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 +} + +/** + * 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' } + 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 04ea20b..24e32c5 100644 --- a/packages/cli/src/adapters/nuxt.ts +++ b/packages/cli/src/adapters/nuxt.ts @@ -1,10 +1,13 @@ import { existsSync } from 'node:fs' +import { readFile } from 'node:fs/promises' import { join } from 'node:path' import { - addModuleNotAvailable, + emptyChange, type KindAdapter, + type ModuleChange, 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( @@ -47,6 +50,82 @@ async function packageVersion( return { name, range, installed } } +/** The package manager of a part, by the lock file it keeps. */ +const MANAGERS = [ + { lock: 'pnpm-lock.yaml', tool: 'pnpm', add: 'add', remove: 'remove' }, + { lock: 'yarn.lock', tool: 'yarn', add: 'add', remove: 'remove' }, + { lock: 'bun.lock', tool: 'bun', add: 'add', remove: 'remove' }, + { lock: 'bun.lockb', tool: 'bun', add: 'add', remove: 'remove' }, +] as const +const NPM = { tool: 'npm', add: 'install', remove: 'uninstall' } as const + +function packageManager(dir: string) { + return MANAGERS.find(({ lock }) => existsSync(join(dir, lock))) ?? NPM +} + +/** + * The steps that add a package to the part and list it in the config, or + * that take both away again. The install comes first, so a failed one leaves + * the config as it was. + */ +async function changeModule( + dir: string, + name: string | undefined, + action: 'add' | 'remove' +): Promise { + const change = emptyChange() + if (!name) return change + + const manager = packageManager(dir) + const dependency = name in (await declared(dir)) + if (action === 'add' && dependency) { + change.notes.push(`${name} is already a dependency in package.json.`) + } else if (action === 'add' || dependency) { + change.steps.push({ + run: { tool: manager.tool, args: [manager[action], name] }, + }) + } + + const file = CONFIG_FILES.find((candidate) => + existsSync(join(dir, candidate)) + ) + if (!file) { + if (action === 'add') { + change.manual.push( + `Add '${name}' to the modules array of the config. No config file was found.` + ) + } + return change + } + + const edit = editModules( + await readFile(join(dir, file), 'utf8'), + name, + action + ) + if (edit.kind === 'changed') { + change.steps.push({ + edit: { + file, + content: edit.content, + summary: + action === 'add' + ? `Add '${name}' to modules in ${file}` + : `Remove '${name}' from modules in ${file}`, + }, + }) + } else if (edit.kind === 'unsafe') { + change.manual.push( + action === 'add' + ? `Add '${name}' to the modules array in ${file}. It could not be edited safely.` + : `Remove '${name}' from the modules array in ${file}. It could not be edited safely.` + ) + } else if (action === 'add') { + change.notes.push(`${name} is already in modules in ${file}.`) + } + return change +} + export const nuxtAdapter: KindAdapter = { kind: 'nuxt', role: 'frontend', @@ -85,5 +164,6 @@ export const nuxtAdapter: KindAdapter = { package: packageVersion, - addModule: addModuleNotAvailable, + addModule: (dir, request) => changeModule(dir, request.package, 'add'), + removeModule: (dir, request) => changeModule(dir, request.package, 'remove'), } diff --git a/packages/cli/src/cli.ts b/packages/cli/src/cli.ts index f91a4f3..8c75ade 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' @@ -34,7 +35,12 @@ 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'), + }), }, }) } diff --git a/packages/cli/src/commands/change.ts b/packages/cli/src/commands/change.ts new file mode 100644 index 0000000..bc1972b --- /dev/null +++ b/packages/cli/src/commands/change.ts @@ -0,0 +1,266 @@ +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, + planAdd, + planData, + planLines, + planRemove, + type ChangeOptions, + type ModulePlan, + type Project, +} from '../modules/change.js' +import type { ModuleEntry } from '../modules/entry.js' +import { createOutput } from '../output.js' +import { CONFIG_FILE, findProjectRoot, loadProjectConfig } 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 + +/** The modules of the registry that the picker offers for an action. */ +async function candidates( + action: Action, + modules: ModuleEntry[], + project: Project, + options: ChangeOptions +): Promise { + const sorted = [...modules].sort((a, b) => a.name.localeCompare(b.name)) + if (action === 'add') { + return sorted.filter((module) => !module.archived && module.npm) + } + const present: ModuleEntry[] = [] + for (const module of sorted) { + const plan = await planRemove(module, project, options) + if (plan.refusals.length === 0) present.push(module) + } + return present +} + +/** + * `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}".` + ) + } + + const loaded = await openModules(context, flags, output) + 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: loaded.modules.some((module) => + module.backend.some((need) => need.core) + ), + registry: loaded.modules, + names: [], + } + + const picked = names.length === 0 + if (picked) { + const offered = await candidates( + action, + loaded.modules, + project, + options + ) + 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(), + })), + }) + } + + const modules = names.map((wanted) => findModule(loaded.modules, wanted)) + options.names = modules.map((module) => module.name) + const plans: ModulePlan[] = [] + for (const module of modules) { + plans.push( + action === 'add' + ? await planAdd(module, project, options) + : await planRemove(module, project, options) + ) + } + + // 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((plan) => + 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.` : ''}` + ) + ) + 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: plan.after, + })) + + if (dryRun) { + output.result( + { ok: true, dryRun: true, modules: data }, + [...shown, '', '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.') + } + } + + await carryOut(plans, project, context, output) + + const left = plans.flatMap((plan) => plan.after) + output.result( + { ok: true, dryRun: false, modules: data }, + [ + ...plans.map((plan) => `${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 87efd34..321bdf0 100644 --- a/packages/cli/src/commands/init.ts +++ b/packages/cli/src/commands/init.ts @@ -486,6 +486,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), }, } diff --git a/packages/cli/src/commands/menu.ts b/packages/cli/src/commands/menu.ts index fa378c8..1c1c505 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: 'Show a module' }, { value: 'info', label: 'Show this project' }, - { 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 2aa8345..49aa53c 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) => @@ -515,13 +518,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 061d3d8..ef7253e 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 } @@ -70,6 +76,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 } @@ -102,6 +110,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 b97e3aa..6b03c40 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' /** diff --git a/packages/cli/src/exec.ts b/packages/cli/src/exec.ts new file mode 100644 index 0000000..d6bc858 --- /dev/null +++ b/packages/cli/src/exec.ts @@ -0,0 +1,37 @@ +import { spawn } from 'node:child_process' + +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 + +/** + * Runs a command with no shell. A tool that cannot be started is a failure + * like any other, with the reason as its output. + */ +export const runTool: RunTool = (command, args, { cwd }) => + new Promise((resolve) => { + let output = '' + const child = spawn(command, args, { + cwd, + stdio: ['ignore', 'pipe', 'pipe'], + shell: process.platform === 'win32', + }) + 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 })) + }) diff --git a/packages/cli/src/modules/change.ts b/packages/cli/src/modules/change.ts new file mode 100644 index 0000000..d5d672a --- /dev/null +++ b/packages/cli/src/modules/change.ts @@ -0,0 +1,475 @@ +import { existsSync } from 'node:fs' +import { mkdir, writeFile } from 'node:fs/promises' +import { dirname, join } from 'node:path' +import { adapterFor, type KindAdapter } from '../adapters/index.js' +import type { BackendRecord, ModuleChange } from '../adapters/adapter.js' +import type { CliContext } from '../context.js' +import { engineFor } from '../engines/index.js' +import { DrxError } from '../errors.js' +import type { Output } from '../output.js' +import type { Part } from '../parts.js' +import { + 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. */ +export type PlannedStep = + | { + type: 'run' + command: string + args: string[] + cwd: string + display: string + } + | { type: 'edit'; file: string; content: string; display: string } + +/** 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[] } + record?: BackendRecord +} + +/** 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 to keep, or to drop when it is undefined on a removal. */ + record?: ModuleRecord +} + +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[] +} + +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 }] + : [] + }) +} + +const pluralPatches = (count: number) => + `${count} patch${count === 1 ? '' : 'es'}` + +/** 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): PlannedStep => + 'run' in step + ? { + type: 'run', + command: step.run.tool, + args: step.run.args, + cwd: at.dir, + display: [step.run.tool, ...step.run.args].join(' '), + } + : { + type: 'edit', + file: join(at.dir, step.edit.file), + content: step.edit.content, + display: step.edit.summary, + } + ), + } +} + +/** + * 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): PlannedStep => { + if ('edit' in step) { + return { + type: 'edit', + file: join(at.dir, step.edit.file), + content: step.edit.content, + display: step.edit.summary, + } + } + const line = engine.run(part, step.run.tool, step.run.args) + return { + type: 'run', + command: line.command, + args: line.args, + cwd: join(project.root, line.cwd), + display: [line.command, ...line.args].join(' '), + } + }), + ...(change.record ? { record: change.record } : {}), + } +} + +/** 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: [], + } + 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 + } + + 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: module.npm, + needs: [], + patches: options.patches, + registryStatesCore: options.registryStatesCore, + }) + absorb(plan, change) + plan.parts.push(frontendPlan(at, change)) + } + + const record: ModuleRecord = { + name: module.name, + package: module.npm, + backend: [], + } + for (const at of located(project, 'backend')) { + const needs = module.backend.filter((need) => need.kind === at.part.kind) + if (needs.length === 0) continue + const change = await at.adapter.addModule(at.dir, { + needs, + patches: options.patches, + registryStatesCore: options.registryStatesCore, + }) + const part = backendPlan(project, at, change) + // What is left by hand: first the commands for a backend that is + // elsewhere, then the setup the module needs wherever it runs. + plan.after.push(...elsewhereLines(part)) + absorb(plan, change) + plan.parts.push(part) + const done = part.record + if (done && done.modules.length + done.patches.length > 0) { + record.backend.push({ path: at.part.path, ...done }) + } + } + plan.record = record + return plan +} + +/** True when the project has the package of a module in a frontend part. */ +async function hasPackage(project: Project, name: string): Promise { + for (const at of located(project, 'frontend')) { + if (await at.adapter.package(at.dir, name)) return true + } + return false +} + +/** Everything taking one module out of the project takes. */ +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: [], + } + const recorded = project.config.modules?.find( + (entry) => entry.name === module.name + ) + const present = module.npm ? await hasPackage(project, module.npm) : false + if (!present && !recorded) { + plan.refusals.push({ + reason: `${module.npm ?? module.name} is not in this project.`, + forceable: false, + }) + return plan + } + + for (const at of located(project, 'frontend')) { + const change = await at.adapter.removeModule(at.dir, { + ...(module.npm ? { package: module.npm } : {}), + stillNeeded: [], + }) + absorb(plan, change) + plan.parts.push(frontendPlan(at, change)) + } + + const backend = recorded?.backend ?? [] + if (backend.length === 0) return plan + if (!options.backend) { + for (const entry of 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. + if (recorded) plan.record = recorded + return plan + } + + // A backend module stays while any other module in the project needs it. + const stillNeeded = new Set() + for (const other of options.registry) { + if (options.names.includes(other.name) || !other.npm) continue + const kept = + (await hasPackage(project, other.npm)) || + project.config.modules?.some((entry) => entry.name === other.name) + if (kept) for (const need of other.backend) stillNeeded.add(need.name) + } + for (const at of located(project, 'backend')) { + const entry = backend.find(({ path }) => path === at.part.path) + if (!entry) continue + const change = await at.adapter.removeModule(at.dir, { + record: { modules: entry.modules, patches: entry.patches }, + stillNeeded: [...stillNeeded], + }) + const part = backendPlan(project, at, change) + plan.after.push(...elsewhereLines(part)) + absorb(plan, change) + plan.parts.push(part) + } + return plan +} + +/** 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 }] + : []), + ]) +} + +/** + * Carries out the plans in order and keeps the project's record in step. + * The first tool that fails stops everything: its output is shown, with what + * had been done by then and what had not. + */ +export async function carryOut( + plans: ModulePlan[], + project: Project, + context: CliContext, + output: Output +): Promise { + const all = plans.flatMap((plan) => + plan.parts.flatMap((part) => + part.steps.map((step) => ({ + step, + label: `${part.path}/: ${step.display}`, + path: part.path, + })) + ) + ) + let done = 0 + let config = project.config + + for (const plan of plans) { + for (const part of plan.parts) { + for (const step of part.steps) { + if (step.type === 'edit') { + await mkdir(dirname(step.file), { recursive: true }) + await writeFile(step.file, step.content) + output.did(`${part.path}/: ${step.display}`) + } else { + output.note(`${part.path}/: ${step.display}`) + const result = await context.exec(step.command, step.args, { + cwd: step.cwd, + }) + if (result.code !== 0) { + const list = (title: string, labels: string[]) => + labels.length > 0 + ? [title, ...labels.map((label) => ` ${label}`)] + : [] + throw new DrxError( + 'step-failed', + [ + `${step.display} failed in ${part.path}/ with exit code ${result.code}.`, + result.output.trimEnd(), + ...list( + 'Done:', + all.slice(0, done).map(({ label }) => label) + ), + ...list( + 'Not done:', + all.slice(done).map(({ label }) => label) + ), + ] + .filter((line) => line !== '') + .join('\n') + ) + } + } + done += 1 + } + } + + // The record is written once the module is wholly done, so a remove + // never undoes something an add did not finish. + const others = (config.modules ?? []).filter( + (entry) => entry.name !== plan.module.name + ) + const modules = plan.record ? [...others, plan.record] : others + const rest: ProjectConfig = { ...config } + delete rest.modules + config = modules.length > 0 ? { ...rest, modules } : rest + await writeProjectConfig(project.root, config) + } +} diff --git a/packages/cli/src/modules/entry.ts b/packages/cli/src/modules/entry.ts index 25ae5df..1fe91bd 100644 --- a/packages/cli/src/modules/entry.ts +++ b/packages/cli/src/modules/entry.ts @@ -1,6 +1,6 @@ import { kindsWithRole } from '../adapters/index.js' import { DrxError } from '../errors.js' -import { isNonEmptyString, isRecord } from '../validate.js' +import { isHttpUrl, isNonEmptyString, isRecord } from '../validate.js' /** The registry format this version reads. */ export const MODULE_SCHEMA_VERSION = 1 @@ -11,9 +11,31 @@ export interface BackendModule { /** The machine name of the module. */ name: string label: string - /** True when the backend ships the module itself. */ + /** True when the registry says the backend ships the module itself. */ 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 } /** @@ -68,6 +90,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 @@ -90,6 +176,7 @@ function backendModules(raw: Raw, at: string): BackendModule[] { label: requiredString(item, 'label', here), core: optionalBoolean(item, 'core', here), ...(url === undefined ? {} : { url }), + ...additions(item, here), }) } } diff --git a/packages/cli/src/project.ts b/packages/cli/src/project.ts index d91ec5f..8a81a14 100644 --- a/packages/cli/src/project.ts +++ b/packages/cli/src/project.ts @@ -3,10 +3,11 @@ 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 } from './adapters/adapter.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, isRecord } from './validate.js' const nodeRequire = createRequire(import.meta.url) @@ -27,6 +28,18 @@ 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. */ +export interface ModuleRecord { + /** The name of the module in the registry. */ + name: string + /** Its frontend package. */ + package: string + /** What was done to each backend part, by the part's path. */ + backend: ({ path: string } & BackendRecord)[] } export async function writeProjectConfig( @@ -58,7 +71,24 @@ 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` + } + } + return undefined } /** Reads and checks the config file of the project rooted at `root`. */ @@ -98,5 +128,6 @@ 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 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 b24065f..c4e92a7 100644 --- a/packages/cli/test/adapters/adapters.test.ts +++ b/packages/cli/test/adapters/adapters.test.ts @@ -75,12 +75,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', () => { @@ -138,12 +132,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..d7d4082 --- /dev/null +++ b/packages/cli/test/adapters/drupal-modules.test.ts @@ -0,0 +1,424 @@ +import { afterEach, describe, expect, test } from 'vitest' +import { adapterFor } from '../../src/adapters/index.js' +import type { AddRequest, 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, + core: false, + ...extra, +}) + +/** 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 +} + +const add = ( + dir: string, + needs: BackendModule[], + options: Partial = {} +) => + drupal.addModule(dir, { + needs, + patches: true, + registryStatesCore: true, + ...options, + }) + +const runs = (change: ModuleChange) => + change.steps.flatMap((step) => + 'run' in step ? [`${step.run.tool} ${step.run.args.join(' ')}`] : [] + ) +const edit = (change: ModuleChange) => + change.steps.flatMap((step) => ('edit' in step ? [step.edit] : []))[0] + +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 en -y decoupled_router', + ]) + expect(change.record).toEqual({ + modules: [ + { name: 'decoupled_router', package: 'drupal/decoupled_router' }, + ], + 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']) + expect(change.record).toEqual({ modules: [], 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 en -y menu_items views', + ]) + expect(change.record?.modules).toEqual([ + { name: 'menu_items', package: 'drupal/jsonapi_menu_items' }, + ]) + }) + + test('does not require a package the site has, and does not record it', 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([]) + }) + + 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 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') + expect(runs(change)).toEqual([ + `composer require ${PLUGIN}:^2.0@beta`, + 'composer patches-relock', + 'composer require drupal/decoupled_router', + 'composer patches-repatch', + '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', + }, + { + package: 'drupal/core', + description: 'Fix core', + url: 'https://example.com/mr/9.diff', + }, + ]) + }) + + 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', + }, + }, + }, + }) + 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.' + ) + }) + + 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 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('taking backend modules out again', () => { + const record = { + modules: [ + { name: 'decoupled_router', package: 'drupal/decoupled_router' }, + { name: 'jsonapi_menu_items', package: 'drupal/jsonapi_menu_items' }, + ], + patches: [ + { + package: 'drupal/decoupled_router', + description: 'Fix the redirect loop', + url: 'https://example.com/mr/12.diff', + }, + ], + } + const carrying = () => + site({ + extra: { + patches: { + 'drupal/decoupled_router': { + 'Fix the redirect loop': 'https://example.com/mr/12.diff', + 'Their own': 'patches/own.patch', + }, + }, + }, + }) + + test('uninstalls and removes what the record says was added', async () => { + const change = await drupal.removeModule(carrying(), { + record, + stillNeeded: [], + }) + expect(runs(change)).toEqual([ + 'drush pmu -y decoupled_router jsonapi_menu_items', + 'composer remove drupal/decoupled_router drupal/jsonapi_menu_items', + 'composer patches-relock', + ]) + 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') + }) + + test('keeps a module something else still needs', async () => { + const change = await drupal.removeModule(carrying(), { + record, + stillNeeded: ['decoupled_router'], + }) + expect(runs(change)).toEqual([ + 'drush pmu -y jsonapi_menu_items', + 'composer remove drupal/jsonapi_menu_items', + ]) + expect(edit(change)).toBeUndefined() + expect(change.notes).toContain( + 'decoupled_router stays: another installed module needs it.' + ) + }) + + 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 drupal.removeModule(dir, { record, stillNeeded: [] }) + expect(JSON.parse(edit(change)?.content ?? '{}').extra).toEqual({}) + }) + + test('does nothing with no record', async () => { + const change = await drupal.removeModule(carrying(), { stillNeeded: [] }) + 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..1b7c9d4 --- /dev/null +++ b/packages/cli/test/adapters/nuxt-modules.test.ts @@ -0,0 +1,225 @@ +import { readFileSync } from 'node:fs' +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'], +}) +` + +const add = (dir: string, name = 'druxt-breadcrumb') => + nuxt.addModule(dir, { + package: name, + needs: [], + patches: true, + registryStatesCore: false, + }) +const remove = (dir: string, name = 'druxt-breadcrumb') => + nuxt.removeModule(dir, { package: name, stillNeeded: [] }) + +const runs = (change: ModuleChange) => + change.steps.flatMap((step) => ('run' in step ? [step.run] : [])) +const edits = (change: ModuleChange) => + change.steps.flatMap((step) => ('edit' in step ? [step.edit] : [])) + +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'], + ], + [ + '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 }]) + }) +}) + +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 + expect(content).not.toContain('druxt-auth') + expect(content).toContain("'druxt-site',") + }) +}) + +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.", + ]) + }) +}) + +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([]) + }) +}) diff --git a/packages/cli/test/commands/add.test.ts b/packages/cli/test/commands/add.test.ts new file mode 100644 index 0000000..f4abbac --- /dev/null +++ b/packages/cli/test/commands/add.test.ts @@ -0,0 +1,764 @@ +import { createHash } from 'node:crypto' +import { 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 { 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', +} + +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'), + ]) + ) +} + +/** + * 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. + */ +function tools(root: string, fail?: { on: string; output: string }) { + const calls: string[] = [] + const exec: CliContext['exec'] = async (command, args, { cwd }) => { + const line = `${relative(root, cwd)}$ ${command} ${args.join(' ')}` + calls.push(line) + if (fail && line.includes(fail.on)) return { code: 1, output: fail.output } + if (command === 'npm') { + const file = join(cwd, 'package.json') + const manifest = JSON.parse(readFileSync(file, 'utf8')) + if (args[0] === 'install') + manifest.dependencies[args[1] as string] = '^1.0.0' + else delete manifest.dependencies[args[1] as string] + writeFileSync(file, JSON.stringify(manifest)) + } + return { code: 0, output: '' } satisfies ToolResult + } + return { calls, exec } +} + +const never: CliContext['exec'] = async (command, args) => { + throw new Error(`A command was run: ${command} ${args.join(' ')}`) +} + +const drx = ( + argv: string[], + cwd: string, + overrides: Partial = {} +) => run(argv, { cwd, defaultModuleRegistry: url, exec: never, ...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 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 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', + backend: [ + { + path: 'drupal', + modules: [ + { name: 'decoupled_router', package: 'drupal/decoupled_router' }, + ], + patches: [ + { + package: 'drupal/decoupled_router', + description: PATCH.description, + url: PATCH.url, + }, + ], + }, + ], + }, + ]) + }) + + 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') + ) + }) +}) + +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 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 en -y decoupled_router', + ].join('\n') + ) + expect(config(root).modules).toBeUndefined() + }) +}) + +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 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 }, + never + ) + expect(result.code).toBe(1) + expect(result.stderr).toContain('Error: Cancelled. Nothing was changed.') + expect(snapshot(root)).toEqual(before) + }) +}) + +describe('drx remove', () => { + /** 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) + 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 drupal/decoupled_router', + 'drupal$ ddev composer patches-relock', + ]) + const composer = JSON.parse( + readFileSync(join(root, 'drupal/composer.json'), 'utf8') + ) + expect(composer.extra.patches).toBeUndefined() + expect(config(root).modules).toBeUndefined() + expect(result.stdout).toBe('Removed breadcrumb.\n') + }) + + 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) + const result = await drx(['remove', 'breadcrumb', '--backend'], root, { + exec, + }) + expect(calls).toEqual(['nuxt$ npm uninstall druxt-breadcrumb']) + expect(result.stderr).toContain( + 'decoupled_router stays: another installed module needs it.' + ) + }) + + test('touches no backend module that drx add did not put there', async () => { + const root = project() + const file = join(root, 'nuxt/package.json') + const manifest = JSON.parse(readFileSync(file, 'utf8')) + manifest.dependencies['druxt-blocks'] = '^0.25.0' + writeFileSync(file, JSON.stringify(manifest)) + + const { calls, exec } = tools(root) + const result = await drx( + ['module', 'remove', 'blocks', '--backend'], + root, + { exec } + ) + expect(result.code).toBe(0) + expect(calls).toEqual(['nuxt$ npm uninstall druxt-blocks']) + }) + + 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 + ) + 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 drupal/decoupled_router', + ' run ddev composer patches-relock', + '', + '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.' + ) + }) +}) diff --git a/packages/cli/test/commands/init-engines.test.ts b/packages/cli/test/commands/init-engines.test.ts index 36f75e4..8123f0b 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, diff --git a/packages/cli/test/commands/init.test.ts b/packages/cli/test/commands/init.test.ts index 5081dd4..f3a7565 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 15dcccf..f74be2b 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: 'Show a module' }, { value: 'info', label: 'Show this project' }, - { 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 f3f9e47..6b77dc6 100644 --- a/packages/cli/test/commands/module.test.ts +++ b/packages/cli/test/commands/module.test.ts @@ -431,7 +431,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..a6e82db --- /dev/null +++ b/packages/cli/test/exec.test.ts @@ -0,0 +1,26 @@ +import { afterEach, describe, expect, test } from 'vitest' +import { runTool } from '../src/exec.js' +import { cleanTmp, tmp } 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') + }) +}) 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 0cc4349..a826c96 100644 --- a/packages/cli/test/helpers/run.ts +++ b/packages/cli/test/helpers/run.ts @@ -28,6 +28,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 9fa7988..75dc0db 100644 --- a/packages/cli/test/modules/entry.test.ts +++ b/packages/cli/test/modules/entry.test.ts @@ -127,4 +127,103 @@ 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', + core: false, + 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', + ], + ])('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}.` + ) + }) }) diff --git a/packages/cli/test/non-interactive.test.ts b/packages/cli/test/non-interactive.test.ts index 8fa9e68..c317a47 100644 --- a/packages/cli/test/non-interactive.test.ts +++ b/packages/cli/test/non-interactive.test.ts @@ -67,8 +67,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, diff --git a/packages/cli/test/project.test.ts b/packages/cli/test/project.test.ts index 1de3c09..fc13e82 100644 --- a/packages/cli/test/project.test.ts +++ b/packages/cli/test/project.test.ts @@ -77,6 +77,61 @@ 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', + backend: [ + { + path: 'drupal', + modules: [ + { + name: 'decoupled_router', + package: 'drupal/decoupled_router', + }, + ], + patches: [ + { + package: 'drupal/core', + description: 'Fix', + url: 'https://example.com/1.diff', + }, + ], + }, + ], + }, + ], + } + await writeProjectConfig(root, recorded) + expect(await loadProjectConfig(root)).toEqual(recorded) + }) + + 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', + ], + ])('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('reads a file again after it has changed', async () => { const root = tmp() await writeProjectConfig(root, config) From 947919b8ac5ed79a300dd3d506c1ffdcf4e7a279 Mon Sep 17 00:00:00 2001 From: Stuart Clark Date: Wed, 18 Nov 2026 21:56:21 +0000 Subject: [PATCH 2/4] fix(cli): make drx remove undo only what drx add recorded The record in `drx.config.json` now says what `drx add` did to each part, and `drx remove` works from it alone. - `add` records, per frontend part, whether it installed the package and whether it listed it in the config, and per backend part which modules it enabled, which requirements it added and which patches it wrote. It asks Drush which modules are enabled before it plans, and again once it has run, since Drupal enables a module's dependencies with it. A second `add` adds to the record and takes nothing away. - `remove` leaves a package, a config entry or an enabled module that was there before `add`. A module with no record is refused with exit code 1, whether the project lacks it or the user installed it. A record from before this change still reads, and its frontend is left alone with the lines that take it out. - `remove --backend` asks Drush what uninstalling each module would take with it, with `pm:uninstall --simulate`, and leaves a module that another enabled module depends on, naming that module. When Drush cannot answer, nothing is uninstalled and the command is printed under "Left to do". - A module another Druxt module still needs moves to that module's record. Whatever stays in place keeps a record. - Requirements come out with `composer remove --no-update-with-dependencies`, which leaves the packages they depended on at their versions. One that another package still requires only leaves `composer.json`, since Composer's remove fails on it. A package holding a module that is still enabled stays. - A patch is applied in place whenever its package is installed, also when another package brought it in. Taking a patch out reinstalls a package that stays. - A patch whose URL is not https is refused before anything is written. Composer refused it later, with the patch half written. - With a backend that is not run from here, a module the registry does not place as core or contributed is no longer refused. Its lines are printed, with a note that a core module needs the enable line only. - A dry run prints what is left to the user, such as the line for a config it cannot edit. - Taking an entry out of the config leaves the rest of the file as it was written. An entry with options used to reprint the whole array. - The JSON of a failed step has `failed`, `done` and `notDone` fields, and the README lists the `refused` and `step-failed` codes. --- README.md | 81 ++- packages/cli/src/adapters/adapter.ts | 64 +- packages/cli/src/adapters/drupal-modules.ts | 394 +++++++++-- packages/cli/src/adapters/nuxt-config.ts | 65 ++ packages/cli/src/adapters/nuxt.ts | 125 +++- packages/cli/src/cli.ts | 8 +- packages/cli/src/commands/change.ts | 49 +- packages/cli/src/errors.ts | 12 +- packages/cli/src/modules/change.ts | 320 +++++++-- packages/cli/src/project.ts | 58 +- .../cli/test/adapters/drupal-modules.test.ts | 487 ++++++++++++- .../cli/test/adapters/nuxt-modules.test.ts | 72 +- packages/cli/test/commands/add.test.ts | 643 +++++++++++++++++- packages/cli/test/project.test.ts | 61 ++ 14 files changed, 2166 insertions(+), 273 deletions(-) diff --git a/README.md b/README.md index ee1f92e..05222fa 100644 --- a/README.md +++ b/README.md @@ -142,37 +142,55 @@ For each module it does two things: - **Frontend.** It installs the package with the package manager of the part's lock file, 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. - **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. -| Option | What it does | -| ------------------------------------------------ | ---------------------------------------------------------------------------------- | -| `--dry-run` | Print every step, with each command line, 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` | +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: - 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. -**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. +**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`. When the site lacks `cweagans/composer-patches`, it allows the plugin and requires it. A patch is skipped when the installed package is at or past the version that has the fix, and when the site already has the same patch. +**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. A patch is skipped when the installed package is at or past the version that has the fix, and when the site already has the same patch. **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. Nothing is recorded for that module. +**When a tool fails.** The run stops there. The tool's output is printed, then what was done and what was not. Nothing is recorded for that module. 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. +**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 ` -Takes a module out of the `modules` array and uninstalls its package. `drx module remove` is the same command. It takes `--dry-run`, `--yes`, `--module-registry`, `--refresh` and `--json`. +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 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. +- 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: -The backend is left alone unless `--backend` is given. With it, `remove` uninstalls and removes only the Drupal modules that `drx add` required, and only the patches it wrote, which it knows from the record in `drx.config.json`. A Drupal module that another installed Druxt module needs stays. +- 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. +- 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. +- 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` @@ -270,7 +288,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 @@ -305,7 +323,39 @@ 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. An entry has the package, and for each backend part the Drupal modules `add` required and the patches it wrote. `drx remove --backend` undoes that and nothing else. +`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 | +| `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 | + +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. @@ -470,7 +520,6 @@ The copy is kept in `~/.cache/drx`, or under `XDG_CACHE_HOME` when that is set. - 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. -- A check that a Drupal module is already enabled. `drush en` is run for each one, and only the modules `drx add` required are recorded as its own. - 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/packages/cli/src/adapters/adapter.ts b/packages/cli/src/adapters/adapter.ts index 2ab56d6..6cc11b4 100644 --- a/packages/cli/src/adapters/adapter.ts +++ b/packages/cli/src/adapters/adapter.ts @@ -1,3 +1,4 @@ +import type { ToolResult } from '../exec.js' import type { BackendModule } from '../modules/entry.js' import type { Role } from '../parts.js' @@ -48,6 +49,12 @@ export interface ToolRun { 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 file of the part to write, with its whole new content. */ export interface FileEdit { /** Relative to the part. */ @@ -67,22 +74,52 @@ export interface AddRequest { 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 - /** What an earlier add did to this part, from the project's record. */ + /** + * 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 - /** Backend modules another installed module needs, which must stay. */ - stillNeeded: string[] + 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 } /** What an add did to a backend part, kept so a remove undoes that and no more. */ export interface BackendRecord { - /** The modules it required and enabled, which were not there before. */ - modules: { name: string; package: string }[] - /** The patches it wrote. */ - patches: { package: string; description: string; url: string }[] + 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 + }[] } /** The steps of a change to one part, in the order to take them. */ @@ -97,8 +134,19 @@ export interface ModuleChange { manual: string[] /** What is left to do once the change is made. */ after: string[] - /** What to keep in the project's record. */ + /** 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, and + * gives the record to keep in place of `record`. A backend may enable more + * than it was asked to, and only then can that be seen. + */ + settle?: () => Promise } export function emptyChange(): ModuleChange { diff --git a/packages/cli/src/adapters/drupal-modules.ts b/packages/cli/src/adapters/drupal-modules.ts index 919631c..8166535 100644 --- a/packages/cli/src/adapters/drupal-modules.ts +++ b/packages/cli/src/adapters/drupal-modules.ts @@ -1,12 +1,13 @@ import { existsSync } from 'node:fs' import { readFile } from 'node:fs/promises' -import { join } from 'node:path' +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, @@ -50,23 +51,30 @@ function write(manifest: Manifest, json: Json): string { return manifest.source.endsWith('\n') ? `${text}\n` : text } -/** The directory core keeps its modules in, under the web root the site names. */ -function coreModulesDir(dir: string, manifest: Manifest): string { - const extra = isRecord(manifest.json.extra) ? manifest.json.extra : {} +/** 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 join( - dir, - typeof webRoot === 'string' ? webRoot : 'web', - 'core', - 'modules' - ) + return resolve(dir, typeof webRoot === 'string' ? webRoot : 'web') } -/** The version of each package Composer has installed. */ -async function installedVersions(dir: string): Promise> { - const versions = new Map() +/** 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 +} + +/** 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') @@ -74,13 +82,73 @@ async function installedVersions(dir: string): Promise> { const packages = isRecord(installed) ? installed.packages : undefined for (const entry of Array.isArray(packages) ? packages : []) { if (isRecord(entry) && typeof entry.name === 'string') { - versions.set(entry.name, String(entry.version)) + const path = entry['install-path'] + found.set(entry.name, { + version: String(entry.version), + requires: Object.keys(isRecord(entry.require) ? entry.require : {}), + // 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 versions + 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', name, '--simulate']) + 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) => @@ -102,22 +170,32 @@ function origin( 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 } = request + const { needs, ask } = request if (needs.length === 0) return change - const manifest = await readManifest(dir) + // 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 : { source: '{}\n', json: {}, require: {}, patches: {} }) if (!manifest) { change.problems.push( `There is no composer.json to add ${needs.map(({ name }) => name).join(', ')} to.` @@ -126,21 +204,30 @@ export async function planBackendAdd( } const coreDir = coreModulesDir(dir, manifest) - const versions = await installedVersions(dir) + const installed = await installedPackages(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 for (const need of needs) { const pkg = packageOf(need) - const from = origin(need, request, manifest, coreDir) + let from = origin(need, request, manifest, coreDir) if (from === 'unknown') { - 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 + 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.`) @@ -148,10 +235,24 @@ export async function planBackendAdd( toRequire.push( need.composer?.constraint ? `${pkg}:${need.composer.constraint}` : pkg ) - record.modules.push({ name: need.name, package: 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) { @@ -160,10 +261,16 @@ export async function planBackendAdd( ) continue } - const has = versions.get(target) + 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 installed = has ? semver.coerce(has) : null - if (fixed && installed && semver.gte(installed, fixed)) { + 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}.` ) @@ -180,12 +287,15 @@ export async function planBackendAdd( 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 already has to be patched in place. - if (target !== pkg || pkg in manifest.require) repatch = true + // 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 ?? []) { @@ -196,6 +306,16 @@ export async function planBackendAdd( } 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.` + ) + } const composer = (...args: string[]) => change.steps.push({ run: { tool: 'composer', args } }) @@ -229,87 +349,221 @@ export async function planBackendAdd( } if (toRequire.length > 0) composer('require', ...toRequire) if (record.patches.length > 0 && repatch) composer('patches-repatch') - change.steps.push({ - run: { - tool: 'drush', - args: ['en', '-y', ...needs.map(({ name }) => name)], - }, - }) + if (toEnable.length > 0) { + change.steps.push({ + run: { tool: 'drush', args: ['en', '-y', ...toEnable] }, + }) + } change.record = record + if (ask && enabled) { + // Drush enables what a module depends on along with it. Those modules + // were enabled by this add too, and are seen only once it has run. + change.settle = async () => { + const after = await enabledModules(ask) + if (!after) return record + const came = [...after.keys()].filter((name) => !enabled.has(name)) + const modules = record.modules + .map((module) => ({ ...module, enabled: came.includes(module.name) })) + .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 { modules, patches: record.patches } + } + } return change } /** - * The steps that undo what an add did to the part: the modules it required - * and the patches it wrote, and nothing the site's owner put there. + * 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 = request.record + const { record, ask } = request if (!record) return change - const going = record.modules.filter( - ({ name }) => !request.stillNeeded.includes(name) - ) - for (const { name } of record.modules) { - if (!going.some((module) => module.name === name)) { - change.notes.push(`${name} stays: another installed module needs it.`) + 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 + if (found === 'absent') { + change.notes.push(`${name} is not enabled, so it is not uninstalled.`) + } else if (found) { + dependents.set(name, found) + } else { + stays.add(name) + change.manual.push( + `The backend could not say what depends on ${name}, so it was left enabled. Once nothing does: drush pm:uninstall ${name}${required && pkg ? `, then composer remove ${pkg}` : ''}` + ) } } - if (going.length > 0) { - change.steps.push({ - run: { - tool: 'drush', - args: ['pmu', '-y', ...going.map(({ name }) => name)], - }, - }) + // 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 + } } - // The record does not say which module a patch was for, so while any of - // them stays, every patch does. + // 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) - let relock = false - if (manifest && going.length === record.modules.length) { + 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) + ) + let listed: Map | undefined | null = null + const enabledNow = async () => { + if (listed === null) listed = ask ? await enabledModules(ask) : undefined + return listed + } + const unowned = removing.filter( + (module) => !module.enabled && !heldByAnother(module.package as string) + ) + for (const { name, package: pkg } of unowned) { + const enabled = await enabledNow() + if (enabled && !enabled.has(name)) 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() + if (manifest) { const patches: Patches = structuredClone(manifest.patches) - let removed = 0 - for (const patch of record.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] - removed += 1 + unpatched.add(patch.package) } - if (removed > 0) { + if (unpatched.size > 0) { const json = structuredClone(manifest.json) const extra = { ...(isRecord(json.extra) ? json.extra : {}) } if (Object.keys(patches).length === 0) delete extra.patches else extra.patches = patches json.extra = extra + const count = leaving.filter((patch) => + unpatched.has(patch.package) + ).length change.steps.push({ edit: { file: 'composer.json', content: write(manifest, json), - summary: `Remove ${removed} patch${removed === 1 ? '' : 'es'} from composer.json`, + summary: `Remove ${count} patch${count === 1 ? '' : 'es'} from composer.json`, }, }) - relock = true } } - if (going.length > 0) { - change.steps.push({ - run: { - tool: 'composer', - args: ['remove', ...going.map((module) => module.package)], - }, - }) + const composer = (...args: string[]) => + change.steps.push({ run: { tool: '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. + if (kept.length > 0) composer('remove', '--no-update', ...kept) + if (free.length > 0) { + composer('remove', '--no-update-with-dependencies', ...free) + } else if (kept.length > 0) { + composer('update', '--lock') } - if (relock) { - change.steps.push({ run: { tool: 'composer', args: ['patches-relock'] } }) + 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) + } + + 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)), } + if (left.modules.length + left.patches.length > 0) change.record = left return change } diff --git a/packages/cli/src/adapters/nuxt-config.ts b/packages/cli/src/adapters/nuxt-config.ts index 0ecd56a..cb422b4 100644 --- a/packages/cli/src/adapters/nuxt-config.ts +++ b/packages/cli/src/adapters/nuxt-config.ts @@ -24,6 +24,65 @@ function entryName(entry: unknown): string | 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. @@ -55,6 +114,12 @@ export function editModules( 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) } } diff --git a/packages/cli/src/adapters/nuxt.ts b/packages/cli/src/adapters/nuxt.ts index 2ac5c69..55b4ebd 100644 --- a/packages/cli/src/adapters/nuxt.ts +++ b/packages/cli/src/adapters/nuxt.ts @@ -5,6 +5,7 @@ import { emptyChange, type KindAdapter, type ModuleChange, + type PackageRecord, type PackageVersion, } from './adapter.js' import { editModules } from './nuxt-config.js' @@ -75,65 +76,122 @@ function packageManager(dir: string) { return MANAGERS.find(({ lock }) => existsSync(join(dir, lock))) ?? NPM } +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, or - * that take both away again. The install comes first, so a failed one leaves - * the config as it was. + * 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 changeModule( +async function addModule( dir: string, - name: string | undefined, - action: 'add' | 'remove' + name: string | undefined ): Promise { const change = emptyChange() if (!name) return change + const did: PackageRecord = { installed: false, listed: false } + change.did = did const manager = packageManager(dir) - const dependency = name in (await declared(dir)) - if (action === 'add' && dependency) { + if (name in (await declared(dir))) { change.notes.push(`${name} is already a dependency in package.json.`) - } else if (action === 'add' || dependency) { + } else { change.steps.push({ - run: { tool: manager.tool, args: [manager[action], name] }, + run: { tool: manager.tool, args: [manager.add, name] }, }) + did.installed = true } - const file = CONFIG_FILES.find((candidate) => - existsSync(join(dir, candidate)) - ) + const file = configFile(dir) if (!file) { - if (action === 'add') { + change.manual.push( + `Add '${name}' to the modules array of the config. No config file was found.` + ) + return change + } + const edit = editModules(await readFile(join(dir, file), 'utf8'), name, 'add') + if (edit.kind === 'changed') { + change.steps.push({ + edit: { + file, + content: edit.content, + summary: `Add '${name}' to modules in ${file}`, + }, + }) + 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.` + ) + } 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. + */ +async function removeModule( + dir: string, + name: string | undefined, + did: PackageRecord | undefined +): Promise { + const change = emptyChange() + if (!name) return change + + const manager = packageManager(dir) + 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( - `Add '${name}' to the modules array of the config. No config file was found.` + `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 } - const edit = editModules( - await readFile(join(dir, file), 'utf8'), - name, - action - ) - if (edit.kind === 'changed') { + if (dependency) { + if (did.installed) { + change.steps.push({ + run: { tool: manager.tool, args: [manager.remove, name] }, + }) + } else { + change.notes.push( + `${name} was in package.json before drx add, so it stays.` + ) + } + } + if (!file || !edit || !listed) return change + if (!did.listed) { + 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, content: edit.content, - summary: - action === 'add' - ? `Add '${name}' to modules in ${file}` - : `Remove '${name}' from modules in ${file}`, + summary: `Remove '${name}' from modules in ${file}`, }, }) - } else if (edit.kind === 'unsafe') { + } else { change.manual.push( - action === 'add' - ? `Add '${name}' to the modules array in ${file}. It could not be edited safely.` - : `Remove '${name}' from the modules array in ${file}. It could not be edited safely.` + `Remove '${name}' from the modules array in ${file}. It could not be edited safely.` ) - } else if (action === 'add') { - change.notes.push(`${name} is already in modules in ${file}.`) } return change } @@ -176,6 +234,7 @@ export const nuxtAdapter: KindAdapter = { package: packageVersion, - addModule: (dir, request) => changeModule(dir, request.package, 'add'), - removeModule: (dir, request) => changeModule(dir, request.package, 'remove'), + addModule: (dir, request) => addModule(dir, request.package), + removeModule: (dir, request) => + removeModule(dir, request.package, request.did), } diff --git a/packages/cli/src/cli.ts b/packages/cli/src/cli.ts index 602f087..cfe24ea 100644 --- a/packages/cli/src/cli.ts +++ b/packages/cli/src/cli.ts @@ -85,9 +85,13 @@ async function usage( } /** 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/change.ts b/packages/cli/src/commands/change.ts index bc1972b..50e39b8 100644 --- a/packages/cli/src/commands/change.ts +++ b/packages/cli/src/commands/change.ts @@ -4,6 +4,8 @@ import type { CliContext } from '../context.js' import { DrxError } from '../errors.js' import { carryOut, + changesSomething, + leftToDo, planAdd, planData, planLines, @@ -68,22 +70,19 @@ const ARGS = { } satisfies Record /** The modules of the registry that the picker offers for an action. */ -async function candidates( +function candidates( action: Action, modules: ModuleEntry[], - project: Project, - options: ChangeOptions -): Promise { + project: Project +): ModuleEntry[] { const sorted = [...modules].sort((a, b) => a.name.localeCompare(b.name)) if (action === 'add') { return sorted.filter((module) => !module.archived && module.npm) } - const present: ModuleEntry[] = [] - for (const module of sorted) { - const plan = await planRemove(module, project, options) - if (plan.refusals.length === 0) present.push(module) - } - return present + // What can be removed is what drx add recorded. + return sorted.filter((module) => + project.config.modules?.some((entry) => entry.name === module.name) + ) } /** @@ -142,16 +141,12 @@ function changeCommand( ), registry: loaded.modules, names: [], + exec: context.exec, } const picked = names.length === 0 if (picked) { - const offered = await candidates( - action, - loaded.modules, - project, - options - ) + const offered = candidates(action, loaded.modules, project) if (offered.length === 0) { throw new DrxError( 'usage', @@ -205,13 +200,22 @@ function changeCommand( name: plan.module.name, package: plan.package, steps: planData(plan), - leftToDo: plan.after, + 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, '', 'Nothing was changed: this was a dry run.'].join('\n') + [ + ...shown, + ...(byHand.length > 0 + ? ['', 'Left to do:', ...byHand.map((line) => ` ${line}`)] + : []), + '', + 'Nothing was changed: this was a dry run.', + ].join('\n') ) return } @@ -231,11 +235,16 @@ function changeCommand( await carryOut(plans, project, context, output) - const left = plans.flatMap((plan) => plan.after) + const left = plans.flatMap(leftToDo) output.result( { ok: true, dryRun: false, modules: data }, [ - ...plans.map((plan) => `${words.did} ${plan.module.name}.`), + ...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}`)] : []), diff --git a/packages/cli/src/errors.ts b/packages/cli/src/errors.ts index 6b03c40..db12abd 100644 --- a/packages/cli/src/errors.ts +++ b/packages/cli/src/errors.ts @@ -21,10 +21,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/modules/change.ts b/packages/cli/src/modules/change.ts index d5d672a..b79aae5 100644 --- a/packages/cli/src/modules/change.ts +++ b/packages/cli/src/modules/change.ts @@ -2,10 +2,11 @@ import { existsSync } from 'node:fs' import { mkdir, writeFile } from 'node:fs/promises' import { dirname, join } from 'node:path' import { adapterFor, type KindAdapter } from '../adapters/index.js' -import type { BackendRecord, ModuleChange } from '../adapters/adapter.js' +import type { Ask, BackendRecord, ModuleChange } 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 { @@ -34,6 +35,8 @@ export interface PartPlan { /** Why the steps cannot be taken from here, and the lines to run instead. */ elsewhere?: { reason: string; lines: string[] } record?: BackendRecord + /** Asks the part what the steps did, once they have run. */ + settle?: () => Promise } /** Why a module cannot be changed. `--force` goes past a forceable one. */ @@ -52,8 +55,22 @@ export interface ModulePlan { notes: string[] /** What is left for the user once the steps are done. */ after: string[] - /** The record to keep, or to drop when it is undefined on a removal. */ + /** + * 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 }[] + /** + * Brings `record` in line with what the steps did, once they have run. + * A plan is made before anything is changed, and a part may do more than + * it was asked to. + */ + settle?: () => Promise } export interface Project { @@ -70,6 +87,8 @@ export interface ChangeOptions { 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 { @@ -89,6 +108,83 @@ function located(project: Project, role: Part['role']): Located[] { }) } +/** + * 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), + }) + } +} + +const hasAny = (record: BackendRecord) => + record.modules.length + record.patches.length > 0 + +/** 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) + } + return { modules, patches } +} + +/** 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) + return { + path: entry.path, + installed: entry.installed || before?.installed === true, + listed: entry.listed || before?.listed === true, + } + }) + let backend = old.backend + for (const { path, ...record } of now.backend) { + backend = withBackend(backend, path, record) + } + return { name: now.name, package: now.package, frontend, backend } +} + const pluralPatches = (count: number) => `${count} patch${count === 1 ? '' : 'es'}` @@ -175,6 +271,7 @@ function backendPlan( } }), ...(change.record ? { record: change.record } : {}), + ...(change.settle ? { settle: change.settle } : {}), } } @@ -212,6 +309,7 @@ export async function planAdd( warnings: [], notes: [], after: [], + handOver: [], } if (module.archived) { plan.refusals.push({ @@ -227,6 +325,12 @@ export async function planAdd( return plan } + const record: ModuleRecord = { + name: module.name, + package: module.npm, + frontend: [], + backend: [], + } for (const at of located(project, 'frontend')) { const druxt = await at.adapter.druxt(at.dir) const fit = compatibility(module.druxt, druxt) @@ -249,45 +353,64 @@ export async function planAdd( }) absorb(plan, change) plan.parts.push(frontendPlan(at, change)) + if (change.did) { + record.frontend?.push({ path: at.part.path, ...change.did }) + } } - const record: ModuleRecord = { - name: module.name, - package: module.npm, - backend: [], - } + const backend: { path: string; part: PartPlan }[] = [] for (const at of located(project, 'backend')) { 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, { needs, patches: options.patches, registryStatesCore: options.registryStatesCore, + ...(ask ? { ask } : {}), }) const part = backendPlan(project, at, change) - // What is left by hand: first the commands for a backend that is - // elsewhere, then the setup the module needs wherever it runs. - plan.after.push(...elsewhereLines(part)) absorb(plan, change) plan.parts.push(part) - const done = part.record - if (done && done.modules.length + done.patches.length > 0) { - record.backend.push({ path: at.part.path, ...done }) + backend.push({ path: at.part.path, part }) + } + + // 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 + ) + const build = (): ModuleRecord => { + const now: ModuleRecord = { + ...record, + backend: backend.flatMap(({ path, part }) => + part.record && hasAny(part.record) ? [{ path, ...part.record }] : [] + ), + } + return before ? mergeRecords(before, now) : now + } + plan.record = build() + plan.settle = async () => { + for (const { part } of backend) { + if (part.settle) part.record = await part.settle() } + plan.record = build() } - plan.record = record return plan } -/** True when the project has the package of a module in a frontend part. */ -async function hasPackage(project: Project, name: string): Promise { +/** 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')) { - if (await at.adapter.package(at.dir, name)) return true + 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. */ +/** + * 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, @@ -302,32 +425,49 @@ export async function planRemove( warnings: [], notes: [], after: [], + handOver: [], } const recorded = project.config.modules?.find( (entry) => entry.name === module.name ) - const present = module.npm ? await hasPackage(project, module.npm) : false - if (!present && !recorded) { + if (!recorded) { + const there = module.npm ? await declares(project, module.npm) : false plan.refusals.push({ - reason: `${module.npm ?? module.name} is not in this project.`, + 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 did = recorded.frontend + ? (recorded.frontend.find(({ path }) => path === at.part.path) ?? { + installed: false, + listed: false, + }) + : undefined const change = await at.adapter.removeModule(at.dir, { ...(module.npm ? { package: module.npm } : {}), - stillNeeded: [], + ...(did ? { did: { installed: did.installed, listed: did.listed } } : {}), }) absorb(plan, change) plan.parts.push(frontendPlan(at, change)) } - const backend = recorded?.backend ?? [] - if (backend.length === 0) return plan + 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 backend) { + for (const entry of recorded.backend) { const put = [ ...entry.modules.map(({ name }) => name), ...(entry.patches.length > 0 @@ -339,34 +479,97 @@ export async function planRemove( ) } // The record stays, so the backend can still be undone. - if (recorded) plan.record = recorded + keep(recorded.backend) return plan } // A backend module stays while any other module in the project needs it. - const stillNeeded = new Set() + // 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 - const kept = - (await hasPackage(project, other.npm)) || - project.config.modules?.some((entry) => entry.name === other.name) - if (kept) for (const need of other.backend) stillNeeded.add(need.name) + 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) + } } - for (const at of located(project, 'backend')) { - const entry = backend.find(({ path }) => path === at.part.path) - if (!entry) continue + + 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, { - record: { modules: entry.modules, patches: entry.patches }, - stillNeeded: [...stillNeeded], + record: { + modules: entry.modules.filter((held) => !staying.includes(held)), + patches: entry.patches.filter((patch) => !stays(patch)), + }, + ...(ask ? { ask } : {}), }) - const part = backendPlan(project, at, change) - plan.after.push(...elsewhereLines(part)) absorb(plan, change) - plan.parts.push(part) + 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) + if (heir) { + heir.record = mergeBackend(heir.record, change.record) + } else { + left = withBackend(left, path, change.record) + } } + 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' @@ -438,22 +641,29 @@ export async function carryOut( labels.length > 0 ? [title, ...labels.map((label) => ` ${label}`)] : [] + const finished = all.slice(0, done).map(({ label }) => label) + const pending = all.slice(done).map(({ label }) => label) + const shown = result.output.trimEnd() throw new DrxError( 'step-failed', [ `${step.display} failed in ${part.path}/ with exit code ${result.code}.`, - result.output.trimEnd(), - ...list( - 'Done:', - all.slice(0, done).map(({ label }) => label) - ), - ...list( - 'Not done:', - all.slice(done).map(({ label }) => label) - ), + shown, + ...list('Done:', finished), + ...list('Not done:', pending), ] .filter((line) => line !== '') - .join('\n') + .join('\n'), + { + failed: { + part: part.path, + step: step.display, + exitCode: result.code, + output: shown, + }, + done: finished, + notDone: pending, + } ) } } @@ -463,10 +673,18 @@ export async function carryOut( // The record is written once the module is wholly done, so a remove // never undoes something an add did not finish. - const others = (config.modules ?? []).filter( + await plan.settle?.() + let modules = (config.modules ?? []).filter( (entry) => entry.name !== plan.module.name ) - const modules = plan.record ? [...others, plan.record] : others + if (plan.record) modules = [...modules, plan.record] + for (const { to, path, record } of plan.handOver) { + modules = modules.map((entry) => + entry.name === to + ? { ...entry, backend: withBackend(entry.backend, path, record) } + : entry + ) + } const rest: ProjectConfig = { ...config } delete rest.modules config = modules.length > 0 ? { ...rest, modules } : rest diff --git a/packages/cli/src/project.ts b/packages/cli/src/project.ts index 8a81a14..edc6e7c 100644 --- a/packages/cli/src/project.ts +++ b/packages/cli/src/project.ts @@ -3,7 +3,7 @@ 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 } from './adapters/adapter.js' +import type { BackendRecord, PackageRecord } from './adapters/adapter.js' import { DrxError } from './errors.js' import { isLayout, LAYOUTS, type Layout } from './layouts.js' import { partsProblem, type Part } from './parts.js' @@ -32,16 +32,66 @@ export interface ProjectConfig { modules?: ModuleRecord[] } -/** One module the CLI added to the project. */ +/** + * 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, + })), + } + : {}), + 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 } : {}), + })), + })), + } +} + export async function writeProjectConfig( root: string, config: ProjectConfig @@ -128,6 +178,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 ModuleRecord[] } : {}), + ...(config.modules + ? { modules: (config.modules as Raw[]).map(moduleRecord) } + : {}), } } diff --git a/packages/cli/test/adapters/drupal-modules.test.ts b/packages/cli/test/adapters/drupal-modules.test.ts index d7d4082..26efaa9 100644 --- a/packages/cli/test/adapters/drupal-modules.test.ts +++ b/packages/cli/test/adapters/drupal-modules.test.ts @@ -1,6 +1,11 @@ import { afterEach, describe, expect, test } from 'vitest' import { adapterFor } from '../../src/adapters/index.js' -import type { AddRequest, ModuleChange } from '../../src/adapters/adapter.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' @@ -16,10 +21,47 @@ const need = ( kind: 'drupal', name, label: name, - core: false, ...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 = {} +) { + const asked: string[] = [] + const ask: Ask = async (tool, args) => { + asked.push(`${tool} ${args.join(' ')}`) + if (args[0] === 'pm: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[1] as string + if (!enabled.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 = {}, @@ -47,6 +89,7 @@ const add = ( needs, patches: true, registryStatesCore: true, + ask: answering().ask, ...options, }) @@ -66,7 +109,12 @@ describe('adding the backend modules a Druxt module needs', () => { ]) expect(change.record).toEqual({ modules: [ - { name: 'decoupled_router', package: 'drupal/decoupled_router' }, + { + name: 'decoupled_router', + package: 'drupal/decoupled_router', + enabled: true, + required: true, + }, ], patches: [], }) @@ -76,7 +124,11 @@ describe('adding the backend modules a Druxt module needs', () => { test('only enables a core module', async () => { const change = await add(site(), [need('jsonapi', { core: true })]) expect(runs(change)).toEqual(['drush en -y jsonapi']) - expect(change.record).toEqual({ modules: [], patches: [] }) + // 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 () => { @@ -91,11 +143,17 @@ describe('adding the backend modules a Druxt module needs', () => { 'drush en -y menu_items views', ]) expect(change.record?.modules).toEqual([ - { name: 'menu_items', package: 'drupal/jsonapi_menu_items' }, + { + 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 does not record it', async () => { + test('does not require a package the site has, and records only the enabling', async () => { const dir = site({ require: { 'drupal/core-recommended': '~11', @@ -107,7 +165,87 @@ describe('adding the backend modules a Druxt module needs', () => { 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']) + 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 change.settle?.()).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 change.settle?.())?.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 () => { @@ -238,11 +376,11 @@ describe('the patches a backend module needs', () => { 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', - 'composer patches-repatch', 'drush en -y decoupled_router', ]) expect(change.record?.patches).toEqual([ @@ -250,15 +388,63 @@ describe('the patches a backend module needs', () => { 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 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([ @@ -346,61 +532,298 @@ describe('the patches a backend module needs', () => { }) }) +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 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 record = { + const ROUTER = 'decoupled_router' + const MENU = 'jsonapi_menu_items' + const record: BackendRecord = { modules: [ - { name: 'decoupled_router', package: 'drupal/decoupled_router' }, - { name: 'jsonapi_menu_items', package: 'drupal/jsonapi_menu_items' }, + { + 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 = () => - site({ - extra: { - patches: { - 'drupal/decoupled_router': { - 'Fix the redirect loop': 'https://example.com/mr/12.diff', - 'Their own': 'patches/own.patch', + 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) => + drupal.removeModule(dir, { record: given, ask }) test('uninstalls and removes what the record says was added', async () => { - const change = await drupal.removeModule(carrying(), { - record, - stillNeeded: [], - }) + const { ask, asked } = answering([ROUTER, MENU]) + const change = await remove(carrying(), ask) + expect(asked).toEqual([ + 'drush pm:uninstall decoupled_router --simulate', + 'drush pm:uninstall jsonapi_menu_items --simulate', + ]) expect(runs(change)).toEqual([ 'drush pmu -y decoupled_router jsonapi_menu_items', - 'composer remove drupal/decoupled_router drupal/jsonapi_menu_items', + 'composer remove --no-update-with-dependencies drupal/decoupled_router drupal/jsonapi_menu_items', 'composer patches-relock', ]) 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('keeps a module something else still needs', async () => { - const change = await drupal.removeModule(carrying(), { - record, - stillNeeded: ['decoupled_router'], - }) + 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 drupal/jsonapi_menu_items', + 'composer remove --no-update-with-dependencies drupal/jsonapi_menu_items', ]) 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 stays: another installed module needs it.' + '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', + ]) + }) + }) + + 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', + ]) + }) + + 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 () => { @@ -413,12 +836,12 @@ describe('taking backend modules out again', () => { }, }, }) - const change = await drupal.removeModule(dir, { record, stillNeeded: [] }) + const change = await remove(dir, answering([ROUTER, MENU]).ask) expect(JSON.parse(edit(change)?.content ?? '{}').extra).toEqual({}) }) test('does nothing with no record', async () => { - const change = await drupal.removeModule(carrying(), { stillNeeded: [] }) + 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 index 1b7c9d4..72d5f6e 100644 --- a/packages/cli/test/adapters/nuxt-modules.test.ts +++ b/packages/cli/test/adapters/nuxt-modules.test.ts @@ -30,8 +30,9 @@ const add = (dir: string, name = 'druxt-breadcrumb') => patches: true, registryStatesCore: false, }) -const remove = (dir: string, name = 'druxt-breadcrumb') => - nuxt.removeModule(dir, { package: name, stillNeeded: [] }) +const DID = { installed: true, listed: true } +const remove = (dir: string, name = 'druxt-breadcrumb', did = DID) => + nuxt.removeModule(dir, { package: name, did }) const runs = (change: ModuleChange) => change.steps.flatMap((step) => ('run' in step ? [step.run] : [])) @@ -147,8 +148,31 @@ describe('adding a module to the Nuxt 2 config of the quickstart', () => { 'package.json': { dependencies: { 'druxt-auth': '^0.4.0' } }, }) const content = edits(await remove(dir, 'druxt-auth'))[0]?.content - expect(content).not.toContain('druxt-auth') - expect(content).toContain("'druxt-site',") + // 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)) }) }) @@ -222,4 +246,44 @@ describe('a package the part already has', () => { 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 index f4abbac..63d3a7d 100644 --- a/packages/cli/test/commands/add.test.ts +++ b/packages/cli/test/commands/add.test.ts @@ -137,14 +137,57 @@ function snapshot(root: string): Record { ) } +/** 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 +} + /** * 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 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 }) { +function tools( + root: string, + fail?: { on: string; output: string }, + backend: Backend = {} +) { const calls: string[] = [] + const asked: string[] = [] + const enabled = new Set(backend.enabled ?? []) 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 }]) + ) + return { code: 0, output: JSON.stringify(list) } + } + if (args.includes('--simulate')) { + asked.push(line) + const name = args.at(-2) as string + if (backend.unreadable) return { code: 1, output: 'No database.' } + if (!enabled.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 (command === 'npm') { @@ -155,20 +198,42 @@ function tools(root: string, fail?: { on: string; output: string }) { else delete manifest.dependencies[args[1] as string] writeFileSync(file, JSON.stringify(manifest)) } + const names = args.slice(args.indexOf('-y') + 1) + 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, exec } + return { calls, asked, exec, enabled } } -const never: CliContext['exec'] = async (command, args) => { - throw new Error(`A command was run: ${command} ${args.join(' ')}`) +/** 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, exec: never, ...overrides }) +) => + 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')) @@ -277,17 +342,24 @@ describe('drx add', () => { { name: 'breadcrumb', package: 'druxt-breadcrumb', + frontend: [{ path: 'nuxt', installed: true, listed: true }], backend: [ { path: 'drupal', modules: [ - { name: 'decoupled_router', package: 'drupal/decoupled_router' }, + { + 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', }, ], }, @@ -630,7 +702,7 @@ describe('drx add in a terminal with no name', () => { const result = await picking( root, { ...answers, 'Make these changes?': false }, - never + asking(root) ) expect(result.code).toBe(1) expect(result.stderr).toContain('Error: Cancelled. Nothing was changed.') @@ -639,6 +711,9 @@ describe('drx add in a terminal with no name', () => { }) 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() @@ -673,7 +748,7 @@ describe('drx remove', () => { test('--backend undoes what the record says drx add did, and drops the record', async () => { const root = await added() - const { calls, exec } = tools(root) + const { calls, exec } = tools(root, undefined, ENABLED) const result = await drx(['remove', 'breadcrumb', '--backend'], root, { exec, }) @@ -681,7 +756,7 @@ describe('drx remove', () => { expect(calls).toEqual([ 'nuxt$ npm uninstall druxt-breadcrumb', 'drupal$ ddev drush pmu -y decoupled_router', - 'drupal$ ddev composer remove drupal/decoupled_router', + 'drupal$ ddev composer remove --no-update-with-dependencies drupal/decoupled_router', 'drupal$ ddev composer patches-relock', ]) const composer = JSON.parse( @@ -700,31 +775,15 @@ describe('drx remove', () => { manifest.dependencies['druxt-router'] = '^0.25.0' writeFileSync(file, JSON.stringify(manifest)) - const { calls, exec } = tools(root) + 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: another installed module needs it.' - ) - }) - - test('touches no backend module that drx add did not put there', async () => { - const root = project() - const file = join(root, 'nuxt/package.json') - const manifest = JSON.parse(readFileSync(file, 'utf8')) - manifest.dependencies['druxt-blocks'] = '^0.25.0' - writeFileSync(file, JSON.stringify(manifest)) - - const { calls, exec } = tools(root) - const result = await drx( - ['module', 'remove', 'blocks', '--backend'], - root, - { exec } - ) - expect(result.code).toBe(0) - expect(calls).toEqual(['nuxt$ npm uninstall druxt-blocks']) + 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 () => { @@ -732,7 +791,8 @@ describe('drx remove', () => { const before = snapshot(root) const result = await drx( ['remove', 'breadcrumb', '--backend', '--dry-run'], - root + root, + { exec: asking(root, ENABLED) } ) expect(result.code).toBe(0) expect(result.stdout).toBe( @@ -744,7 +804,7 @@ describe('drx remove', () => { ' drupal/', ' run ddev drush pmu -y decoupled_router', ' edit Remove 1 patch from composer.json', - ' run ddev composer remove drupal/decoupled_router', + ' run ddev composer remove --no-update-with-dependencies drupal/decoupled_router', ' run ddev composer patches-relock', '', 'Nothing was changed: this was a dry run.', @@ -762,3 +822,520 @@ describe('drx remove', () => { ) }) }) + +/** 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', + ]) + 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', + ]) + 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', + ]) + 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 decoupled_router --simulate' + ) + 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', + ]) + 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', + }, + ], + }, + ], + }, + ]) + + 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', + ]) + expect( + JSON.parse(readFileSync(join(root, 'drupal/composer.json'), 'utf8')).extra + ).toEqual({}) + 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 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 en -y decoupled_router', + ], + }, + }) + }) +}) diff --git a/packages/cli/test/project.test.ts b/packages/cli/test/project.test.ts index fc13e82..57a083f 100644 --- a/packages/cli/test/project.test.ts +++ b/packages/cli/test/project.test.ts @@ -85,6 +85,7 @@ describe('loadProjectConfig', () => { { name: 'breadcrumb', package: 'druxt-breadcrumb', + frontend: [{ path: 'nuxt', installed: true, listed: false }], backend: [ { path: 'drupal', @@ -92,13 +93,17 @@ describe('loadProjectConfig', () => { { 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', }, ], }, @@ -110,6 +115,62 @@ describe('loadProjectConfig', () => { 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'], [ From 7f2aa6ba12d2388426d942cf6630240ae09ac10b Mon Sep 17 00:00:00 2001 From: Stuart Clark Date: Wed, 18 Nov 2026 23:20:31 +0000 Subject: [PATCH 3/4] fix(cli): keep files, records and tool arguments true when adding and removing modules `drx add` and `drx remove` now change a file from what is in it when the step runs, and record what they really did. - An edit holds the change and not the content. `nuxt.config`, `composer.json` and `drx.config.json` are read again as each step is taken, so two modules in one run keep what the other wrote. - Each module is planned again once the one before it is done. A backend module two of them need is required and enabled once. - Every step of an add says what it does. When a tool fails, the steps taken go on the record, a second run finishes the job with the record of a clean run, and a remove undoes what was done. - `allow-plugins` gains one key in a list or where there is none. `true` is left alone. With `false`, a patch is refused. - A patch is refused when the site has one of the same name with another URL, and when the installed patches plugin is version 1. - `add` refuses a module no frontend part can take, and lists what a module needs of a backend the project does not have. - `remove` works from the record when the registry has no such module, cannot be read or is invalid. - The package manager is the one `packageManager` names, then the one of a lock file, each looked for from the project root down. - A Composer package, a constraint and a patch package are checked by pattern in the registry, and so is every name in a record. - npm, pnpm, yarn, Composer and Drush get `--` before the names. - On Windows a program is started by its file with no shell. A batch file gets every argument in double quotes, and one with a quote, a percent sign or a line break is refused. - `init --force` keeps the `modules` records of the project. - Taking out the last patch also takes out an `extra` it leaves empty. --- README.md | 28 +- packages/cli/src/adapters/adapter.ts | 49 +- packages/cli/src/adapters/drupal-fields.ts | 79 +- packages/cli/src/adapters/drupal-modules.ts | 240 +++- packages/cli/src/adapters/drupal.ts | 3 +- packages/cli/src/adapters/nuxt.ts | 129 +- packages/cli/src/commands-on-path.ts | 46 +- packages/cli/src/commands/change.ts | 158 ++- packages/cli/src/commands/init.ts | 28 +- packages/cli/src/exec.ts | 121 +- packages/cli/src/modules/change.ts | 469 ++++--- packages/cli/src/project.ts | 22 +- .../cli/test/adapters/drupal-modules.test.ts | 157 ++- .../cli/test/adapters/nuxt-modules.test.ts | 152 ++- packages/cli/test/commands/add.test.ts | 1075 +++++++++++++++-- .../cli/test/commands/init-engines.test.ts | 64 + packages/cli/test/commands/menu.test.ts | 2 +- packages/cli/test/exec.test.ts | 157 ++- packages/cli/test/modules/entry.test.ts | 101 ++ packages/cli/test/non-interactive.test.ts | 182 ++- packages/cli/test/project.test.ts | 75 ++ 21 files changed, 2872 insertions(+), 465 deletions(-) diff --git a/README.md b/README.md index cf820c1..e091a87 100644 --- a/README.md +++ b/README.md @@ -75,7 +75,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. @@ -142,9 +142,13 @@ npx @druxt/cli add breadcrumb --dry-run For each module it does two things: -- **Frontend.** It installs the package with the package manager of the part's lock file, 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. +- **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. - **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. +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 | @@ -157,18 +161,26 @@ It first asks the backend which modules are enabled, with `drush pm:list`, and l 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. A patch is skipped when the installed package is at or past the version that has the fix, and when the site already has the same patch. +**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. 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, and when the site already has the same patch. + +**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. Nothing is recorded for that module. 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. +**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. @@ -178,6 +190,8 @@ At a terminal with no name, `drx add` lists the modules to pick from, shows the 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. @@ -189,7 +203,7 @@ The backend is left alone unless `--backend` is given. With it, `remove` undoes - 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. - 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. +- 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. - 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. @@ -358,6 +372,8 @@ A kind is `nuxt` or `drupal` in this version. | `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 | +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. @@ -472,7 +488,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` may hold only what a version constraint is made of. 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: diff --git a/packages/cli/src/adapters/adapter.ts b/packages/cli/src/adapters/adapter.ts index 743b3f3..9751789 100644 --- a/packages/cli/src/adapters/adapter.ts +++ b/packages/cli/src/adapters/adapter.ts @@ -35,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 /** @@ -69,19 +75,43 @@ export interface ToolRun { */ export type Ask = (tool: string, args: string[]) => Promise -/** A file of the part to write, with its whole new content. */ +/** + * 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 - content: 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 } +/** + * 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 }) & { + /** 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. */ @@ -97,6 +127,8 @@ export interface AddRequest { 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. @@ -138,7 +170,7 @@ export interface BackendRecord { /** The steps of a change to one part, in the order to take them. */ export interface ModuleChange { - steps: ({ run: ToolRun } | { edit: FileEdit })[] + steps: ChangeStep[] /** Reasons the change cannot be made. With any, no step is taken. */ problems: string[] warnings: string[] @@ -156,11 +188,12 @@ export interface ModuleChange { */ record?: BackendRecord /** - * For an add, asks the part what the steps did once they have run, and - * gives the record to keep in place of `record`. A backend may enable more - * than it was asked to, and only then can that be seen. + * 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?: () => Promise + settle?: (done: BackendRecord) => Promise } export function emptyChange(): ModuleChange { diff --git a/packages/cli/src/adapters/drupal-fields.ts b/packages/cli/src/adapters/drupal-fields.ts index 9058104..f86318d 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,77 @@ 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' + +/** + * The characters a Composer version constraint is made of: versions, + * operators, ranges, stability flags, branch names and references. It + * starts with a version or an operator, never with a hyphen. + */ +const CONSTRAINT = /^[A-Za-z0-9^~<>=!*][A-Za-z0-9 .*^~<>=!|,@#/_+-]*$/ +const CONSTRAINT_RULE = 'must be a Composer version constraint' + +/** No name or constraint is anywhere near this long. */ +const LENGTH = 200 + +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 && + !matches(composer.constraint, 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 index 8166535..96764e9 100644 --- a/packages/cli/src/adapters/drupal-modules.ts +++ b/packages/cli/src/adapters/drupal-modules.ts @@ -16,12 +16,12 @@ import { /** 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 type Json = Record type Patches = Record> interface Manifest { - source: string json: Json require: Record patches: Patches @@ -29,12 +29,12 @@ interface Manifest { async function readManifest(dir: string): Promise { try { - const source = await readFile(join(dir, 'composer.json'), 'utf8') - const json: unknown = JSON.parse(source) + 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 { - source, json, require: isRecord(json.require) ? json.require : {}, patches: (isRecord(extra.patches) ? extra.patches : {}) as Patches, @@ -44,11 +44,106 @@ async function readManifest(dir: string): Promise { } } -/** The manifest as text, with the indent and final newline it had. */ -function write(manifest: Manifest, json: Json): string { - const indent = /^([ \t]+)"/m.exec(manifest.source)?.[1] ?? ' ' +/** 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 manifest.source.endsWith('\n') ? `${text}\n` : text + 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) +} + +/** + * 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. */ @@ -142,7 +237,7 @@ async function uninstallList( ask: Ask, name: string ): Promise { - const result = await ask('drush', ['pm:uninstall', name, '--simulate']) + const result = await ask('drush', ['pm:uninstall', '--simulate', '--', name]) if (result.code !== 0) { return /not installed/.test(result.output) ? 'absent' : undefined } @@ -195,7 +290,7 @@ export async function planBackendAdd( // lines are printed for whoever is there, so an empty manifest will do. const manifest = (await readManifest(dir)) ?? - (ask ? undefined : { source: '{}\n', json: {}, require: {}, patches: {} }) + (ask ? undefined : { json: {}, require: {}, patches: {} }) if (!manifest) { change.problems.push( `There is no composer.json to add ${needs.map(({ name }) => name).join(', ')} to.` @@ -282,6 +377,14 @@ export async function planBackendAdd( ) 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, @@ -305,6 +408,32 @@ export async function planBackendAdd( } } + // 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] + if (first) { + 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.description}" 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.description}" 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.description}" needs it. Allow the plugin there, or ${without}.` + ) + } + } + if (change.problems.length > 0) return change if (ask && !enabled && toEnable.length > 0) { change.warnings.push( @@ -316,62 +445,80 @@ export async function planBackendAdd( `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.` ) } - const composer = (...args: string[]) => - change.steps.push({ run: { tool: 'composer', args } }) + // Each step carries what it will have done, so a run that stops part way + // can still say what it did. + const composer = (args: string[], done?: BackendRecord) => + change.steps.push({ + run: { tool: 'composer', args }, + ...(done ? { record: done } : {}), + }) if (record.patches.length > 0) { - const json = structuredClone(manifest.json) - json.extra = { ...(isRecord(json.extra) ? json.extra : {}), patches } - const hasPlugin = PATCHES_PLUGIN in manifest.require - if (!hasPlugin) { - // Allowed before it is required, or Composer stops to ask. - const config = isRecord(json.config) ? json.config : {} - const allowed = isRecord(config['allow-plugins']) - ? config['allow-plugins'] - : {} - json.config = { - ...config, - 'allow-plugins': { ...allowed, [PATCHES_PLUGIN]: true }, - } - } + // Allowed before it is required, or Composer stops to ask. + const allow = !hasPlugin const count = record.patches.length change.steps.push({ edit: { file: 'composer.json', - content: write(manifest, json), + change: (source) => withPatches(source, record.patches, allow), summary: `Add ${count} patch${count === 1 ? '' : 'es'} to composer.json`, }, + record: { modules: [], patches: record.patches }, }) if (!hasPlugin) { - composer('require', `${PATCHES_PLUGIN}:${PATCHES_PLUGIN_CONSTRAINT}`) + composer([ + 'require', + '--', + `${PATCHES_PLUGIN}:${PATCHES_PLUGIN_CONSTRAINT}`, + ]) } - composer('patches-relock') + composer(['patches-relock']) + } + if (toRequire.length > 0) { + composer(['require', '--', ...toRequire], { + modules: record.modules + .filter((module) => module.required) + .map((module) => ({ ...module, enabled: false })), + patches: [], + }) } - if (toRequire.length > 0) composer('require', ...toRequire) - if (record.patches.length > 0 && repatch) composer('patches-repatch') + if (record.patches.length > 0 && repatch) composer(['patches-repatch']) if (toEnable.length > 0) { change.steps.push({ - run: { tool: 'drush', args: ['en', '-y', ...toEnable] }, + run: { tool: 'drush', args: ['en', '-y', '--', ...toEnable] }, + record: { + 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. Those modules - // were enabled by this add too, and are seen only once it has run. - change.settle = async () => { + // 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 record + 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) })) + .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 { modules, patches: record.patches } + return { modules, patches: done.patches } } } return change @@ -497,7 +644,9 @@ export async function planBackendRemove( 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] } }) + change.steps.push({ + run: { tool: 'drush', args: ['pmu', '-y', '--', ...going] }, + }) } // A patch goes with the requirement of the module it was written for. A @@ -517,18 +666,13 @@ export async function planBackendRemove( unpatched.add(patch.package) } if (unpatched.size > 0) { - const json = structuredClone(manifest.json) - const extra = { ...(isRecord(json.extra) ? json.extra : {}) } - if (Object.keys(patches).length === 0) delete extra.patches - else extra.patches = patches - json.extra = extra const count = leaving.filter((patch) => unpatched.has(patch.package) ).length change.steps.push({ edit: { file: 'composer.json', - content: write(manifest, json), + change: (source) => withoutPatches(source, leaving), summary: `Remove ${count} patch${count === 1 ? '' : 'es'} from composer.json`, }, }) @@ -541,9 +685,9 @@ export async function planBackendRemove( // 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. - if (kept.length > 0) composer('remove', '--no-update', ...kept) + if (kept.length > 0) composer('remove', '--no-update', '--', ...kept) if (free.length > 0) { - composer('remove', '--no-update-with-dependencies', ...free) + composer('remove', '--no-update-with-dependencies', '--', ...free) } else if (kept.length > 0) { composer('update', '--lock') } @@ -553,7 +697,7 @@ export async function planBackendRemove( const still = [...unpatched].filter( (pkg) => installed.has(pkg) && !free.includes(pkg) ) - if (still.length > 0) composer('reinstall', ...still) + if (still.length > 0) composer('reinstall', '--', ...still) } const left: BackendRecord = { diff --git a/packages/cli/src/adapters/drupal.ts b/packages/cli/src/adapters/drupal.ts index a68a58d..3b9bd38 100644 --- a/packages/cli/src/adapters/drupal.ts +++ b/packages/cli/src/adapters/drupal.ts @@ -1,7 +1,7 @@ import { join } from 'node:path' import { isRecord } from '../validate.js' import type { KindAdapter, PackageVersion } from './adapter.js' -import { moduleProblem } from './drupal-fields.js' +import { moduleProblem, recordProblem } from './drupal-fields.js' import { planBackendAdd, planBackendRemove } from './drupal-modules.js' import { readJsonObject, stringMap } from './read-json.js' @@ -43,6 +43,7 @@ export const drupalAdapter: KindAdapter = { }, moduleProblem, + recordProblem, async packages(dir) { const requires = await required(dir) diff --git a/packages/cli/src/adapters/nuxt.ts b/packages/cli/src/adapters/nuxt.ts index 55b4ebd..a900611 100644 --- a/packages/cli/src/adapters/nuxt.ts +++ b/packages/cli/src/adapters/nuxt.ts @@ -1,6 +1,6 @@ import { existsSync } from 'node:fs' import { readFile } from 'node:fs/promises' -import { dirname, join, resolve } from 'node:path' +import { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path' import { emptyChange, type KindAdapter, @@ -63,19 +63,106 @@ async function packageVersion( return { name, range, installed } } -/** The package manager of a part, by the lock file it keeps. */ +/** + * 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 = [ - { lock: 'pnpm-lock.yaml', tool: 'pnpm', add: 'add', remove: 'remove' }, - { lock: 'yarn.lock', tool: 'yarn', add: 'add', remove: 'remove' }, - { lock: 'bun.lock', tool: 'bun', add: 'add', remove: 'remove' }, - { lock: 'bun.lockb', tool: 'bun', add: 'add', remove: 'remove' }, + { + 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 -const NPM = { tool: 'npm', add: 'install', remove: 'uninstall' } as const +type Manager = (typeof MANAGERS)[number] +const NPM = MANAGERS[3] -function packageManager(dir: string) { - return MANAGERS.find(({ lock }) => existsSync(join(dir, lock))) ?? NPM +/** 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))) @@ -86,19 +173,21 @@ const configFile = (dir: string) => */ async function addModule( dir: string, - name: string | undefined + 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 = packageManager(dir) + 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: [manager.add, name] }, + run: { tool: manager.tool, args: packageArgs(manager, 'add', name) }, + did: { installed: true }, }) did.installed = true } @@ -115,9 +204,10 @@ async function addModule( change.steps.push({ edit: { file, - content: edit.content, + change: moduleEdit(file, name, 'add'), summary: `Add '${name}' to modules in ${file}`, }, + did: { listed: true }, }) did.listed = true } else if (edit.kind === 'unsafe') { @@ -139,12 +229,13 @@ async function addModule( async function removeModule( dir: string, name: string | undefined, - did: PackageRecord | undefined + did: PackageRecord | undefined, + root: string | undefined ): Promise { const change = emptyChange() if (!name) return change - const manager = packageManager(dir) + const manager = await packageManager(dir, root) const dependency = name in (await declared(dir)) const file = configFile(dir) const edit = file @@ -167,7 +258,7 @@ async function removeModule( if (dependency) { if (did.installed) { change.steps.push({ - run: { tool: manager.tool, args: [manager.remove, name] }, + run: { tool: manager.tool, args: packageArgs(manager, 'remove', name) }, }) } else { change.notes.push( @@ -184,7 +275,7 @@ async function removeModule( change.steps.push({ edit: { file, - content: edit.content, + change: moduleEdit(file, name, 'remove'), summary: `Remove '${name}' from modules in ${file}`, }, }) @@ -234,7 +325,7 @@ export const nuxtAdapter: KindAdapter = { package: packageVersion, - addModule: (dir, request) => addModule(dir, request.package), + addModule: (dir, request) => addModule(dir, request.package, request.root), removeModule: (dir, request) => - removeModule(dir, request.package, request.did), + removeModule(dir, request.package, request.did, request.root), } 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 index 50e39b8..d3aa48b 100644 --- a/packages/cli/src/commands/change.ts +++ b/packages/cli/src/commands/change.ts @@ -10,13 +10,20 @@ import { 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 } from '../project.js' +import { + CONFIG_FILE, + findProjectRoot, + loadProjectConfig, + type ModuleRecord, +} from '../project.js' import { repeatCommand } from '../repeat.js' import { findModule, openModules, registryArgs } from './module.js' @@ -69,20 +76,44 @@ const ARGS = { }, } satisfies Record -/** The modules of the registry that the picker offers for an action. */ +/** + * 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 sorted = [...modules].sort((a, b) => a.name.localeCompare(b.name)) + const byName = (a: ModuleEntry, b: ModuleEntry) => + a.name.localeCompare(b.name) if (action === 'add') { - return sorted.filter((module) => !module.archived && module.npm) + return modules + .filter((module) => !module.archived && module.npm) + .sort(byName) } - // What can be removed is what drx add recorded. - return sorted.filter((module) => - project.config.modules?.some((entry) => entry.name === module.name) - ) + // 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) } /** @@ -130,23 +161,41 @@ function changeCommand( ) } - const loaded = await openModules(context, flags, output) + // 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: loaded.modules.some((module) => + registryStatesCore: registry.some((module) => module.backend.some((need) => need.core) ), - registry: loaded.modules, + registry, names: [], exec: context.exec, } const picked = names.length === 0 if (picked) { - const offered = candidates(action, loaded.modules, project) + const offered = candidates(action, registry, project) if (offered.length === 0) { throw new DrxError( 'usage', @@ -163,27 +212,45 @@ function changeCommand( }) } - const modules = names.map((wanted) => findModule(loaded.modules, wanted)) - options.names = modules.map((module) => module.name) - const plans: ModulePlan[] = [] - for (const module of modules) { - plans.push( - action === 'add' - ? await planAdd(module, project, options) - : await planRemove(module, project, options) - ) + /** 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.` + ) + } } - - // 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((plan) => + 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) { @@ -196,18 +263,19 @@ function changeCommand( ...(index > 0 ? [''] : []), ...planLines(plan), ]) - const data = plans.map((plan) => ({ - name: plan.module.name, - package: plan.package, - steps: planData(plan), - leftToDo: leftToDo(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 }, + { ok: true, dryRun: true, modules: data() }, [ ...shown, ...(byHand.length > 0 @@ -233,11 +301,31 @@ function changeCommand( } } - await carryOut(plans, project, context, output) + // 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 }, + { ok: true, dryRun: false, modules: data() }, [ ...plans.map((plan) => // A removal with no step found everything in place before it. diff --git a/packages/cli/src/commands/init.ts b/packages/cli/src/commands/init.ts index 5498068..68c3f23 100644 --- a/packages/cli/src/commands/init.ts +++ b/packages/cli/src/commands/init.ts @@ -27,7 +27,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 } from '../registry/entry.js' import { repeatCommand, shellQuote } from '../repeat.js' import { @@ -541,6 +547,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}` + ) + } + } + output.note(`Fetching the ${entry.name} starter from ${entry.tar}.`) try { await context.download(`starter:${entry.name}`, { @@ -623,8 +643,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/exec.ts b/packages/cli/src/exec.ts index d6bc858..2c30f55 100644 --- a/packages/cli/src/exec.ts +++ b/packages/cli/src/exec.ts @@ -1,4 +1,6 @@ import { spawn } from 'node:child_process' +import { extname } from 'node:path' +import { findCommandFile } from './commands-on-path.js' export interface ToolResult { code: number @@ -13,25 +15,106 @@ export type RunTool = ( 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'] + /** - * Runs a command with no shell. A tool that cannot be started is a failure - * like any other, with the reason as its output. + * 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. */ -export const runTool: RunTool = (command, args, { cwd }) => - new Promise((resolve) => { - let output = '' - const child = spawn(command, args, { - cwd, - stdio: ['ignore', 'pipe', 'pipe'], - shell: process.platform === 'win32', - }) - 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}`, +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 } : {}), }) - ) - child.on('close', (code) => resolve({ code: code ?? 1, output })) - }) + 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 index b79aae5..c4962ab 100644 --- a/packages/cli/src/modules/change.ts +++ b/packages/cli/src/modules/change.ts @@ -1,8 +1,14 @@ import { existsSync } from 'node:fs' -import { mkdir, writeFile } from 'node:fs/promises' -import { dirname, join } from 'node:path' +import { readFile, writeFile } from 'node:fs/promises' +import { join } from 'node:path' import { adapterFor, type KindAdapter } from '../adapters/index.js' -import type { Ask, BackendRecord, ModuleChange } from '../adapters/adapter.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' @@ -10,6 +16,7 @@ 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, @@ -17,8 +24,12 @@ import { 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. */ -export type PlannedStep = +/** + * 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 @@ -26,7 +37,20 @@ export type PlannedStep = cwd: string display: string } - | { type: 'edit'; file: string; content: string; display: string } + | { + type: 'edit' + file: string + change: (source: string) => string + 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 { @@ -34,9 +58,11 @@ export interface PartPlan { steps: PlannedStep[] /** Why the steps cannot be taken from here, and the lines to run instead. */ elsewhere?: { reason: string; lines: string[] } - record?: BackendRecord - /** Asks the part what the steps did, once they have run. */ - settle?: () => Promise + /** + * 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. */ @@ -66,13 +92,19 @@ export interface ModulePlan { */ handOver: { to: string; path: string; record: BackendRecord }[] /** - * Brings `record` in line with what the steps did, once they have run. - * A plan is made before anything is changed, and a part may do more than - * it was asked to. + * 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 @@ -123,6 +155,22 @@ function asker(project: Project, at: Located, exec: RunTool): Ask | undefined { } } +/** 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 @@ -178,35 +226,67 @@ function mergeRecords(old: ModuleRecord, now: ModuleRecord): ModuleRecord { listed: entry.listed || before?.listed === true, } }) - let backend = old.backend - for (const { path, ...record } of now.backend) { - backend = withBackend(backend, path, record) - } + // 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, + } + } + 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): PlannedStep => - 'run' in step - ? { - type: 'run', - command: step.run.tool, - args: step.run.args, - cwd: at.dir, - display: [step.run.tool, ...step.run.args].join(' '), - } - : { - type: 'edit', - file: join(at.dir, step.edit.file), - content: step.edit.content, - display: step.edit.summary, - } + steps: change.steps.map((step) => + planned(step, at.dir, ({ tool, args }) => ({ + command: tool, + args, + cwd: at.dir, + })) ), } } @@ -252,25 +332,12 @@ function backendPlan( return { path: part.path, - steps: change.steps.map((step): PlannedStep => { - if ('edit' in step) { - return { - type: 'edit', - file: join(at.dir, step.edit.file), - content: step.edit.content, - display: step.edit.summary, - } - } - const line = engine.run(part, step.run.tool, step.run.args) - return { - type: 'run', - command: line.command, - args: line.args, - cwd: join(project.root, line.cwd), - display: [line.command, ...line.args].join(' '), - } - }), - ...(change.record ? { record: change.record } : {}), + 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 } : {}), } } @@ -325,12 +392,8 @@ export async function planAdd( return plan } - const record: ModuleRecord = { - name: module.name, - package: module.npm, - frontend: [], - backend: [], - } + const npm = module.npm + const frontend: { path: string; part: PartPlan }[] = [] for (const at of located(project, 'frontend')) { const druxt = await at.adapter.druxt(at.dir) const fit = compatibility(module.druxt, druxt) @@ -346,24 +409,37 @@ export async function planAdd( ) } const change = await at.adapter.addModule(at.dir, { - package: module.npm, + package: npm, + root: project.root, needs: [], patches: options.patches, registryStatesCore: options.registryStatesCore, }) absorb(plan, change) - plan.parts.push(frontendPlan(at, change)) - if (change.did) { - record.frontend?.push({ path: at.part.path, ...change.did }) - } + const part = frontendPlan(at, change) + plan.parts.push(part) + if (change.did) frontend.push({ path: at.part.path, part }) + } + // 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 }[] = [] - for (const at of located(project, 'backend')) { + 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, @@ -375,25 +451,57 @@ export async function planAdd( 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 ) - const build = (): ModuleRecord => { + // 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 = { - ...record, - backend: backend.flatMap(({ path, part }) => - part.record && hasAny(part.record) ? [{ path, ...part.record }] : [] - ), + name: module.name, + package: npm, + frontend: frontend.map(({ path, part }) => ({ + path, + installed: taken(part).some((step) => step.did?.installed === true), + listed: taken(part).some((step) => step.did?.listed === true), + })), + backend: [], } - return before ? mergeRecords(before, now) : now - } - plan.record = build() - plan.settle = async () => { - for (const { part } of backend) { - if (part.settle) part.record = await part.settle() + 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 = build() + plan.record = before ? mergeRecords(before, now) : now } return plan } @@ -451,6 +559,7 @@ export async function planRemove( : 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 } } : {}), }) absorb(plan, change) @@ -535,6 +644,7 @@ export async function planRemove( 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)), @@ -601,93 +711,148 @@ export function planData(plan: ModulePlan) { ]) } +/** 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}`) + ) +} + /** - * Carries out the plans in order and keeps the project's record in step. - * The first tool that fails stops everything: its output is shown, with what - * had been done by then and what had not. + * 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( - plans: ModulePlan[], + plan: ModulePlan, project: Project, context: CliContext, - output: Output + output: Output, + around: Around = { done: [], pending: [] } ): Promise { - const all = plans.flatMap((plan) => - plan.parts.flatMap((part) => - part.steps.map((step) => ({ - step, - label: `${part.path}/: ${step.display}`, - path: part.path, - })) - ) + const steps = plan.parts.flatMap((part) => + part.steps.map((step) => ({ + step, + path: part.path, + label: `${part.path}/: ${step.display}`, + })) ) - let done = 0 - let config = project.config - - for (const plan of plans) { - for (const part of plan.parts) { - for (const step of part.steps) { - if (step.type === 'edit') { - await mkdir(dirname(step.file), { recursive: true }) - await writeFile(step.file, step.content) - output.did(`${part.path}/: ${step.display}`) - } else { - output.note(`${part.path}/: ${step.display}`) - const result = await context.exec(step.command, step.args, { - cwd: step.cwd, - }) - if (result.code !== 0) { - const list = (title: string, labels: string[]) => - labels.length > 0 - ? [title, ...labels.map((label) => ` ${label}`)] - : [] - const finished = all.slice(0, done).map(({ label }) => label) - const pending = all.slice(done).map(({ label }) => label) - const shown = result.output.trimEnd() - throw new DrxError( - 'step-failed', - [ - `${step.display} failed in ${part.path}/ with exit code ${result.code}.`, - shown, - ...list('Done:', finished), - ...list('Not done:', pending), - ] - .filter((line) => line !== '') - .join('\n'), - { - failed: { - part: part.path, - step: step.display, - exitCode: result.code, - output: shown, - }, - done: finished, - notDone: pending, - } - ) - } - } - done += 1 - } + 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) } - - // The record is written once the module is wholly done, so a remove - // never undoes something an add did not finish. - await plan.settle?.() - let modules = (config.modules ?? []).filter( - (entry) => entry.name !== plan.module.name + 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, + } ) - if (plan.record) modules = [...modules, plan.record] - for (const { to, path, record } of plan.handOver) { - modules = modules.map((entry) => - entry.name === to - ? { ...entry, backend: withBackend(entry.backend, path, record) } - : entry - ) + } + + 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 { + 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() + ) + } } - const rest: ProjectConfig = { ...config } - delete rest.modules - config = modules.length > 0 ? { ...rest, modules } : rest - await writeProjectConfig(project.root, config) + step.done = true } + + await plan.settle?.() + await writeRecord(plan, project, true) } diff --git a/packages/cli/src/project.ts b/packages/cli/src/project.ts index edc6e7c..5bb4fbb 100644 --- a/packages/cli/src/project.ts +++ b/packages/cli/src/project.ts @@ -4,10 +4,11 @@ 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, isRecord } from './validate.js' +import { isNonEmptyString, isNpmName, isRecord } from './validate.js' const nodeRequire = createRequire(import.meta.url) @@ -137,6 +138,25 @@ function configProblem(config: Record): string | undefined { 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 } diff --git a/packages/cli/test/adapters/drupal-modules.test.ts b/packages/cli/test/adapters/drupal-modules.test.ts index 26efaa9..bfb04dd 100644 --- a/packages/cli/test/adapters/drupal-modules.test.ts +++ b/packages/cli/test/adapters/drupal-modules.test.ts @@ -1,3 +1,5 @@ +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 { @@ -45,7 +47,7 @@ function answering( ) return { code: 0, output: JSON.stringify(list) } } - const name = args[1] as string + const name = args.at(-1) as string if (!enabled.includes(name)) { return { code: 1, @@ -80,32 +82,59 @@ function site( 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 = {} ) => - drupal.addModule(dir, { - needs, - patches: true, - registryStatesCore: true, - ask: answering().ask, - ...options, - }) + 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) => ('edit' in step ? [step.edit] : []))[0] + 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 en -y decoupled_router', + 'composer require -- drupal/decoupled_router', + 'drush en -y -- decoupled_router', ]) expect(change.record).toEqual({ modules: [ @@ -123,7 +152,7 @@ describe('adding the backend modules a Druxt module needs', () => { test('only enables a core module', async () => { const change = await add(site(), [need('jsonapi', { core: true })]) - expect(runs(change)).toEqual(['drush en -y jsonapi']) + 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 }], @@ -139,8 +168,8 @@ describe('adding the backend modules a Druxt module needs', () => { need('views', { core: true }), ]) expect(runs(change)).toEqual([ - 'composer require drupal/jsonapi_menu_items:^1.2', - 'drush en -y menu_items views', + 'composer require -- drupal/jsonapi_menu_items:^1.2', + 'drush en -y -- menu_items views', ]) expect(change.record?.modules).toEqual([ { @@ -161,7 +190,7 @@ describe('adding the backend modules a Druxt module needs', () => { }, }) const change = await add(dir, [need('decoupled_router')]) - expect(runs(change)).toEqual(['drush en -y decoupled_router']) + expect(runs(change)).toEqual(['drush en -y -- decoupled_router']) expect(change.notes).toContain( 'drupal/decoupled_router is already required in composer.json.' ) @@ -185,7 +214,9 @@ describe('adding the backend modules a Druxt module needs', () => { expect(asked).toEqual([ 'drush pm:list --type=module --status=enabled --fields=name,path --format=json', ]) - expect(runs(change)).toEqual(['composer require drupal/decoupled_router']) + expect(runs(change)).toEqual([ + 'composer require -- drupal/decoupled_router', + ]) expect(change.notes).toEqual([ 'decoupled_router is already enabled.', 'views is already enabled.', @@ -209,7 +240,7 @@ describe('adding the backend modules a Druxt module needs', () => { ]) // Drush enables what a module depends on with it. enabled.push('jsonapi_defaults', 'jsonapi_extras') - expect(await change.settle?.()).toEqual({ + expect(await settled(change)).toEqual({ modules: [ { name: 'jsonapi_defaults', @@ -227,7 +258,7 @@ describe('adding the backend modules a Druxt module needs', () => { const { ask } = answering([]) const change = await add(site(), [need('decoupled_router')], { ask }) // Nothing was enabled by the time it is asked again. - expect((await change.settle?.())?.modules).toEqual([ + expect((await settled(change))?.modules).toEqual([ { name: 'decoupled_router', package: 'drupal/decoupled_router', @@ -241,7 +272,7 @@ describe('adding the backend modules a Druxt module needs', () => { const change = await add(site(), [need('views', { core: true })], { ask: silent, }) - expect(runs(change)).toEqual(['drush en -y views']) + 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.', @@ -299,8 +330,8 @@ describe('telling a core module from a contributed one when the registry does no published ) expect(runs(change)).toEqual([ - 'composer require drupal/decoupled_router', - 'drush en -y jsonapi decoupled_router', + 'composer require -- drupal/decoupled_router', + 'drush en -y -- jsonapi decoupled_router', ]) }) @@ -312,7 +343,7 @@ describe('telling a core module from a contributed one when the registry does no { 'docroot/core/modules/views/views.info.yml': 'name: Views\n' } ) expect(runs(await add(dir, [need('views')], published))).toEqual([ - 'drush en -y views', + 'drush en -y -- views', ]) }) @@ -325,7 +356,7 @@ describe('telling a core module from a contributed one when the registry does no }) const change = await add(dir, [need('decoupled_router')], published) expect(change.problems).toEqual([]) - expect(runs(change)).toEqual(['drush en -y decoupled_router']) + expect(runs(change)).toEqual(['drush en -y -- decoupled_router']) }) test('refuses to guess when core is not installed, and takes no step', async () => { @@ -378,10 +409,10 @@ describe('the patches a backend module needs', () => { 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 require -- ${PLUGIN}:^2.0@beta`, 'composer patches-relock', - 'composer require drupal/decoupled_router', - 'drush en -y decoupled_router', + 'composer require -- drupal/decoupled_router', + 'drush en -y -- decoupled_router', ]) expect(change.record?.patches).toEqual([ { @@ -420,11 +451,11 @@ describe('the patches a backend module needs', () => { }), ]) expect(runs(change)).toEqual([ - `composer require ${PLUGIN}:^2.0@beta`, + `composer require -- ${PLUGIN}:^2.0@beta`, 'composer patches-relock', - 'composer require drupal/decoupled_router', + 'composer require -- drupal/decoupled_router', 'composer patches-repatch', - 'drush en -y decoupled_router', + 'drush en -y -- decoupled_router', ]) }) @@ -466,7 +497,9 @@ describe('the patches a backend module needs', () => { 'A local fix': 'patches/a.patch', }) expect(written.config).toBeUndefined() - expect(runs(change)).not.toContain(`composer require ${PLUGIN}:^2.0@beta`) + expect(runs(change)).not.toContain( + `composer require -- ${PLUGIN}:^2.0@beta` + ) }) test('skip one whose fix the installed package has', async () => { @@ -522,8 +555,8 @@ describe('the patches a backend module needs', () => { const change = await add(site(), [patched()], { patches: false }) expect(edit(change)).toBeUndefined() expect(runs(change)).toEqual([ - 'composer require drupal/decoupled_router', - 'drush en -y decoupled_router', + 'composer require -- drupal/decoupled_router', + '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.', @@ -548,8 +581,8 @@ describe('a backend that is not run from here', () => { ]) expect(change.problems).toEqual([]) expect(runs(change)).toEqual([ - 'composer require drupal/jsonapi_menu_items drupal/menu_link_content', - 'drush en -y jsonapi_menu_items menu_link_content', + 'composer require -- drupal/jsonapi_menu_items drupal/menu_link_content', + '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.', @@ -561,7 +594,7 @@ describe('a backend that is not run from here', () => { need('block', { core: true }), ]) expect(change.problems).toEqual([]) - expect(runs(change)).toEqual(['drush en -y block']) + expect(runs(change)).toEqual(['drush en -y -- block']) }) }) @@ -607,18 +640,18 @@ describe('taking backend modules out again', () => { files ) const remove = (dir: string, ask: Ask, given = record) => - drupal.removeModule(dir, { record: given, ask }) + 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) expect(asked).toEqual([ - 'drush pm:uninstall decoupled_router --simulate', - 'drush pm:uninstall jsonapi_menu_items --simulate', + 'drush pm:uninstall --simulate -- decoupled_router', + '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', + 'drush pmu -y -- decoupled_router jsonapi_menu_items', + 'composer remove --no-update-with-dependencies -- drupal/decoupled_router drupal/jsonapi_menu_items', 'composer patches-relock', ]) expect(JSON.parse(edit(change)?.content ?? '{}').extra.patches).toEqual({ @@ -632,8 +665,8 @@ describe('taking backend modules out again', () => { 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 pmu -y -- jsonapi_menu_items', + 'composer remove --no-update-with-dependencies -- drupal/jsonapi_menu_items', ]) expect(edit(change)).toBeUndefined() expect(change.notes).toEqual([ @@ -649,7 +682,7 @@ describe('taking backend modules out again', () => { 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' + 'drush pmu -y -- decoupled_router jsonapi_menu_items' ) }) @@ -677,12 +710,12 @@ describe('taking backend modules out again', () => { 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(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' + 'composer remove --no-update-with-dependencies -- drupal/decoupled_router drupal/jsonapi_menu_items' ) }) @@ -713,7 +746,7 @@ describe('taking backend modules out again', () => { 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 remove --no-update -- drupal/jsonapi_views', 'composer update --lock', ]) expect(asked).toEqual([]) @@ -735,7 +768,7 @@ describe('taking backend modules out again', () => { const { ask } = answering([]) const change = await remove(site({}, installed({})), ask, only) expect(runs(change)).toEqual([ - 'composer remove --no-update-with-dependencies drupal/jsonapi_views', + 'composer remove --no-update-with-dependencies -- drupal/jsonapi_views', ]) }) }) @@ -776,7 +809,7 @@ describe('taking backend modules out again', () => { } ) const change = await remove(dir, ask, given) - expect(runs(change)).toEqual(['drush pmu -y jsonapi_defaults']) + 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.', ]) @@ -803,11 +836,11 @@ describe('taking backend modules out again', () => { 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', + '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', + 'composer reinstall -- drupal/decoupled_router', ]) }) @@ -837,7 +870,25 @@ describe('taking backend modules out again', () => { }, }) const change = await remove(dir, answering([ROUTER, MENU]).ask) - expect(JSON.parse(edit(change)?.content ?? '{}').extra).toEqual({}) + // 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/' } }, + }) }) test('does nothing with no record', async () => { diff --git a/packages/cli/test/adapters/nuxt-modules.test.ts b/packages/cli/test/adapters/nuxt-modules.test.ts index 72d5f6e..d07ca33 100644 --- a/packages/cli/test/adapters/nuxt-modules.test.ts +++ b/packages/cli/test/adapters/nuxt-modules.test.ts @@ -1,4 +1,5 @@ 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' @@ -23,21 +24,46 @@ export default defineNuxtConfig({ }) ` -const add = (dir: string, name = 'druxt-breadcrumb') => - nuxt.addModule(dir, { - package: name, - needs: [], - patches: true, - registryStatesCore: false, - }) +/** 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) => - nuxt.removeModule(dir, { package: name, did }) +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) => ('edit' in step ? [step.edit] : [])) + 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-') @@ -50,21 +76,22 @@ describe('the package manager of a frontend part', () => { [ 'package-lock.json', 'npm', - ['install', 'druxt-breadcrumb'], - ['uninstall', 'druxt-breadcrumb'], + ['install', '--', 'druxt-breadcrumb'], + ['uninstall', '--', 'druxt-breadcrumb'], ], [ 'pnpm-lock.yaml', 'pnpm', - ['add', 'druxt-breadcrumb'], - ['remove', 'druxt-breadcrumb'], + ['add', '--', 'druxt-breadcrumb'], + ['remove', '--', 'druxt-breadcrumb'], ], [ 'yarn.lock', 'yarn', - ['add', 'druxt-breadcrumb'], - ['remove', 'druxt-breadcrumb'], + ['add', '--', 'druxt-breadcrumb'], + ['remove', '--', 'druxt-breadcrumb'], ], + // Not known to take the separator, so it is left out. [ 'bun.lock', 'bun', @@ -74,8 +101,8 @@ describe('the package manager of a frontend part', () => { [ 'README.md', 'npm', - ['install', 'druxt-breadcrumb'], - ['uninstall', 'druxt-breadcrumb'], + ['install', '--', 'druxt-breadcrumb'], + ['uninstall', '--', 'druxt-breadcrumb'], ], ])('with %s is %s', async (lock, tool, installArgs, removeArgs) => { const dir = part({ @@ -88,6 +115,95 @@ describe('the package manager of a frontend part', () => { ]) 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', () => { diff --git a/packages/cli/test/commands/add.test.ts b/packages/cli/test/commands/add.test.ts index 63d3a7d..5bd6478 100644 --- a/packages/cli/test/commands/add.test.ts +++ b/packages/cli/test/commands/add.test.ts @@ -7,7 +7,7 @@ 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 { serve, type TestServer } from '../helpers/server.js' +import { closedPort, serve, type TestServer } from '../helpers/server.js' import { cleanTmp, tmp, writeTree } from '../helpers/tmp.js' const NUXT_CONFIG = readFileSync( @@ -137,6 +137,8 @@ function snapshot(root: string): Record { ) } +const MANAGERS = ['npm', 'pnpm', 'yarn', 'bun'] + /** What the stand-in backend has enabled, and what depends on what. */ interface Backend { enabled?: string[] @@ -168,13 +170,16 @@ function tools( asked.push(line) if (backend.unreadable) return { code: 1, output: 'No database.' } const list = Object.fromEntries( - [...enabled].map((name) => [name, { name }]) + [...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.at(-2) as string + const name = args.findLast((arg) => !arg.startsWith('-')) as string if (backend.unreadable) return { code: 1, output: 'No database.' } if (!enabled.has(name)) { return { @@ -190,15 +195,39 @@ function tools( } calls.push(line) if (fail && line.includes(fail.on)) return { code: 1, output: fail.output } - if (command === 'npm') { + if (MANAGERS.includes(command)) { const file = join(cwd, 'package.json') const manifest = JSON.parse(readFileSync(file, 'utf8')) - if (args[0] === 'install') - manifest.dependencies[args[1] as string] = '^1.0.0' - else delete manifest.dependencies[args[1] as string] - writeFileSync(file, JSON.stringify(manifest)) + 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)) } - const names = args.slice(args.indexOf('-y') + 1) + // 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') + } + const names = args + .slice(args.indexOf('-y') + 1) + .filter((name) => name !== '--') if (args.includes('en')) { for (const name of names) { enabled.add(name) @@ -241,14 +270,14 @@ const config = (root: string) => const DRY_RUN = [ 'Add breadcrumb (druxt-breadcrumb)', ' nuxt/', - ' run npm install druxt-breadcrumb', + ' 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 require -- cweagans/composer-patches:^2.0@beta', ' run ddev composer patches-relock', - ' run ddev composer require drupal/decoupled_router', - ' run ddev drush en -y decoupled_router', + ' run ddev composer require -- drupal/decoupled_router', + ' run ddev drush en -y -- decoupled_router', '', 'Nothing was changed: this was a dry run.', '', @@ -296,12 +325,12 @@ describe('drx add --dry-run', () => { name: 'blocks', package: 'druxt-blocks', steps: [ - { part: 'nuxt', run: 'npm install druxt-blocks' }, + { 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' }, + { part: 'drupal', run: 'ddev drush en -y -- block' }, ], }, ], @@ -317,11 +346,11 @@ describe('drx add', () => { expect(result.code).toBe(0) expect(calls).toEqual([ - 'nuxt$ npm install druxt-breadcrumb', - 'drupal$ ddev composer require cweagans/composer-patches:^2.0@beta', + '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 en -y decoupled_router', + 'drupal$ ddev composer require -- drupal/decoupled_router', + 'drupal$ ddev drush en -y -- decoupled_router', ]) expect(readFileSync(join(root, 'nuxt/nuxt.config.js'), 'utf8')).toContain( " localhostListenURL,\n 'druxt-breadcrumb'\n ]," @@ -373,8 +402,8 @@ describe('drx add', () => { 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', + 'nuxt$ npm install -- druxt-blocks', + 'drupal$ vendor/bin/drush en -y -- block', ]) }) @@ -384,8 +413,8 @@ describe('drx add', () => { 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', + 'nuxt$ npm install -- druxt-blocks', + 'nuxt$ npm install -- druxt-router', ]) expect(config(root).modules.map((m: { name: string }) => m.name)).toEqual([ 'blocks', @@ -456,7 +485,7 @@ describe('drx add when the backend is not run from here', () => { 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(calls).toEqual(['nuxt$ npm install -- druxt-breadcrumb']) expect(result.stdout).toBe( [ 'Added breadcrumb.', @@ -464,10 +493,10 @@ describe('drx add when the backend is not run from here', () => { '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 require -- cweagans/composer-patches:^2.0@beta', ' composer patches-relock', - ' composer require drupal/decoupled_router', - ' drush en -y decoupled_router', + ' composer require -- drupal/decoupled_router', + ' drush en -y -- decoupled_router', '', ].join('\n') ) @@ -481,9 +510,9 @@ describe('drx add when the backend is not run from here', () => { 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(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' + ' This project does not record how drupal/ is run. In it:\n drush en -y -- block' ) }) }) @@ -569,31 +598,52 @@ 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', + 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' + '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.', + '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/: 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 require -- cweagans/composer-patches:^2.0@beta', ' drupal/: ddev composer patches-relock', 'Not done:', - ' drupal/: ddev composer require drupal/decoupled_router', - ' drupal/: ddev drush en -y decoupled_router', + ' drupal/: ddev composer require -- drupal/decoupled_router', + ' drupal/: ddev drush en -y -- decoupled_router', ].join('\n') ) - expect(config(root).modules).toBeUndefined() + // 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', + }, + ], + }, + ], + }, + ]) }) }) @@ -639,8 +689,8 @@ describe('telling core from contributed with the published registry', () => { 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 en -y jsonapi_menu_items menu_link_content', + 'drupal$ ddev composer require -- drupal/jsonapi_menu_items', + 'drupal$ ddev drush en -y -- jsonapi_menu_items menu_link_content', ]) }) }) @@ -685,7 +735,7 @@ describe('drx add in a terminal with no name', () => { 'router', ]) expect(result.stderr).toContain('Add breadcrumb (druxt-breadcrumb)') - expect(result.stderr).toContain(' run ddev drush en -y block') + expect(result.stderr).toContain(' run ddev drush en -y -- block') expect(result.stdout).toBe('Added breadcrumb.\nAdded blocks.\n') }) @@ -729,7 +779,7 @@ describe('drx remove', () => { 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(calls).toEqual(['nuxt$ npm uninstall -- druxt-breadcrumb']) expect(readFileSync(join(root, 'nuxt/nuxt.config.js'), 'utf8')).toBe( NUXT_CONFIG ) @@ -754,15 +804,16 @@ describe('drx remove', () => { }) 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', + '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', ]) const composer = JSON.parse( readFileSync(join(root, 'drupal/composer.json'), 'utf8') ) - expect(composer.extra.patches).toBeUndefined() + // The patches were all that was under `extra`, so it went with them. + expect(composer.extra).toBeUndefined() expect(config(root).modules).toBeUndefined() expect(result.stdout).toBe('Removed breadcrumb.\n') }) @@ -779,7 +830,7 @@ describe('drx remove', () => { const result = await drx(['remove', 'breadcrumb', '--backend'], root, { exec, }) - expect(calls).toEqual(['nuxt$ npm uninstall druxt-breadcrumb']) + 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') @@ -799,12 +850,12 @@ describe('drx remove', () => { [ 'Remove breadcrumb (druxt-breadcrumb)', ' nuxt/', - ' run npm uninstall druxt-breadcrumb', + ' run npm uninstall -- druxt-breadcrumb', " edit Remove 'druxt-breadcrumb' from modules in nuxt.config.js", ' drupal/', - ' run ddev drush pmu -y decoupled_router', + ' 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 remove --no-update-with-dependencies -- drupal/decoupled_router', ' run ddev composer patches-relock', '', 'Nothing was changed: this was a dry run.', @@ -840,8 +891,8 @@ describe('what drx add records', () => { 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', + 'nuxt$ npm install -- druxt-router', + 'drupal$ ddev composer require -- drupal/decoupled_router', ]) expect(result.stderr).toContain('decoupled_router is already enabled.') expect(config(root).modules).toEqual([ @@ -887,7 +938,7 @@ describe('what drx add records', () => { calls.length = 0 await drx(['remove', 'router', '--backend'], root, { exec }) expect(calls).toContain( - 'drupal$ ddev drush pmu -y decoupled_router path_alias' + 'drupal$ ddev drush pmu -y -- decoupled_router path_alias' ) expect(config(root).modules).toBeUndefined() }) @@ -914,9 +965,9 @@ describe('what drx add records', () => { 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', + 'nuxt$ npm uninstall -- druxt-router', + 'drupal$ ddev drush pmu -y -- decoupled_router', + 'drupal$ ddev composer remove --no-update-with-dependencies -- drupal/decoupled_router', ]) expect(config(root).modules).toBeUndefined() }) @@ -949,8 +1000,8 @@ describe('what drx add records', () => { 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 pmu -y -- decoupled_router', + 'drupal$ ddev composer remove --no-update-with-dependencies -- drupal/decoupled_router', ]) 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.' @@ -1035,9 +1086,9 @@ describe('drx remove --backend and what the backend still needs', () => { const result = await drx(['remove', 'router', '--backend'], root, { exec }) expect(result.code).toBe(0) expect(asked).toContain( - 'drupal$ ddev drush pm:uninstall decoupled_router --simulate' + 'drupal$ ddev drush pm:uninstall --simulate -- decoupled_router' ) - expect(calls).toEqual(['nuxt$ npm uninstall druxt-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.' @@ -1076,7 +1127,7 @@ describe('drx remove --backend and what the backend still needs', () => { exec: silent.exec, }) expect(result.code).toBe(0) - expect(silent.calls).toEqual(['nuxt$ npm uninstall druxt-router']) + expect(silent.calls).toEqual(['nuxt$ npm uninstall -- druxt-router']) expect(result.stdout).toBe( [ 'Removed router.', @@ -1112,9 +1163,9 @@ describe('drx remove --backend and what the backend still needs', () => { 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', + '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', ]) expect(config(root).modules).toBeUndefined() }) @@ -1145,7 +1196,7 @@ describe('drx remove --backend and what the backend still needs', () => { exec, }) expect(result.stderr).not.toContain('router needs it') - expect(calls).toContain('drupal$ ddev drush pmu -y decoupled_router') + expect(calls).toContain('drupal$ ddev drush pmu -y -- decoupled_router') }) test('hands what stays to the module that still needs it', async () => { @@ -1160,7 +1211,7 @@ describe('drx remove --backend and what the backend still needs', () => { exec, }) expect(first.code).toBe(0) - expect(calls).toEqual(['nuxt$ npm uninstall druxt-breadcrumb']) + expect(calls).toEqual(['nuxt$ npm uninstall -- druxt-breadcrumb']) expect(first.stderr).toContain('decoupled_router stays: router needs it.') expect(config(root).modules).toEqual([ { @@ -1195,14 +1246,14 @@ describe('drx remove --backend and what the backend still needs', () => { 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', + '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', ]) expect( JSON.parse(readFileSync(join(root, 'drupal/composer.json'), 'utf8')).extra - ).toEqual({}) + ).toBeUndefined() expect(config(root).modules).toBeUndefined() }) }) @@ -1233,12 +1284,12 @@ describe('drx add with no backend to look in', () => { [ 'Add menu (druxt-menu)', ' nuxt/', - ' run npm install druxt-menu', + ' 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 en -y jsonapi_menu_items menu_link_content', + ' composer require -- drupal/jsonapi_menu_items drupal/menu_link_content', + ' 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.', @@ -1309,7 +1360,7 @@ 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', + on: 'composer require -- drupal/decoupled_router', output: 'Your requirements could not be resolved.', }) const result = await drx(['add', 'router', '--json'], root, { exec }) @@ -1319,23 +1370,891 @@ describe('the JSON of a step that failed', () => { error: { code: 'step-failed', message: expect.stringContaining( - 'ddev composer require drupal/decoupled_router failed in drupal/ with exit code 1.' + 'ddev composer require -- drupal/decoupled_router failed in drupal/ with exit code 1.' ), failed: { part: 'drupal', - step: 'ddev composer require drupal/decoupled_router', + step: 'ddev composer require -- drupal/decoupled_router', exitCode: 1, output: 'Your requirements could not be resolved.', }, done: [ - 'nuxt/: npm install druxt-router', + '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 en -y decoupled_router', + 'drupal/: ddev composer require -- drupal/decoupled_router', + '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 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 }], + backend: [backendRecord('alpha')], + }, + { + 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('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')]) + 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', + }, + ], + }, + ], + }, + ] + + 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 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', + ]) + 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 996ab59..f19162d 100644 --- a/packages/cli/test/commands/init-engines.test.ts +++ b/packages/cli/test/commands/init-engines.test.ts @@ -327,6 +327,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/menu.test.ts b/packages/cli/test/commands/menu.test.ts index f74be2b..8aad958 100644 --- a/packages/cli/test/commands/menu.test.ts +++ b/packages/cli/test/commands/menu.test.ts @@ -233,7 +233,7 @@ describe('bare drx in a terminal, inside a project', () => { } ) expect(result.code).toBe(0) - expect(calls[0]).toBe('npm install druxt-blocks') + 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') }) diff --git a/packages/cli/test/exec.test.ts b/packages/cli/test/exec.test.ts index a6e82db..042ac7d 100644 --- a/packages/cli/test/exec.test.ts +++ b/packages/cli/test/exec.test.ts @@ -1,6 +1,8 @@ +import { join } from 'node:path' import { afterEach, describe, expect, test } from 'vitest' -import { runTool } from '../src/exec.js' -import { cleanTmp, tmp } from './helpers/tmp.js' +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) @@ -23,4 +25,155 @@ describe.skipIf(process.platform === 'win32')('runTool', () => { 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/modules/entry.test.ts b/packages/cli/test/modules/entry.test.ts index c78a4af..82840ce 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' @@ -272,6 +275,39 @@ describe('parseModuleRegistry', () => { }, '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}`, + ], + [ + { + 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 }] @@ -280,4 +316,69 @@ describe('parseModuleRegistry', () => { `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', + ])('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 7ba81a5..dfcb69b 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 @@ -130,6 +130,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', () => { const unattended = (argv: string[]) => run(argv, { @@ -196,6 +346,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('an option the command does not have is refused, wherever it is', async () => { const result = await unattended(['module', '--bogus', 'list']) expect(result.code).toBe(1) diff --git a/packages/cli/test/project.test.ts b/packages/cli/test/project.test.ts index 57a083f..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() @@ -185,6 +196,60 @@ describe('loadProjectConfig', () => { { 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 } }) @@ -193,6 +258,16 @@ describe('loadProjectConfig', () => { ) }) + 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) From 6788e69b44368b16d75da69fac9ed950fc9414d2 Mon Sep 17 00:00:00 2001 From: Stuart Clark Date: Thu, 19 Nov 2026 00:17:53 +0000 Subject: [PATCH 4/4] fix(cli): decide what add and remove do from the site, never from one answer `drx remove --backend` could leave modules enabled and write on the record that they were not, and `drx add` took a patch listed in `composer.json` to be applied. - Drupal keeps its container by the set of installed packages, so a set the site has had before brings back an old container. `drush cr` now runs after Composer changes that set, in `add` and in `remove`. - Whether a module is enabled is asked of `drush pm:list` and of the simulated uninstall. When the two differ, or one fails, the module stays, its record is not changed and the commands are printed under "Left to do". - A patch counts as applied when `patches.lock.json` has it. One that only `composer.json` lists is locked again and applied, so a run that failed at `composer patches-relock` is finished by the next with the state of a clean run. Version 2 of the patches plugin does not record applied patches on a package, so a package with a locked patch is installed again. - The record says when `add` required the patches plugin and when it added its `allow-plugins` key, as `patcher`. `remove` takes out each with the last patch, along with the plugin's lock file, and leaves a plugin the site had. A plugin that another module's patch needs moves to the record of that module. - A `composer.constraint` in a registry is checked as a set of Composer version constraints. A word that is not one, such as an option, makes the registry invalid. - Where `add` printed the line of a config it could not edit, the record says so as `byHand`, and `remove` prints the line to take out under "Left to do". It does not say the entry was there before. --- README.md | 16 +- packages/cli/src/adapters/adapter.ts | 29 +- packages/cli/src/adapters/drupal-fields.ts | 82 ++- packages/cli/src/adapters/drupal-modules.ts | 302 +++++++++-- packages/cli/src/adapters/nuxt.ts | 24 +- packages/cli/src/modules/change.ts | 100 +++- packages/cli/src/project.ts | 9 + .../cli/test/adapters/drupal-modules.test.ts | 484 +++++++++++++++++- .../cli/test/adapters/nuxt-modules.test.ts | 51 ++ packages/cli/test/commands/add.test.ts | 268 +++++++++- packages/cli/test/modules/entry.test.ts | 47 ++ 11 files changed, 1316 insertions(+), 96 deletions(-) diff --git a/README.md b/README.md index 363d63e..0f8562e 100644 --- a/README.md +++ b/README.md @@ -142,8 +142,8 @@ 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. -- **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. +- **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. @@ -172,7 +172,9 @@ What it refuses, before it takes any step: **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. 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, and when the site already has the same patch. +**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. @@ -195,6 +197,7 @@ It needs the record and not the registry. A module the registry no longer lists 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. @@ -202,8 +205,11 @@ The backend is left alone unless `--backend` is given. With it, `remove` undoes - 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. @@ -368,9 +374,11 @@ A kind is `nuxt` or `drupal` in this version. | -------------------- | ------------------------------------------------------------------------------------------------------------------------------- | | `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. @@ -488,7 +496,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. A `composer.package` and the `package` of a patch have to be Composer names, as in `vendor/name`. A `composer.constraint` may hold only what a version constraint is made of. 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: diff --git a/packages/cli/src/adapters/adapter.ts b/packages/cli/src/adapters/adapter.ts index 9751789..43f83d0 100644 --- a/packages/cli/src/adapters/adapter.ts +++ b/packages/cli/src/adapters/adapter.ts @@ -92,11 +92,26 @@ export interface FileEdit { 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 }) & { +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. */ @@ -145,6 +160,11 @@ export interface PackageRecord { 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. */ @@ -166,6 +186,13 @@ export interface BackendRecord { /** 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. */ diff --git a/packages/cli/src/adapters/drupal-fields.ts b/packages/cli/src/adapters/drupal-fields.ts index f86318d..972aa47 100644 --- a/packages/cli/src/adapters/drupal-fields.ts +++ b/packages/cli/src/adapters/drupal-fields.ts @@ -15,16 +15,86 @@ 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. It - * starts with a version or an operator, never with a hyphen. + * operators, ranges, stability flags, branch names and references. */ -const CONSTRAINT = /^[A-Za-z0-9^~<>=!*][A-Za-z0-9 .*^~<>=!|,@#/_+-]*$/ +const CONSTRAINT_CHARACTERS = /^[A-Za-z0-9 .*^~<>=!|,@#/_+-]+$/ const CONSTRAINT_RULE = 'must be a Composer version constraint' -/** No name or constraint is anywhere near this long. */ -const LENGTH = 200 +/** 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) @@ -45,7 +115,7 @@ export function moduleProblem(module: BackendModule): FieldProblem | undefined { } if ( composer?.constraint !== undefined && - !matches(composer.constraint, CONSTRAINT) + !(composer.constraint.length <= LENGTH && isConstraint(composer.constraint)) ) { return { field: 'composer.constraint', must: CONSTRAINT_RULE } } diff --git a/packages/cli/src/adapters/drupal-modules.ts b/packages/cli/src/adapters/drupal-modules.ts index 96764e9..58cc6c2 100644 --- a/packages/cli/src/adapters/drupal-modules.ts +++ b/packages/cli/src/adapters/drupal-modules.ts @@ -17,6 +17,8 @@ import { 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> @@ -121,6 +123,76 @@ function withPatches( 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 @@ -165,6 +237,11 @@ interface Installed { 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. */ @@ -178,9 +255,14 @@ async function installedPackages(dir: string): Promise> { 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) } @@ -300,6 +382,7 @@ export async function planBackendAdd( 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[] = [] @@ -307,6 +390,12 @@ export async function planBackendAdd( 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) @@ -372,9 +461,28 @@ export async function planBackendAdd( continue } if (Object.values(patches[target] ?? {}).includes(patch.url)) { - change.notes.push( - `The patch "${patch.description}" is already in composer.json.` - ) + // 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. @@ -413,23 +521,23 @@ export async function planBackendAdd( 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] - if (first) { + 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.description}" 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}.` + `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.description}" needs ${PATCHES_PLUGIN}. Allow the plugin there, or ${without}.` + `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.description}" needs it. Allow the plugin there, or ${without}.` + `composer.json turns ${PATCHES_PLUGIN} off under allow-plugins, and the patch "${first}" needs it. Allow the plugin there, or ${without}.` ) } } @@ -447,33 +555,51 @@ export async function planBackendAdd( } // Each step carries what it will have done, so a run that stops part way // can still say what it did. - const composer = (args: string[], done?: BackendRecord) => + const tool = (name: string) => (args: string[], done?: BackendRecord) => change.steps.push({ - run: { tool: 'composer', args }, + run: { tool: name, args }, ...(done ? { record: done } : {}), }) - - if (record.patches.length > 0) { + 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. - const allow = !hasPlugin - const count = record.patches.length change.steps.push({ edit: { file: 'composer.json', - change: (source) => withPatches(source, record.patches, allow), - summary: `Add ${count} patch${count === 1 ? '' : 'es'} to 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 } } : {}), }, - record: { modules: [], patches: record.patches }, }) - if (!hasPlugin) { - composer([ - 'require', - '--', - `${PATCHES_PLUGIN}:${PATCHES_PLUGIN_CONSTRAINT}`, - ]) - } - composer(['patches-relock']) } + 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 @@ -482,16 +608,19 @@ export async function planBackendAdd( patches: [], }) } - if (record.patches.length > 0 && repatch) composer(['patches-repatch']) + // 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) { - change.steps.push({ - run: { tool: 'drush', args: ['en', '-y', '--', ...toEnable] }, - record: { - modules: record.modules - .filter((module) => module.enabled) - .map((module) => ({ ...module, required: false })), - patches: [], - }, + drush(['en', '-y', '--', ...toEnable], { + modules: record.modules + .filter((module) => module.enabled) + .map((module) => ({ ...module, required: false })), + patches: [], }) } @@ -518,7 +647,7 @@ export async function planBackendAdd( modules.push({ name, enabled: true, required: false }) } } - return { modules, patches: done.patches } + return { ...done, modules } } } return change @@ -543,21 +672,42 @@ export async function planBackendRemove( 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 - if (found === 'absent') { - change.notes.push(`${name} is not enabled, so it is not uninstalled.`) - } else if (found) { - dependents.set(name, found) - } else { + 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: drush pm:uninstall ${name}${required && pkg ? `, then composer remove ${pkg}` : ''}` + `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()] @@ -591,17 +741,14 @@ export async function planBackendRemove( [...installed].some( ([name, { requires }]) => !packages.has(name) && requires.includes(pkg) ) - let listed: Map | undefined | null = null - const enabledNow = async () => { - if (listed === null) listed = ask ? await enabledModules(ask) : undefined - return listed - } const unowned = removing.filter( (module) => !module.enabled && !heldByAnother(module.package as string) ) for (const { name, package: pkg } of unowned) { const enabled = await enabledNow() - if (enabled && !enabled.has(name)) continue + // 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( @@ -656,6 +803,8 @@ export async function planBackendRemove( 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) { @@ -665,6 +814,7 @@ export async function planBackendRemove( 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) @@ -679,16 +829,27 @@ export async function planBackendRemove( } } - const composer = (...args: string[]) => - change.steps.push({ run: { tool: 'composer', args } }) + // 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. - if (kept.length > 0) composer('remove', '--no-update', '--', ...kept) + 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 (kept.length > 0) { + } else if (held.length > 0) { composer('update', '--lock') } if (unpatched.size > 0) { @@ -699,6 +860,40 @@ export async function planBackendRemove( ) 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: [ @@ -707,7 +902,10 @@ export async function planBackendRemove( ...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 } - if (left.modules.length + left.patches.length > 0) change.record = left return change } diff --git a/packages/cli/src/adapters/nuxt.ts b/packages/cli/src/adapters/nuxt.ts index a900611..07cc492 100644 --- a/packages/cli/src/adapters/nuxt.ts +++ b/packages/cli/src/adapters/nuxt.ts @@ -197,6 +197,7 @@ async function addModule( 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') @@ -214,6 +215,7 @@ async function addModule( 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}.`) } @@ -224,7 +226,8 @@ async function addModule( * 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. + * 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, @@ -266,11 +269,24 @@ async function removeModule( ) } } + 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) { - change.notes.push( - `${name} was in modules in ${file} before drx add, so it stays.` - ) + // 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: { diff --git a/packages/cli/src/modules/change.ts b/packages/cli/src/modules/change.ts index c4962ab..4e72261 100644 --- a/packages/cli/src/modules/change.ts +++ b/packages/cli/src/modules/change.ts @@ -1,5 +1,5 @@ import { existsSync } from 'node:fs' -import { readFile, writeFile } from 'node:fs/promises' +import { readFile, rm, writeFile } from 'node:fs/promises' import { join } from 'node:path' import { adapterFor, type KindAdapter } from '../adapters/index.js' import type { @@ -43,6 +43,13 @@ export type PlannedStep = ( 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 @@ -172,7 +179,8 @@ function unusable(project: Project, role: Part['role']): string[] { } const hasAny = (record: BackendRecord) => - record.modules.length + record.patches.length > 0 + 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 { @@ -193,7 +201,16 @@ function mergeBackend(a: BackendRecord, b: BackendRecord): BackendRecord { for (const patch of b.patches) { if (!patches.some((other) => key(other) === key(patch))) patches.push(patch) } - return { modules, patches } + // 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. */ @@ -220,10 +237,13 @@ function withBackend( 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: entry.listed || before?.listed === 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 @@ -266,6 +286,15 @@ function planned( ...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', @@ -393,7 +422,7 @@ export async function planAdd( } const npm = module.npm - const frontend: { path: string; part: PartPlan }[] = [] + 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) @@ -418,7 +447,10 @@ export async function planAdd( absorb(plan, change) const part = frontendPlan(at, change) plan.parts.push(part) - if (change.did) frontend.push({ path: at.part.path, 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) { @@ -486,10 +518,14 @@ export async function planAdd( const now: ModuleRecord = { name: module.name, package: npm, - frontend: frontend.map(({ path, part }) => ({ + 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: [], } @@ -551,16 +587,22 @@ export async function planRemove( 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) ?? { - installed: false, - listed: false, - }) + ? (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 + ? { + did: { + installed: did.installed, + listed: did.listed, + ...(did.byHand ? { byHand: true } : {}), + }, + } + : {}), }) absorb(plan, change) plan.parts.push(frontendPlan(at, change)) @@ -648,6 +690,7 @@ export async function planRemove( record: { modules: entry.modules.filter((held) => !staying.includes(held)), patches: entry.patches.filter((patch) => !stays(patch)), + ...(entry.patcher ? { patcher: entry.patcher } : {}), }, ...(ask ? { ask } : {}), }) @@ -657,10 +700,28 @@ export async function planRemove( // 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, change.record) + heir.record = mergeBackend(heir.record, stay) } else { - left = withBackend(left, path, change.record) + left = withBackend(left, path, stay) } } keep(left) @@ -836,6 +897,17 @@ export async function carryOut( } 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, { diff --git a/packages/cli/src/project.ts b/packages/cli/src/project.ts index 5bb4fbb..52a0fc4 100644 --- a/packages/cli/src/project.ts +++ b/packages/cli/src/project.ts @@ -70,6 +70,7 @@ function moduleRecord(raw: Raw): ModuleRecord { path: String(entry.path), installed: entry.installed === true, listed: entry.listed === true, + ...(entry.byHand === true ? { byHand: true } : {}), })), } : {}), @@ -89,6 +90,14 @@ function moduleRecord(raw: Raw): ModuleRecord { 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, + }, + } + : {}), })), } } diff --git a/packages/cli/test/adapters/drupal-modules.test.ts b/packages/cli/test/adapters/drupal-modules.test.ts index bfb04dd..11929c6 100644 --- a/packages/cli/test/adapters/drupal-modules.test.ts +++ b/packages/cli/test/adapters/drupal-modules.test.ts @@ -33,12 +33,17 @@ const need = ( function answering( enabled: string[] = [], dependents: Record = {}, - paths: 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, @@ -48,7 +53,7 @@ function answering( return { code: 0, output: JSON.stringify(list) } } const name = args.at(-1) as string - if (!enabled.includes(name)) { + if (!cached.includes(name)) { return { code: 1, output: `The following module(s) are not installed: ${name}. No modules to uninstall.`, @@ -134,6 +139,7 @@ describe('adding the backend modules a Druxt module needs', () => { 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({ @@ -169,6 +175,7 @@ describe('adding the backend modules a Druxt module needs', () => { ]) 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([ @@ -216,6 +223,7 @@ describe('adding the backend modules a Druxt module needs', () => { ]) expect(runs(change)).toEqual([ 'composer require -- drupal/decoupled_router', + 'drush cr', ]) expect(change.notes).toEqual([ 'decoupled_router is already enabled.', @@ -331,6 +339,7 @@ describe('telling a core module from a contributed one when the registry does no ) expect(runs(change)).toEqual([ 'composer require -- drupal/decoupled_router', + 'drush cr', 'drush en -y -- jsonapi decoupled_router', ]) }) @@ -412,6 +421,7 @@ describe('the patches a backend module needs', () => { `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([ @@ -455,6 +465,7 @@ describe('the patches a backend module needs', () => { 'composer patches-relock', 'composer require -- drupal/decoupled_router', 'composer patches-repatch', + 'drush cr', 'drush en -y -- decoupled_router', ]) }) @@ -524,16 +535,27 @@ describe('the patches a backend module needs', () => { }) 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', + 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: [ @@ -551,11 +573,168 @@ describe('the patches a backend module needs', () => { ) }) + 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([ @@ -582,6 +761,7 @@ describe('a backend that is not run from here', () => { 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([ @@ -645,14 +825,17 @@ describe('taking backend modules out again', () => { 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' }, @@ -667,6 +850,7 @@ describe('taking backend modules out again', () => { 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([ @@ -769,6 +953,7 @@ describe('taking backend modules out again', () => { const change = await remove(site({}, installed({})), ask, only) expect(runs(change)).toEqual([ 'composer remove --no-update-with-dependencies -- drupal/jsonapi_views', + 'drush cr', ]) }) }) @@ -841,6 +1026,7 @@ describe('taking backend modules out again', () => { 'composer remove --no-update-with-dependencies -- drupal/jsonapi_menu_items', 'composer patches-relock', 'composer reinstall -- drupal/decoupled_router', + 'drush cr', ]) }) @@ -891,6 +1077,286 @@ describe('taking backend modules out again', () => { }) }) + 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 index d07ca33..a3969dd 100644 --- a/packages/cli/test/adapters/nuxt-modules.test.ts +++ b/packages/cli/test/adapters/nuxt-modules.test.ts @@ -341,6 +341,57 @@ describe('a config that cannot be edited safely', () => { "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', () => { diff --git a/packages/cli/test/commands/add.test.ts b/packages/cli/test/commands/add.test.ts index 5bd6478..8245ee9 100644 --- a/packages/cli/test/commands/add.test.ts +++ b/packages/cli/test/commands/add.test.ts @@ -1,5 +1,5 @@ import { createHash } from 'node:crypto' -import { readdirSync, readFileSync, writeFileSync } from 'node:fs' +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' @@ -22,6 +22,9 @@ const PATCH = { 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}`, @@ -148,6 +151,11 @@ interface Backend { 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[] } /** @@ -164,6 +172,7 @@ function tools( 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')) { @@ -181,7 +190,7 @@ function tools( 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)) { + if (!enabled.has(name) || stale.has(name)) { return { code: 1, output: `The following module(s) are not installed: ${name}. No modules to uninstall.`, @@ -195,6 +204,7 @@ function tools( } 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')) @@ -225,6 +235,32 @@ function tools( ) 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 !== '--') @@ -277,6 +313,7 @@ const DRY_RUN = [ ' 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.', @@ -350,6 +387,7 @@ describe('drx add', () => { '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( @@ -391,6 +429,7 @@ describe('drx add', () => { module: 'decoupled_router', }, ], + patcher: ADDED_PLUGIN, }, ], }, @@ -476,6 +515,51 @@ describe('drx add', () => { " 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 }, + ]) }) }) @@ -496,6 +580,7 @@ describe('drx add when the backend is not run from here', () => { ' 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') @@ -619,6 +704,7 @@ describe('drx add when a tool fails', () => { ' 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') ) @@ -640,6 +726,7 @@ describe('drx add when a tool fails', () => { module: 'decoupled_router', }, ], + patcher: ADDED_PLUGIN, }, ], }, @@ -690,6 +777,7 @@ describe('telling core from contributed with the published registry', () => { 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', ]) }) @@ -808,16 +896,68 @@ describe('drx remove', () => { '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() @@ -857,6 +997,10 @@ describe('drx remove', () => { ' 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.', '', @@ -893,6 +1037,7 @@ describe('what drx add records', () => { 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([ @@ -968,6 +1113,7 @@ describe('what drx add records', () => { '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() }) @@ -1002,6 +1148,7 @@ describe('what drx add records', () => { 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.' @@ -1166,6 +1313,7 @@ describe('drx remove --backend and what the backend still needs', () => { '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() }) @@ -1237,6 +1385,7 @@ describe('drx remove --backend and what the backend still needs', () => { module: 'decoupled_router', }, ], + patcher: ADDED_PLUGIN, }, ], }, @@ -1250,10 +1399,13 @@ describe('drx remove --backend and what the backend still needs', () => { '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')).extra - ).toBeUndefined() + JSON.parse(readFileSync(join(root, 'drupal/composer.json'), 'utf8')) + ).toEqual({ require: { 'drupal/core-recommended': '~11' } }) expect(config(root).modules).toBeUndefined() }) }) @@ -1289,6 +1441,7 @@ describe('drx add with no backend to look in', () => { ' 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:', @@ -1384,6 +1537,7 @@ describe('the JSON of a step that failed', () => { ], notDone: [ 'drupal/: ddev composer require -- drupal/decoupled_router', + 'drupal/: ddev drush cr', 'drupal/: ddev drush en -y -- decoupled_router', ], }, @@ -1442,6 +1596,9 @@ const withPlugin = () => 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', } ) @@ -1510,7 +1667,8 @@ describe('several modules in one run', () => { name: 'alpha', package: 'druxt-alpha', frontend: [{ path: 'nuxt', installed: true, listed: true }], - backend: [backendRecord('alpha')], + // The first to need a patch brought the plugin that applies them. + backend: [{ ...backendRecord('alpha'), patcher: ADDED_PLUGIN }], }, { name: 'beta', @@ -1552,6 +1710,59 @@ describe('several modules in one run', () => { 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) @@ -1563,7 +1774,9 @@ describe('several modules in one run', () => { 'drupal$ ddev drush en -y -- mod_alpha', ]) const [alpha, gamma] = json(root, 'drx.config.json').modules - expect(alpha.backend).toEqual([backendRecord('alpha')]) + expect(alpha.backend).toEqual([ + { ...backendRecord('alpha'), patcher: ADDED_PLUGIN }, + ]) expect(gamma.backend).toEqual([]) calls.length = 0 @@ -1620,6 +1833,7 @@ describe('drx add when a tool fails part way', () => { module: 'decoupled_router', }, ], + patcher: ADDED_PLUGIN, }, ], }, @@ -1683,6 +1897,47 @@ describe('drx add when a tool fails part way', () => { 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) @@ -1698,6 +1953,7 @@ describe('drx add when a tool fails part way', () => { '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) diff --git a/packages/cli/test/modules/entry.test.ts b/packages/cli/test/modules/entry.test.ts index 82840ce..afd6946 100644 --- a/packages/cli/test/modules/entry.test.ts +++ b/packages/cli/test/modules/entry.test.ts @@ -296,6 +296,35 @@ describe('parseModuleRegistry', () => { { 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: [ @@ -327,6 +356,24 @@ describe('parseModuleRegistry', () => { '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 = [