From 13526f6dbf98b9abf4fa85beef303a5390539505 Mon Sep 17 00:00:00 2001 From: Stuart Clark Date: Wed, 18 Nov 2026 03:26:25 +0000 Subject: [PATCH 1/6] feat(cli): choose the engine of the backend at init A starter entry can describe the engines that run its backend: local PHP with SQLite, DDEV, Lando, or a Drupal that already exists. - drx init asks for the engine, or takes it from a flag, and checks that the engine's commands are on the machine. - It removes the files of the engines not chosen, writes the backend URL, and records the choice in drx.config.json. - The quickstart entry describes its three engines, and keeps its local tooling whatever engine is chosen. - drx.config.json is read from disk on every load. --- .changeset/first-release-cli.md | 2 +- README.md | 145 +++-- packages/cli/src/commands-on-path.ts | 2 +- packages/cli/src/commands/info.ts | 28 +- packages/cli/src/commands/init.ts | 122 +++- packages/cli/src/engines/backend-url.ts | 37 ++ packages/cli/src/engines/choose.ts | 258 +++++++++ packages/cli/src/engines/ddev.ts | 4 + packages/cli/src/engines/engine.ts | 39 ++ packages/cli/src/engines/files.ts | 74 +++ packages/cli/src/engines/index.ts | 23 + packages/cli/src/engines/lando.ts | 4 + packages/cli/src/engines/none.ts | 14 + packages/cli/src/engines/php.ts | 15 + packages/cli/src/parts.ts | 28 +- packages/cli/src/project.ts | 11 +- packages/cli/src/registry/entry.ts | 150 ++++- packages/cli/src/validate.ts | 12 + .../cli/test/commands/init-engines.test.ts | 545 ++++++++++++++++++ packages/cli/test/commands/init.test.ts | 5 + packages/cli/test/e2e/quickstart.test.ts | 51 ++ packages/cli/test/engines/engines.test.ts | 60 ++ packages/cli/test/engines/files.test.ts | 172 ++++++ packages/cli/test/helpers/engines.ts | 44 ++ packages/cli/test/helpers/server.ts | 2 + packages/cli/test/project.test.ts | 46 ++ packages/cli/test/registry/entry.test.ts | 125 ++++ packages/cli/test/registry/registry.test.ts | 8 +- packages/cli/test/seams.test.ts | 13 + starters/quickstart.json | 61 +- 30 files changed, 2037 insertions(+), 63 deletions(-) create mode 100644 packages/cli/src/engines/backend-url.ts create mode 100644 packages/cli/src/engines/choose.ts create mode 100644 packages/cli/src/engines/ddev.ts create mode 100644 packages/cli/src/engines/engine.ts create mode 100644 packages/cli/src/engines/files.ts create mode 100644 packages/cli/src/engines/index.ts create mode 100644 packages/cli/src/engines/lando.ts create mode 100644 packages/cli/src/engines/none.ts create mode 100644 packages/cli/src/engines/php.ts create mode 100644 packages/cli/test/commands/init-engines.test.ts create mode 100644 packages/cli/test/engines/engines.test.ts create mode 100644 packages/cli/test/engines/files.test.ts create mode 100644 packages/cli/test/helpers/engines.ts diff --git a/.changeset/first-release-cli.md b/.changeset/first-release-cli.md index 5c2d8f8..e47f745 100644 --- a/.changeset/first-release-cli.md +++ b/.changeset/first-release-cli.md @@ -4,7 +4,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. It warns when the commands the starter needs are not on `PATH`. +- `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 info` prints the versions of the CLI, Node and the packages of each part of a project. - The registry holds one starter, `quickstart`, and the `monorepo` layout is the one available. diff --git a/README.md b/README.md index 9a8297a..b59ec10 100644 --- a/README.md +++ b/README.md @@ -35,19 +35,24 @@ You will need Node 22.12 or newer to run the CLI. The site it creates has its ow Creates a site from a starter in a registry, writes `drx.config.json` at its root, and prints what the site needs and what to run next. -| Option | What it does | Default | -| --------------------------- | ----------------------------------------------------------------- | ------------------------------------------------ | -| `[dir]` | The directory to create the site in | Asked for, or the starter's default with `--yes` | -| `--starter ` | The starter to create the site from | The registry's default | -| `--layout ` | `monorepo`, `split` or `workspace`. Only `monorepo` is available. | The starter's layout | -| `--registry ` | A starter registry: a URL, or a name from the user configuration | The public registry | -| `--source ` | Where the Druxt packages come from. Only `npm` is available. | `npm` | -| `--install`, `--no-install` | Install the site's dependencies after creating it, or do not | Asked for, or no | -| `--force` | Write into a directory that exists and is not empty | Refuse | -| `--yes`, `-y` | Accept the default for everything not given, and ask nothing | | -| `--json` | Print the result as JSON on stdout | | - -At a terminal, `init` asks for the directory, the starter when the registry has more than one, the layout, and whether to install. A flag answers each question, so the command runs unattended: +| Option | What it does | Default | +| --------------------------- | ----------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------- | +| `[dir]` | The directory to create the site in | Asked for, or the starter's default with `--yes` | +| `--starter ` | The starter to create the site from | The registry's default | +| `--layout ` | `monorepo`, `split` or `workspace`. Only `monorepo` is available. | The starter's layout | +| `--registry ` | A starter registry: a URL, or a name from the user configuration | The public registry | +| `--source ` | Where the Druxt packages come from. Only `npm` is available. | `npm` | +| `--engine ` | The engine that runs the backend: one of the starter's engines, or `none` for a backend that exists already | Asked for, or the first engine whose commands are installed | +| `--database ` | The database, where the engine offers a choice | Asked for, or the engine's first | +| `--base-url ` | With `--engine none`: the URL of the backend | Asked for | +| `--keep-engines` | Keep the files of the engines that were not chosen | Remove them | +| `--setup` | Run the engine's steps after creating the site. Not available yet. | | +| `--install`, `--no-install` | Install the site's dependencies after creating it, or do not | Asked for, or no | +| `--force` | Write into a directory that exists and is not empty | Refuse | +| `--yes`, `-y` | Accept the default for everything not given, and ask nothing | | +| `--json` | Print the result as JSON on stdout | | + +At a terminal, `init` asks for the directory, the starter when the registry has more than one, the layout, the engine and its database when the starter gives a choice, and whether to install. A flag answers each question, so the command runs unattended: ```bash npx @druxt/cli init my-site --yes --json @@ -55,6 +60,29 @@ npx @druxt/cli init my-site --yes --json With no terminal, `init` uses the defaults and never waits for input. It needs the directory or `--yes`, and fails with a message saying so when it has neither. +#### Engines + +An engine is a way to run the site's backend on your machine. The starter lists the ones it supports, and `none` is always there for a backend that runs somewhere else. For the `quickstart` starter: + +| Engine | Needs on `PATH` | Database | What it is | +| ------- | ----------------- | --------- | -------------------------------------------------------------- | +| `php` | `php`, `composer` | `sqlite` | PHP's built-in server and SQLite, with no containers | +| `ddev` | `ddev` | `mariadb` | [DDEV](https://ddev.readthedocs.io) | +| `lando` | `lando` | `mariadb` | [Lando](https://lando.dev) | +| `none` | | | A Drupal that exists already, at the URL you give `--base-url` | + +- 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. +- 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. + +```bash +npx @druxt/cli init my-site --engine ddev +npx @druxt/cli init my-site --engine none --base-url https://cms.example.com +``` + `--install` runs the install of the package manager the starter declares. For the `quickstart` starter that is `npm install`, which also sets up the Drupal backend when PHP and Composer are present. ### `drx info` @@ -127,7 +155,13 @@ Usage for the CLI or one command, and the version. "source": "npm", "parts": [ { "role": "frontend", "kind": "nuxt", "path": "nuxt" }, - { "role": "backend", "kind": "drupal", "path": "drupal" } + { + "role": "backend", + "kind": "drupal", + "path": "drupal", + "engine": "ddev", + "database": "mariadb" + } ] } ``` @@ -142,6 +176,8 @@ Usage for the CLI or one command, and the version. A kind is `nuxt` or `drupal` in this version. +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 A registry is a URL that answers `/.json` for each starter, in the format [giget](https://github.com/unjs/giget) defines, and `/index.json` with the names. The public registry is the [`starters/`](starters/) directory of this repository. @@ -161,41 +197,82 @@ A registry is a URL that answers `/.json` for each starter, in the format ], "requires": { "node": "16.18.1", - "tools": ["PHP 8.3 or newer with Composer, or DDEV"], - "commands": [["php", "composer"], ["ddev"]] + "tools": ["PHP 8.3 or newer with Composer, or DDEV, or Lando"] }, "maintained": "2026-11-15", "default": true, - "steps": ["npm run setup", "npm run dev"] + "steps": ["npm run setup", "npm run dev"], + "backendUrl": { + "file": ".env", + "template": ".env.example", + "variable": "BASE_URL" + }, + "engines": [ + { + "name": "ddev", + "label": "DDEV", + "commands": ["ddev"], + "databases": ["mariadb"], + "baseUrl": "http://quickstart-druxtsite.ddev.site", + "steps": [ + "npm run setup", + { "run": "ddev start", "dir": "drupal" }, + { "run": "ddev drupal-install", "dir": "drupal" }, + { "run": "ddev druxt-add-consumer", "dir": "drupal" }, + "npm run dev" + ], + "notes": [ + "ddev druxt-add-consumer prints OAUTH_CLIENT_ID. Copy it into .env before npm run dev." + ], + "files": ["drupal/.ddev"] + } + ] } } ``` `name`, `tar`, `defaultDir`, `url`, `subdir` and `headers` are giget's fields. giget ignores the `druxt` object, so the same file works with `npx giget --registry quickstart`. -| Key in `druxt` | What it holds | -| ------------------- | -------------------------------------------------------------------------- | -| `line` | The Druxt release line | -| `layout` | The layout the starter has | -| `parts` | The parts of the starter, as in the project configuration | -| `requires.node` | The Node version the site runs on: a full version, or a major such as `22` | -| `requires.tools` | What else the site needs, each as a phrase to show the user | -| `requires.commands` | Optional. The commands the site needs on `PATH`, as a list of alternatives | -| `maintained` | The date the starter was last checked to work, as `YYYY-MM-DD` | -| `default` | `true` for the starter `init` uses when none is named | -| `steps` | Optional. The commands to run in the new site, in order | +| Key in `druxt` | What it holds | +| ------------------- | ------------------------------------------------------------------------------------------------------------------- | +| `line` | The Druxt release line | +| `layout` | The layout the starter has | +| `parts` | The parts of the starter, as in the project configuration | +| `requires.node` | The Node version the site runs on: a full version, or a major such as `22` | +| `requires.tools` | What else the site needs, each as a phrase to show the user | +| `requires.commands` | Superseded by `engines`. Still read from an entry that has no `engines` | +| `maintained` | The date the starter was last checked to work, as `YYYY-MM-DD` | +| `default` | `true` for the starter `init` uses when none is named | +| `steps` | Optional. The commands to run in the new site, in order, when no engine is chosen and for the `none` engine | +| `engines` | Optional. The ways the backend can be run, described below | +| `backendUrl` | Optional. The `file` and `variable` the starter reads its backend URL from, and a `template` to start the file from | `index.json` is `{ "starters": ["quickstart"] }`. -`requires.commands` is a list of alternatives, and each alternative is a list of command names. The site can be set up when every command of one alternative is on `PATH`. `[["php", "composer"], ["ddev"]]` reads as `php` and `composer`, or `ddev`. A name is a bare command, and an entry with a path or arguments in one is rejected. +An entry in `engines` has: -`init` looks each command up on `PATH` without running it. On Windows it tries the extensions in `PATHEXT`. When no alternative is complete it prints one warning naming the missing commands, and still creates the site: +| Key | What it holds | +| ----------- | ------------------------------------------------------------------------------------------------------------------ | +| `name` | The name `--engine` takes. Lower case. `none` is taken | +| `label` | What the prompt shows, and what `init` prints under "It needs" | +| `commands` | The commands the engine needs on `PATH`, as bare names | +| `databases` | Optional. The databases it can be set up with, the default first | +| `steps` | What to run in the new site, in order. A step is a command, or `{ "run", "dir" }` for a command run in a directory | +| `notes` | Optional. What to do by hand, printed after the steps | +| `files` | Optional. Paths in the starter that the engine needs, relative to its root | +| `baseUrl` | Optional. The URL the engine serves the backend at, when it is fixed | + +`init` removes the `files` of the engines that were not chosen. A path that two engines list is kept when either is chosen, and a directory that holds a kept path loses the rest of its contents. An absolute path, or one that leaves the starter, is refused when the entry is read, and again before anything is removed, which also stops a link in the starter from leading outside the site. + +`init` looks each of the chosen engine's commands up on `PATH` without running it. On Windows it tries the extensions in `PATHEXT`. When one is missing it prints one warning and still creates the site: ```text -Warning: The quickstart starter needs php and composer, or ddev. Not found on PATH: php, composer, ddev. Install the commands of one alternative before you set up the site. +Warning: The ddev engine needs ddev. Not found on PATH: ddev. Install what is missing before you set up the site. ``` -With `--json` the result has a `commands` object: `satisfied`, `alternatives`, `found` and `missing`. It is `null` for an entry with no `requires.commands`, which is not checked. +With `--json` the result has `engine`, `database`, `baseUrl`, `removed`, `notes` and a `commands` object with `satisfied`, `alternatives`, `found` and `missing`. + +`requires.commands`, a list of alternatives such as `[["php", "composer"], ["ddev"]]`, is what an entry used before `engines`. It is read only from an entry with no `engines`, and warns when no alternative is complete. `init` checks an entry before it downloads anything, and fails with a message naming the field that is wrong. It warns when the starter was last maintained more than a year ago, and when the running Node is not the one the starter needs. @@ -244,7 +321,9 @@ The copy is kept in `~/.cache/drx`, or under `XDG_CACHE_HOME` when that is set. - `drx module add`, `drx module remove` and `drx module configure`. The commands exist and fail with a message. - Making a wrapper component and upgrading a site. - Kinds other than `nuxt` and `drupal`. -- A version check of the commands a starter needs. `init` checks that `php` is on `PATH`, not that it is 8.3 or newer. +- `init --setup`, which would run the engine's steps. The flag exists and fails with a message, and `init` prints the steps. +- A database other than the one each quickstart engine is set up for. `--database` records the choice and does not change a file. +- A version check of the commands an engine needs. `init` checks that `php` is on `PATH`, not that it is 8.3 or newer. - The same check in `drx info`. A project does not record what its starter requires, so `info` would have to read the registry again. - A published public registry. Until this repository is public, `init` reads the copy in the package. diff --git a/packages/cli/src/commands-on-path.ts b/packages/cli/src/commands-on-path.ts index 445d21b..8dab810 100644 --- a/packages/cli/src/commands-on-path.ts +++ b/packages/cli/src/commands-on-path.ts @@ -95,7 +95,7 @@ export function checkCommands( } } -/** The alternatives as a phrase: "php and composer, or ddev". */ +/** The alternatives as a phrase: "one and two, or three". */ export function describeAlternatives(alternatives: string[][]): string { return alternatives .map((commands) => diff --git a/packages/cli/src/commands/info.ts b/packages/cli/src/commands/info.ts index 8cf8775..2c2f720 100644 --- a/packages/cli/src/commands/info.ts +++ b/packages/cli/src/commands/info.ts @@ -47,23 +47,39 @@ async function reportPart(root: string, part: Part): Promise { } function partLines(part: PartReport): string[] { - const heading = `${part.role} ${part.kind} ${part.path}/` + const heading = [ + `${part.role} ${part.kind} ${part.path}/`, + ...columns( + [ + ...(part.engine ? [['Engine', part.engine]] : []), + ...(part.database ? [['Database', part.database]] : []), + ...(part.baseUrl ? [['Backend URL', part.baseUrl]] : []), + ], + ' ' + ), + ] if (!adapterFor(part.kind)) { - return [heading, ` This version has no adapter for the ${part.kind} kind.`] + return [ + ...heading, + ` This version has no adapter for the ${part.kind} kind.`, + ] } - if (!part.exists) return [heading, ' The directory does not exist.'] + if (!part.exists) return [...heading, ' The directory does not exist.'] if (!part.detected) { - return [heading, ` The directory does not look like a ${part.kind} part.`] + return [ + ...heading, + ` The directory does not look like a ${part.kind} part.`, + ] } if (part.packages.length === 0) { - return [heading, ' No packages to report.'] + return [...heading, ' No packages to report.'] } const rows = part.packages.map((entry) => [ entry.name, entry.range ?? '', entry.installed ? `installed ${entry.installed}` : 'not installed', ]) - return [heading, ...columns(rows, ' ')] + return [...heading, ...columns(rows, ' ')] } function text(report: InfoReport, cwd: string): string { diff --git a/packages/cli/src/commands/init.ts b/packages/cli/src/commands/init.ts index 8e7f7ae..17c3e1b 100644 --- a/packages/cli/src/commands/init.ts +++ b/packages/cli/src/commands/init.ts @@ -8,6 +8,15 @@ import { type CommandCheck, } from '../commands-on-path.js' import type { CliContext } from '../context.js' +import { writeBackendUrl } from '../engines/backend-url.js' +import { + assertBaseUrl, + chooseEngine, + missingCommandsWarning, + stepLines, + type EngineChoice, +} from '../engines/choose.js' +import { removeEngineFiles } from '../engines/files.js' import { DrxError } from '../errors.js' import { assertLayoutAvailable, @@ -62,6 +71,31 @@ const args = { valueHint: 'name', description: `Where the Druxt packages come from (default: ${DEFAULT_SOURCE})`, }, + engine: { + type: 'string', + valueHint: 'name', + description: + 'How the backend runs: an engine of the starter, or none for a backend that exists already', + }, + database: { + type: 'string', + valueHint: 'name', + description: 'The database, where the engine offers a choice', + }, + 'base-url': { + type: 'string', + valueHint: 'url', + description: 'With --engine none: the URL of the backend', + }, + 'keep-engines': { + type: 'boolean', + description: 'Keep the files of the engines that were not chosen', + }, + setup: { + type: 'boolean', + description: + 'Run the steps of the engine after creating the site (not available yet)', + }, install: { type: 'boolean', description: 'Install the dependencies of the site after creating it', @@ -88,6 +122,11 @@ interface InitOptions { layout?: Layout registry?: string source?: string + engine?: string + database?: string + baseUrl?: string + keepEngines: boolean + setup: boolean install?: boolean force: boolean yes: boolean @@ -188,6 +227,7 @@ function nodeSatisfies(running: string, needed: string): boolean { function warnAboutStarter( entry: StarterEntry, + engine: EngineChoice | undefined, target: string, context: CliContext, output: Output @@ -212,6 +252,19 @@ function warnAboutStarter( } } + if (engine) { + // The chosen engine's commands are the ones that matter. An engine with + // none, such as a backend that exists already, has nothing to check. + if (engine.commands.length === 0) return null + const check = checkCommands([engine.commands], context.findCommand) + if (!check.satisfied) { + output.warn( + missingCommandsWarning(engine.name, engine.commands, check.missing) + ) + } + return check + } + if (!requires.commands) return null const commands = checkCommands(requires.commands, context.findCommand) if (!commands.satisfied) { @@ -239,6 +292,14 @@ async function runInit( ) } + if (options.setup) { + throw new DrxError( + 'not-available', + '--setup is not available yet. init prints the steps for you to run.' + ) + } + if (options.baseUrl) assertBaseUrl(options.baseUrl) + // Everything that can fail without the network is checked before it is used. const userConfig = await loadUserConfig(context.env) const source = resolveSource(options.source ?? DEFAULT_SOURCE, userConfig) @@ -264,6 +325,7 @@ async function runInit( const entry = await chooseStarter(registry, options, context, canAsk) const layout = await chooseLayout(entry, options, context, canAsk) + const engine = await chooseEngine(entry, options, context, canAsk) const defaultDir = entry.defaultDir ?? entry.name const dir = @@ -312,15 +374,49 @@ async function runInit( ) } + let removed: string[] = [] + if (engine && !options.keepEngines) { + removed = await removeEngineFiles(target, engine.remove, engine.keep) + if (removed.length > 0) { + output.note( + `Removed the files of the engines not chosen: ${removed.join(', ')}.` + ) + } + } + if (engine?.writeUrl) { + const where = entry.druxt.backendUrl + if (where) { + await writeBackendUrl(target, where, engine.writeUrl) + output.note( + `Wrote ${where.variable}=${engine.writeUrl} to ${where.file}.` + ) + } else if (engine.baseUrl) { + output.warn( + `The ${entry.name} starter does not say where it reads its backend URL from. Point it at ${engine.baseUrl} yourself.` + ) + } + } + const config: ProjectConfig = { layout, line: entry.druxt.line, starter: entry.name, source: source.name, - parts: entry.druxt.parts, + // The choice is recorded on every backend part, for the commands that + // will run tools in it. + parts: entry.druxt.parts.map((part) => + engine && part.role === 'backend' + ? { + ...part, + engine: engine.name, + ...(engine.database ? { database: engine.database } : {}), + ...(engine.baseUrl ? { baseUrl: engine.baseUrl } : {}), + } + : part + ), } await writeProjectConfig(target, config) - const commands = warnAboutStarter(entry, target, context, output) + const commands = warnAboutStarter(entry, engine, target, context, output) if (install) { output.note('Installing dependencies.') @@ -339,9 +435,11 @@ async function runInit( const inside = fromCwd !== '' && !fromCwd.startsWith('..') const next = [ `cd ${inside && !isAbsolute(fromCwd) ? fromCwd : target}`, - ...(entry.druxt.steps ?? []), + ...stepLines(engine ? engine.steps : (entry.druxt.steps ?? [])), ] const { requires } = entry.druxt + const needs = engine ? [engine.label] : requires.tools + const notes = engine?.notes ?? [] output.result( { @@ -351,18 +449,26 @@ async function runInit( ...config, installed: install, requires, + engine: engine?.name ?? null, + database: engine?.database ?? null, + baseUrl: engine?.baseUrl ?? null, + removed, commands, next, + notes, }, [ `Created a Druxt site in ${target} from the ${entry.name} starter.`, '', 'It needs:', ` Node ${requires.node}`, - ...requires.tools.map((tool) => ` ${tool}`), + ...needs.map((tool) => ` ${tool}`), '', 'Next:', ...next.map((step) => ` ${step}`), + ...(notes.length > 0 + ? ['', 'Note:', ...notes.map((note) => ` ${note}`)] + : []), ].join('\n') ) } @@ -379,7 +485,15 @@ export function initCommand(context: CliContext) { const options: InitOptions = { force: parsed.force === true, yes: parsed.yes === true, + keepEngines: parsed['keep-engines'] === true, + setup: parsed.setup === true, } + const engine = valueOf('engine', parsed.engine) + const database = valueOf('database', parsed.database) + const baseUrl = valueOf('base-url', parsed['base-url']) + if (engine) options.engine = engine + if (database) options.database = database + if (baseUrl) options.baseUrl = baseUrl const dir = valueOf('dir', parsed.dir) const starter = valueOf('starter', parsed.starter) const registry = valueOf('registry', parsed.registry) diff --git a/packages/cli/src/engines/backend-url.ts b/packages/cli/src/engines/backend-url.ts new file mode 100644 index 0000000..2072882 --- /dev/null +++ b/packages/cli/src/engines/backend-url.ts @@ -0,0 +1,37 @@ +import { mkdir, readFile, writeFile } from 'node:fs/promises' +import { dirname, join } from 'node:path' +import type { BackendUrlTarget } from '../registry/entry.js' + +async function read(file: string): Promise { + try { + return await readFile(file, 'utf8') + } catch { + return undefined + } +} + +/** + * Writes the URL of the backend where the starter reads it: one variable in + * a file of `NAME=value` lines. The file is started from the starter's + * template when it does not exist, and every other line is left as it is. + */ +export async function writeBackendUrl( + root: string, + target: BackendUrlTarget, + url: string +): Promise { + const file = join(root, target.file) + const start = + (await read(file)) ?? + (target.template ? await read(join(root, target.template)) : undefined) ?? + '' + + const line = `${target.variable}=${url}` + const assignment = new RegExp(`^${target.variable}=.*$`, 'm') + const content = assignment.test(start) + ? start.replace(assignment, line) + : `${start}${start === '' || start.endsWith('\n') ? '' : '\n'}${line}\n` + + await mkdir(dirname(file), { recursive: true }) + await writeFile(file, content) +} diff --git a/packages/cli/src/engines/choose.ts b/packages/cli/src/engines/choose.ts new file mode 100644 index 0000000..45c9011 --- /dev/null +++ b/packages/cli/src/engines/choose.ts @@ -0,0 +1,258 @@ +import { checkCommands, describeAlternatives } from '../commands-on-path.js' +import type { Choice, CliContext } from '../context.js' +import { DrxError } from '../errors.js' +import { + EXISTING_BACKEND, + type EngineStep, + type StarterEngine, + type StarterEntry, +} from '../registry/entry.js' +import { isHttpUrl } from '../validate.js' + +/** What the flags say about the engine. Each is undefined when not given. */ +export interface EngineOptions { + engine?: string + database?: string + baseUrl?: string +} + +/** The engine a site is created with, and what follows from the choice. */ +export interface EngineChoice { + name: string + /** What the site needs for this engine, as a phrase. */ + label: string + /** The commands the engine needs on PATH. */ + commands: string[] + database?: string + /** The URL of a backend that exists already. Recorded in the project. */ + baseUrl?: string + /** The URL to write where the starter reads its backend URL from. */ + writeUrl?: string + steps: EngineStep[] + notes: string[] + /** The paths the chosen engine needs. */ + keep: string[] + /** The paths of the engines that were not chosen. */ + remove: string[] +} + +/** Fails unless the value of `--base-url` is a URL a site can fetch from. */ +export function assertBaseUrl(value: string): void { + if (!isHttpUrl(value)) { + throw new DrxError( + 'usage', + `--base-url must be an http or https URL: "${value}".` + ) + } +} + +const missingFrom = (engine: StarterEngine, context: CliContext) => + checkCommands([engine.commands], context.findCommand).missing + +async function chooseName( + entry: StarterEntry, + engines: StarterEngine[], + options: EngineOptions, + context: CliContext, + canAsk: boolean +): Promise { + const names = [...engines.map(({ name }) => name), EXISTING_BACKEND] + if (options.engine) { + if (!names.includes(options.engine)) { + throw new DrxError( + 'usage', + `The ${entry.name} starter has no engine named "${options.engine}". It offers: ${names.join(', ')}.` + ) + } + return options.engine + } + + const missing = new Map( + engines.map((engine) => [engine.name, missingFrom(engine, context)]) + ) + const present = engines.filter(({ name }) => missing.get(name)?.length === 0) + const absent = engines.filter((engine) => !present.includes(engine)) + // The first engine that can run on this machine, or the starter's first. + const fallback = (present[0] ?? engines[0]) as StarterEngine + if (!canAsk) return fallback.name + + const choices: Choice[] = [ + ...present.map(({ name, label }) => ({ value: name, label })), + ...absent.map(({ name, label }) => ({ + value: name, + label, + hint: `not installed: ${missing.get(name)?.join(', ')}`, + })), + { + value: EXISTING_BACKEND, + label: 'None: use a backend that exists already', + }, + ] + return context.prompter.select({ + message: 'How should the backend run?', + choices, + initial: fallback.name, + }) +} + +async function chooseDatabase( + entry: StarterEntry, + engine: StarterEngine, + options: EngineOptions, + context: CliContext, + canAsk: boolean +): Promise { + const databases = engine.databases + const of = `The ${engine.name} engine of the ${entry.name} starter` + if (!databases) { + if (options.database) { + throw new DrxError('usage', `${of} offers no choice of database.`) + } + return undefined + } + if (options.database) { + if (!databases.includes(options.database)) { + throw new DrxError( + 'usage', + `${of} has no database named "${options.database}". It offers: ${databases.join(', ')}.` + ) + } + return options.database + } + if (canAsk && databases.length > 1) { + return context.prompter.select({ + message: 'Which database?', + choices: databases.map((name) => ({ value: name, label: name })), + initial: databases[0] as string, + }) + } + return databases[0] +} + +async function existingBackend( + entry: StarterEntry, + engines: StarterEngine[], + options: EngineOptions, + context: CliContext, + canAsk: boolean +): Promise { + if (options.database) { + throw new DrxError( + 'usage', + `--database does not go with --engine ${EXISTING_BACKEND}. The backend has its database already.` + ) + } + let baseUrl = options.baseUrl + if (!baseUrl) { + if (!canAsk) { + throw new DrxError( + 'usage', + `--engine ${EXISTING_BACKEND} needs --base-url, the URL of the backend that exists already.` + ) + } + baseUrl = await context.prompter.text({ + message: 'What is the URL of the backend?', + }) + assertBaseUrl(baseUrl) + } + return { + name: EXISTING_BACKEND, + label: `A backend that exists already, at ${baseUrl}`, + commands: [], + baseUrl, + writeUrl: baseUrl, + steps: entry.druxt.steps ?? [], + notes: [], + keep: [], + remove: engines.flatMap((engine) => engine.files ?? []), + } +} + +/** + * Settles which engine the site is created with: the flag, the answer to a + * prompt, or the first engine of the starter whose commands are on PATH. + * + * Undefined for a starter that lists no engines when none was asked for. The + * engine for a backend that exists already is offered by every starter. + */ +export async function chooseEngine( + entry: StarterEntry, + options: EngineOptions, + context: CliContext, + canAsk: boolean +): Promise { + const engines = entry.druxt.engines ?? [] + if (engines.length === 0 && !options.engine) { + for (const [flag, value] of [ + ['--database', options.database], + ['--base-url', options.baseUrl], + ]) { + if (value) { + throw new DrxError( + 'usage', + `${flag} goes with --engine, and the ${entry.name} starter lists no engines. Only --engine ${EXISTING_BACKEND} can be used with it.` + ) + } + } + return undefined + } + + const name = await chooseName(entry, engines, options, context, canAsk) + if (name === EXISTING_BACKEND) { + return existingBackend(entry, engines, options, context, canAsk) + } + + const engine = engines.find((candidate) => candidate.name === name) + if (!engine) throw new Error(`No engine named ${name}.`) + if (options.baseUrl) { + throw new DrxError( + 'usage', + `--base-url goes with --engine ${EXISTING_BACKEND}. The ${name} engine serves the backend itself.` + ) + } + const database = await chooseDatabase(entry, engine, options, context, canAsk) + return { + name, + label: engine.label, + commands: engine.commands, + ...(database ? { database } : {}), + ...(engine.baseUrl ? { writeUrl: engine.baseUrl } : {}), + steps: engine.steps, + notes: engine.notes ?? [], + keep: engine.files ?? [], + remove: engines + .filter((other) => other !== engine) + .flatMap((other) => other.files ?? []), + } +} + +/** + * The steps as lines to type, starting in the site's root: a `cd` wherever + * the directory changes, and one back to the root when a step returns there. + */ +export function stepLines(steps: EngineStep[]): string[] { + const lines: string[] = [] + let here = '' + for (const step of steps) { + const dir = typeof step === 'string' ? '' : step.dir.replace(/\/+$/, '') + if (dir !== here) { + const back = here + .split('/') + .filter(Boolean) + .map(() => '..') + lines.push(`cd ${[...back, dir].filter(Boolean).join('/')}`) + here = dir + } + lines.push(typeof step === 'string' ? step : step.run) + } + return lines +} + +/** The warning for an engine whose commands are not all on PATH. */ +export function missingCommandsWarning( + name: string, + commands: string[], + missing: string[] +): string { + return `The ${name} engine needs ${describeAlternatives([commands])}. Not found on PATH: ${missing.join(', ')}. Install what is missing before you set up the site.` +} diff --git a/packages/cli/src/engines/ddev.ts b/packages/cli/src/engines/ddev.ts new file mode 100644 index 0000000..2edad36 --- /dev/null +++ b/packages/cli/src/engines/ddev.ts @@ -0,0 +1,4 @@ +import { wrappingEngine } from './engine.js' + +/** DDEV runs a tool in its web container: `ddev composer`, `ddev drush`. */ +export const ddevEngine = wrappingEngine('ddev') diff --git a/packages/cli/src/engines/engine.ts b/packages/cli/src/engines/engine.ts new file mode 100644 index 0000000..5a70bfc --- /dev/null +++ b/packages/cli/src/engines/engine.ts @@ -0,0 +1,39 @@ +import type { Part } from '../parts.js' + +/** A command line, and the directory to run it in, from the project root. */ +export interface EngineCommand { + command: string + args: string[] + cwd: string +} + +/** + * How the tools of a backend part are run when the part is run a certain + * way. A command that changes the backend asks the part's engine for the + * command line, and never names an engine itself. A new engine is a new file + * in this directory and a line in index.ts. + */ +export interface EngineAdapter { + /** The value a part's `engine` holds. */ + readonly name: string + /** + * The command line that runs a backend tool, such as its package manager, + * with the given arguments. + */ + run(part: Part, command: string, args: string[]): EngineCommand +} + +/** + * An engine that runs every tool as an argument of its own command, in the + * part's directory, as container tools do. + */ +export function wrappingEngine(name: string): EngineAdapter { + return { + name, + run: (part, command, args) => ({ + command: name, + args: [command, ...args], + cwd: part.path, + }), + } +} diff --git a/packages/cli/src/engines/files.ts b/packages/cli/src/engines/files.ts new file mode 100644 index 0000000..b5c973f --- /dev/null +++ b/packages/cli/src/engines/files.ts @@ -0,0 +1,74 @@ +import { existsSync, lstatSync, realpathSync } from 'node:fs' +import { readdir, rm } from 'node:fs/promises' +import { dirname, join, sep } from 'node:path' +import { DrxError } from '../errors.js' +import { isInsidePath } from '../validate.js' + +/** A relative path with forward slashes and no `.` segments. */ +function normalise(path: string): string { + return path + .split(/[\\/]/) + .filter((segment) => segment !== '' && segment !== '.') + .join('/') +} + +/** + * Fails unless the path names something inside the site, by its spelling + * and by where the directory holding it is on disk. The second check is for + * a link in the starter that points out of the site. + */ +function assertInsideSite(root: string, path: string): void { + const refuse = () => + new DrxError( + 'invalid-entry', + `Refusing to remove ${path}: it is not inside the site.` + ) + if (!isInsidePath(path)) throw refuse() + + const realRoot = realpathSync(root) + let holder = dirname(join(root, normalise(path))) + while (!existsSync(holder)) holder = dirname(holder) + const realHolder = realpathSync(holder) + if (realHolder !== realRoot && !realHolder.startsWith(realRoot + sep)) { + throw refuse() + } +} + +/** + * Removes the paths of the engines that were not chosen, and returns what it + * removed. A path in `keep`, or inside one, stays. A directory that holds a + * kept path loses everything else in it. + * + * Every path is checked before anything is removed, so a bad one removes + * nothing. A link is removed as a link, never followed. + */ +export async function removeEngineFiles( + root: string, + remove: string[], + keep: string[] +): Promise { + for (const path of remove) assertInsideSite(root, path) + + const kept = keep.map(normalise) + const isKept = (path: string) => + kept.some((other) => path === other || path.startsWith(`${other}/`)) + const holdsKept = (path: string) => + kept.some((other) => other.startsWith(`${path}/`)) + + const removed: string[] = [] + const visit = async (path: string): Promise => { + const file = join(root, path) + const stat = lstatSync(file, { throwIfNoEntry: false }) + if (!stat || isKept(path)) return + if (holdsKept(path) && stat.isDirectory()) { + for (const child of (await readdir(file)).sort()) { + await visit(`${path}/${child}`) + } + return + } + await rm(file, { recursive: true, force: true }) + removed.push(path) + } + for (const path of remove) await visit(normalise(path)) + return removed +} diff --git a/packages/cli/src/engines/index.ts b/packages/cli/src/engines/index.ts new file mode 100644 index 0000000..0a6ac35 --- /dev/null +++ b/packages/cli/src/engines/index.ts @@ -0,0 +1,23 @@ +import { ddevEngine } from './ddev.js' +import type { EngineAdapter } from './engine.js' +import { landoEngine } from './lando.js' +import { noEngine } from './none.js' +import { phpEngine } from './php.js' + +export type { EngineAdapter, EngineCommand } from './engine.js' + +/** Every engine this version can run tools through. */ +const ENGINES: readonly EngineAdapter[] = [ + phpEngine, + ddevEngine, + landoEngine, + noEngine, +] + +export function engineFor(name: string): EngineAdapter | undefined { + return ENGINES.find((engine) => engine.name === name) +} + +export function knownEngines(): string[] { + return ENGINES.map((engine) => engine.name) +} diff --git a/packages/cli/src/engines/lando.ts b/packages/cli/src/engines/lando.ts new file mode 100644 index 0000000..560a1a9 --- /dev/null +++ b/packages/cli/src/engines/lando.ts @@ -0,0 +1,4 @@ +import { wrappingEngine } from './engine.js' + +/** Lando runs a tool through its tooling: `lando composer`, `lando drush`. */ +export const landoEngine = wrappingEngine('lando') diff --git a/packages/cli/src/engines/none.ts b/packages/cli/src/engines/none.ts new file mode 100644 index 0000000..7613149 --- /dev/null +++ b/packages/cli/src/engines/none.ts @@ -0,0 +1,14 @@ +import { DrxError } from '../errors.js' +import { EXISTING_BACKEND } from '../registry/entry.js' +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, + run(_part, command, args) { + throw new DrxError( + 'not-available', + `The backend of this project is not on this machine, so ${command} cannot be run from here. Run "${[command, ...args].join(' ')}" where the backend is.` + ) + }, +} diff --git a/packages/cli/src/engines/php.ts b/packages/cli/src/engines/php.ts new file mode 100644 index 0000000..2f48341 --- /dev/null +++ b/packages/cli/src/engines/php.ts @@ -0,0 +1,15 @@ +import type { EngineAdapter } from './engine.js' + +/** + * PHP on the machine itself. Composer is on PATH. Every other tool is one + * Composer installed for the project, so it is run from Composer's bin + * directory and needs no global install. + */ +export const phpEngine: EngineAdapter = { + name: 'php', + run: (part, command, args) => ({ + command: command === 'composer' ? command : `vendor/bin/${command}`, + args, + cwd: part.path, + }), +} diff --git a/packages/cli/src/parts.ts b/packages/cli/src/parts.ts index 881c2bf..5903428 100644 --- a/packages/cli/src/parts.ts +++ b/packages/cli/src/parts.ts @@ -1,4 +1,9 @@ -import { isNonEmptyString, isRecord } from './validate.js' +import { + isHttpUrl, + isInsidePath, + isNonEmptyString, + isRecord, +} from './validate.js' export const ROLES = ['frontend', 'backend'] as const export type Role = (typeof ROLES)[number] @@ -13,13 +18,12 @@ export interface Part { kind: string /** Relative to the project root, with forward slashes. */ path: string -} - -/** True for a path that stays inside the directory it is resolved against. */ -function isInsidePath(value: unknown): value is string { - if (!isNonEmptyString(value)) return false - if (value.startsWith('/') || /^[a-z]:/i.test(value)) return false - return !value.split(/[\\/]/).includes('..') + /** How a backend part is run on this machine, by the name of its engine. */ + engine?: string + /** The database the engine was set up with, where it offers a choice. */ + database?: string + /** The URL of a backend that is not run on this machine. */ + baseUrl?: string } /** @@ -45,6 +49,14 @@ export function partsProblem( if (!isInsidePath(part.path)) { return `${at}.path must be a relative path inside the project` } + for (const key of ['engine', 'database']) { + if (part[key] !== undefined && !isNonEmptyString(part[key])) { + return `${at}.${key} must be a non-empty string` + } + } + if (part.baseUrl !== undefined && !isHttpUrl(part.baseUrl)) { + return `${at}.baseUrl must be an http or https URL` + } } return undefined } diff --git a/packages/cli/src/project.ts b/packages/cli/src/project.ts index bfd0059..d91ec5f 100644 --- a/packages/cli/src/project.ts +++ b/packages/cli/src/project.ts @@ -1,5 +1,6 @@ -import { existsSync } from 'node:fs' +import { existsSync, realpathSync } from 'node:fs' import { writeFile } from 'node:fs/promises' +import { createRequire } from 'node:module' import { dirname, join, resolve } from 'node:path' import { loadConfig } from 'c12' import { DrxError } from './errors.js' @@ -7,6 +8,8 @@ import { isLayout, LAYOUTS, type Layout } from './layouts.js' import { partsProblem, type Part } from './parts.js' import { isNonEmptyString } from './validate.js' +const nodeRequire = createRequire(import.meta.url) + /** The file at a project's root that says how the project is laid out. */ export const CONFIG_FILE = 'drx.config.json' @@ -63,6 +66,12 @@ export async function loadProjectConfig(root: string): Promise { const file = join(root, CONFIG_FILE) let config: Record try { + // c12 loads a JSON file through Node's require, which keeps the first + // read for the life of the process. Forgetting it reads the file as it is + // now, which matters to anything that calls the CLI more than once. + for (const cached of [file, realpathSync(file)]) { + delete nodeRequire.cache[cached] + } // The file is read on its own: no rc file, no package.json key, no // environment overrides and no `extends`, so what is in it is all there is. const loaded = await loadConfig>({ diff --git a/packages/cli/src/registry/entry.ts b/packages/cli/src/registry/entry.ts index 42ce6d0..9d95ce3 100644 --- a/packages/cli/src/registry/entry.ts +++ b/packages/cli/src/registry/entry.ts @@ -4,6 +4,7 @@ import { isLayout, LAYOUTS, type Layout } from '../layouts.js' import { partsProblem, type Part } from '../parts.js' import { isHttpUrl, + isInsidePath, isNonEmptyString, isRecord, isStringArray, @@ -22,6 +23,47 @@ export interface StarterRequirements { commands?: string[][] } +/** A step of an engine: a command at the root, or one run in a directory. */ +export type EngineStep = string | { run: string; dir: string } + +/** + * One way a starter's backend can be run. The name is data: the CLI has an + * engine adapter for the names it can run tools through, and needs none to + * create a site. + */ +export interface StarterEngine { + name: string + /** What the user reads in a prompt and under "It needs". */ + label: string + /** The commands the engine needs on PATH. */ + commands: string[] + /** The databases it can be set up with, the default first. */ + databases?: string[] + /** What to run in the new site, in order. */ + steps: EngineStep[] + /** What to do by hand, printed after the steps. */ + notes?: string[] + /** + * Paths in the starter that this engine needs, removed when another engine + * is chosen. A path two engines list is kept when either is chosen. + */ + files?: string[] + /** The URL the engine serves the backend at, when it is fixed. */ + baseUrl?: string +} + +/** Where a starter reads the URL of its backend from. */ +export interface BackendUrlTarget { + /** A file of `NAME=value` lines, relative to the starter's root. */ + file: string + variable: string + /** A file to start from when `file` does not exist. */ + template?: string +} + +/** The engine every starter has: a backend that exists somewhere else. */ +export const EXISTING_BACKEND = 'none' + /** What Druxt adds to a giget registry entry. giget ignores the key. */ export interface StarterDetails { /** The Druxt release line, such as `0.x`. */ @@ -33,8 +75,14 @@ export interface StarterDetails { maintained: string /** True for the starter `init` uses when none is named. */ default: boolean - /** Commands to run in the new site, in order. */ + /** + * Commands to run in the new site, in order, when no engine is chosen or + * the backend exists already. + */ steps?: string[] + /** The ways the backend can be run. Supersedes `requires.commands`. */ + engines?: StarterEngine[] + backendUrl?: BackendUrlTarget } /** A giget registry entry with the `druxt` object `init` needs. */ @@ -76,6 +124,104 @@ function commandsProblem(value: unknown): string | undefined { return undefined } +const INSIDE = 'must be a relative path inside the starter' + +function stepProblem(step: unknown, at: string): string | undefined { + if (typeof step === 'string') { + return step.trim() === '' + ? `${at} must be a command, or an object with run and dir` + : undefined + } + if (!isRecord(step)) + return `${at} must be a command, or an object with run and dir` + if (!isNonEmptyString(step.run)) return `${at}.run must be a non-empty string` + if (!isInsidePath(step.dir)) return `${at}.dir ${INSIDE}` + return undefined +} + +/** The first problem with `druxt.engines`, or undefined. */ +function enginesProblem(value: unknown): string | undefined { + const label = 'druxt.engines' + if (value === undefined) return undefined + if (!Array.isArray(value) || value.length === 0) { + return `${label} must be a non-empty array` + } + const names = new Set() + for (const [index, engine] of value.entries()) { + const at = `${label}[${index}]` + if (!isRecord(engine)) return `${at} must be an object` + + const name = engine.name + if (typeof name !== 'string' || !/^[a-z0-9][a-z0-9-]*$/.test(name)) { + return `${at}.name must be a lower-case name` + } + if (name === EXISTING_BACKEND) { + return `${at}.name cannot be ${EXISTING_BACKEND}, which every starter has` + } + if (names.has(name)) return `${at}.name repeats the name ${name}` + names.add(name) + + if (!isNonEmptyString(engine.label)) { + return `${at}.label must be a non-empty string` + } + if (!Array.isArray(engine.commands)) { + return `${at}.commands must be an array of command names` + } + for (const [position, command] of engine.commands.entries()) { + if (!isCommandName(command)) { + return `${at}.commands[${position}] must be a command name with no path or spaces` + } + } + const databases = engine.databases + if ( + databases !== undefined && + (!Array.isArray(databases) || + databases.length === 0 || + !databases.every(isNonEmptyString)) + ) { + return `${at}.databases must be a non-empty array of names` + } + if (!Array.isArray(engine.steps)) return `${at}.steps must be an array` + for (const [position, step] of engine.steps.entries()) { + const problem = stepProblem(step, `${at}.steps[${position}]`) + if (problem) return problem + } + if (engine.notes !== undefined && !isStringArray(engine.notes)) { + return `${at}.notes must be an array of strings` + } + if (engine.baseUrl !== undefined && !isHttpUrl(engine.baseUrl)) { + return `${at}.baseUrl must be an http or https URL` + } + if (engine.files !== undefined) { + if (!Array.isArray(engine.files)) { + return `${at}.files must be an array of paths` + } + for (const [position, file] of engine.files.entries()) { + if (!isInsidePath(file)) return `${at}.files[${position}] ${INSIDE}` + } + } + } + return undefined +} + +/** The first problem with `druxt.backendUrl`, or undefined. */ +function backendUrlProblem(value: unknown): string | undefined { + const at = 'druxt.backendUrl' + if (value === undefined) return undefined + if (!isRecord(value)) return `${at} must be an object` + if (!isInsidePath(value.file)) return `${at}.file ${INSIDE}` + if ( + typeof value.variable !== 'string' || + !/^[a-z_][a-z0-9_]*$/i.test(value.variable) + ) { + return `${at}.variable must be the name of a variable` + } + if (value.template !== undefined && !isInsidePath(value.template)) { + return `${at}.template ${INSIDE}` + } + return undefined +} + /** The first problem with an entry, or undefined when it is valid. */ function entryProblem(entry: unknown): string | undefined { if (!isRecord(entry)) return 'the entry must be an object' @@ -122,7 +268,7 @@ function entryProblem(entry: unknown): string | undefined { if (druxt.steps !== undefined && !isStringArray(druxt.steps)) { return 'druxt.steps must be an array of strings' } - return undefined + return enginesProblem(druxt.engines) ?? backendUrlProblem(druxt.backendUrl) } /** diff --git a/packages/cli/src/validate.ts b/packages/cli/src/validate.ts index 263a2d7..822bc50 100644 --- a/packages/cli/src/validate.ts +++ b/packages/cli/src/validate.ts @@ -20,3 +20,15 @@ export function isHttpUrl(value: unknown): value is string { return false } } + +/** + * True for a relative path that names something inside the directory it is + * resolved against: not absolute, not the directory itself, and with no + * segment that climbs out. + */ +export function isInsidePath(value: unknown): value is string { + if (!isNonEmptyString(value)) return false + if (/^[\\/]/.test(value) || /^[a-z]:/i.test(value)) return false + const segments = value.split(/[\\/]/).filter((segment) => segment !== '.') + return segments.some(Boolean) && !segments.includes('..') +} diff --git a/packages/cli/test/commands/init-engines.test.ts b/packages/cli/test/commands/init-engines.test.ts new file mode 100644 index 0000000..ab57d40 --- /dev/null +++ b/packages/cli/test/commands/init-engines.test.ts @@ -0,0 +1,545 @@ +import { existsSync, readFileSync } from 'node:fs' +import { join } from 'node:path' +import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest' +import type { Choice, CliContext, Prompter } from '../../src/context.js' +import { validEngines } from '../helpers/engines.js' +import { run } from '../helpers/run.js' +import { + fixtureRegistry, + STARTER_FILES, + type FixtureRegistry, +} from '../helpers/starter.js' +import { cleanTmp, tmp } from '../helpers/tmp.js' + +const FILES = { + ...STARTER_FILES, + '.env.example': + '# Backend\nBASE_URL=http://template.example\nOAUTH_CLIENT_ID=\n', + 'drupal/Makefile': 'build:\n', + 'drupal/.devtools/start': '#!/bin/sh\n', + 'drupal/.ddev/config.yaml': 'name: fixture\n', + 'drupal/.ddev/commands/web/drupal-install': '#!/bin/sh\n', + 'drupal/.lando.yml': 'name: fixture\n', +} + +let registry: FixtureRegistry +let cwd: string + +type Druxt = Record +const withEngines = (druxt: Druxt) => { + druxt.engines = validEngines() + druxt.backendUrl = { + file: '.env', + template: '.env.example', + variable: 'BASE_URL', + } +} +const serve = async (change: (druxt: Druxt) => void = withEngines) => { + await registry?.close() + registry = await fixtureRegistry(FILES, (entry) => + change(entry.druxt as Druxt) + ) +} + +beforeEach(async () => { + vi.stubEnv('XDG_CACHE_HOME', tmp('drx-cache-')) + vi.stubEnv('GIGET_REGISTRY', undefined) + vi.stubEnv('GIGET_AUTH', undefined) + await serve() + cwd = tmp('drx-cwd-') +}) + +afterEach(async () => { + await registry.close() + vi.unstubAllEnvs() + cleanTmp() +}) + +const on = (present: string[]) => (name: string) => + present.includes(name) ? `/usr/bin/${name}` : undefined +const everything = on(['php', 'composer', 'ddev', 'lando']) + +const init = (argv: string[], overrides: Partial = {}) => + run(['init', 'site', ...argv, '--registry', registry.url], { + cwd, + nodeVersion: '16.18.1', + findCommand: everything, + ...overrides, + }) + +const site = (...path: string[]) => join(cwd, 'site', ...path) +const has = (...path: string[]) => existsSync(site(...path)) +const config = () => JSON.parse(readFileSync(site('drx.config.json'), 'utf8')) +const backend = () => + config().parts.find((part: { role: string }) => part.role === 'backend') + +/** A prompter that answers by message and records the choices it showed. */ +function answering(answers: Record) { + const asked: { message: string; choices?: Choice[] }[] = [] + const answer = (message: string, choices?: Choice[]) => { + asked.push(choices ? { message, choices } : { message }) + if (!(message in answers)) throw new Error(`Unexpected prompt: ${message}`) + return answers[message] + } + const prompter: Prompter = { + text: async ({ message }) => answer(message) as string, + select: async ({ message, choices }) => answer(message, choices) as never, + confirm: async ({ message }) => answer(message) as boolean, + } + return { prompter, asked } +} + +describe('drx init --engine', () => { + test('keeps the chosen engine and removes the files of the others', async () => { + const result = await init(['--yes', '--engine', 'ddev']) + expect(result.code).toBe(0) + expect(has('drupal/.ddev/config.yaml')).toBe(true) + expect(has('drupal/.ddev/commands/web/drupal-install')).toBe(true) + expect(has('drupal/.devtools')).toBe(false) + expect(has('drupal/Makefile')).toBe(false) + expect(has('drupal/.lando.yml')).toBe(false) + expect(has('drupal/composer.json')).toBe(true) + expect(result.stderr).toContain( + 'Removed the files of the engines not chosen: drupal/.devtools, drupal/Makefile, drupal/.lando.yml.' + ) + }) + + test('keeps a path the chosen engine shares, inside a directory it does not', async () => { + const result = await init(['--yes', '--engine', 'lando']) + expect(result.code).toBe(0) + expect(has('drupal/.lando.yml')).toBe(true) + expect(has('drupal/.ddev/commands/web/drupal-install')).toBe(true) + expect(has('drupal/.ddev/config.yaml')).toBe(false) + expect(has('drupal/.devtools')).toBe(false) + }) + + test('records the engine and its database on the backend part', async () => { + await init(['--yes', '--engine', 'ddev']) + expect(config().parts).toEqual([ + { role: 'frontend', kind: 'nuxt', path: 'nuxt' }, + { + role: 'backend', + kind: 'drupal', + path: 'drupal', + engine: 'ddev', + database: 'mariadb', + }, + ]) + }) + + test('writes the URL the engine serves at where the starter reads it', async () => { + const result = await init(['--yes', '--engine', 'ddev']) + expect(readFileSync(site('.env'), 'utf8')).toBe( + '# Backend\nBASE_URL=http://fixture.ddev.site\nOAUTH_CLIENT_ID=\n' + ) + expect(result.stderr).toContain( + 'Wrote BASE_URL=http://fixture.ddev.site to .env.' + ) + }) + + test('writes no URL for an engine that has none of its own', async () => { + await init(['--yes', '--engine', 'php']) + expect(has('.env')).toBe(false) + }) + + test('prints what the engine needs, its steps and its notes', async () => { + const result = await init(['--yes', '--engine', 'ddev']) + expect(result.stdout).toBe( + [ + `Created a Druxt site in ${site()} from the quickstart starter.`, + '', + 'It needs:', + ' Node 16.18.1', + ' DDEV', + '', + 'Next:', + ' cd site', + ' npm run setup', + ' cd drupal', + ' ddev start', + ' ddev drupal-install', + ' cd ..', + ' npm run dev', + '', + 'Note:', + ' Copy the printed OAUTH_CLIENT_ID into .env.', + '', + ].join('\n') + ) + }) + + test('--json has the engine, the database and what was removed', async () => { + const result = await init(['--yes', '--engine', 'ddev', '--json']) + expect(JSON.parse(result.stdout)).toMatchObject({ + ok: true, + engine: 'ddev', + database: 'mariadb', + baseUrl: null, + removed: ['drupal/.devtools', 'drupal/Makefile', 'drupal/.lando.yml'], + notes: ['Copy the printed OAUTH_CLIENT_ID into .env.'], + next: [ + 'cd site', + 'npm run setup', + 'cd drupal', + 'ddev start', + 'ddev drupal-install', + 'cd ..', + 'npm run dev', + ], + commands: { + satisfied: true, + alternatives: [['ddev']], + found: ['ddev'], + missing: [], + }, + }) + }) + + test('fails on an engine the starter does not offer, naming the ones it does', async () => { + const result = await init(['--yes', '--engine', 'docker']) + expect(result.code).toBe(1) + expect(result.stderr).toContain( + 'The quickstart starter has no engine named "docker". It offers: php, ddev, lando, none.' + ) + expect(has()).toBe(false) + }) + + test('--keep-engines removes nothing', async () => { + const result = await init(['--yes', '--engine', 'ddev', '--keep-engines']) + expect(result.code).toBe(0) + expect(has('drupal/.devtools/start')).toBe(true) + expect(has('drupal/.lando.yml')).toBe(true) + expect(result.stderr).not.toContain('Removed') + expect(backend().engine).toBe('ddev') + }) +}) + +describe('drx init --database', () => { + test('records a database the engine offers', async () => { + await init(['--yes', '--engine', 'php', '--database', 'mysql']) + expect(backend()).toMatchObject({ engine: 'php', database: 'mysql' }) + }) + + test('defaults to the first the engine offers', async () => { + await init(['--yes', '--engine', 'php']) + expect(backend().database).toBe('sqlite') + }) + + test('fails on one the engine does not offer, naming the ones it does', async () => { + const result = await init([ + '--yes', + '--engine', + 'php', + '--database', + 'oracle', + ]) + expect(result.code).toBe(1) + expect(result.stderr).toContain( + 'The php engine of the quickstart starter has no database named "oracle". It offers: sqlite, mysql.' + ) + }) + + test('fails for an engine with no databases to choose from', async () => { + const result = await init([ + '--yes', + '--engine', + 'lando', + '--database', + 'mariadb', + ]) + expect(result.code).toBe(1) + expect(result.stderr).toContain( + 'The lando engine of the quickstart starter offers no choice of database.' + ) + await init(['--yes', '--engine', 'lando', '--force']) + expect(backend()).toEqual({ + role: 'backend', + kind: 'drupal', + path: 'drupal', + engine: 'lando', + }) + }) +}) + +describe('drx init --engine none', () => { + const URL = 'https://example.com' + + test('points the site at the backend and removes the files of every engine', async () => { + const result = await init(['--yes', '--engine', 'none', '--base-url', URL]) + expect(result.code).toBe(0) + for (const path of ['.devtools', 'Makefile', '.ddev', '.lando.yml']) { + expect(has('drupal', path), path).toBe(false) + } + expect(has('drupal/composer.json')).toBe(true) + expect(readFileSync(site('.env'), 'utf8')).toBe( + `# Backend\nBASE_URL=${URL}\nOAUTH_CLIENT_ID=\n` + ) + expect(backend()).toEqual({ + role: 'backend', + kind: 'drupal', + path: 'drupal', + engine: 'none', + baseUrl: URL, + }) + }) + + test('prints the steps of the starter and checks no commands', async () => { + const findCommand = vi.fn() + const result = await init( + ['--yes', '--engine', 'none', '--base-url', URL], + { + findCommand, + } + ) + expect(findCommand).not.toHaveBeenCalled() + expect(result.stderr).not.toContain('Warning') + expect(result.stdout).toBe( + [ + `Created a Druxt site in ${site()} from the quickstart starter.`, + '', + 'It needs:', + ' Node 16.18.1', + ` A backend that exists already, at ${URL}`, + '', + 'Next:', + ' cd site', + ' npm run setup', + ' npm run dev', + '', + ].join('\n') + ) + }) + + test('fails without --base-url when there is nobody to ask', async () => { + const result = await init(['--yes', '--engine', 'none']) + expect(result.code).toBe(1) + expect(result.stderr).toContain( + '--engine none needs --base-url, the URL of the backend that exists already.' + ) + expect(has()).toBe(false) + }) + + test.each(['example.com', 'ftp://example.com', ''])( + 'fails on --base-url %j before reading anything', + async (url) => { + const result = await init([ + '--yes', + '--engine', + 'none', + `--base-url=${url}`, + ]) + expect(result.code).toBe(1) + expect(result.stderr).toMatch( + /--base-url (must be an http or https URL|needs a value)/ + ) + expect(registry.requests).toEqual([]) + } + ) + + test('fails on --base-url with another engine', async () => { + const result = await init(['--yes', '--engine', 'ddev', '--base-url', URL]) + expect(result.code).toBe(1) + expect(result.stderr).toContain( + '--base-url goes with --engine none. The ddev engine serves the backend itself.' + ) + }) + + test('fails on --database', async () => { + const result = await init([ + '--yes', + '--engine', + 'none', + '--base-url', + URL, + '--database', + 'sqlite', + ]) + expect(result.code).toBe(1) + expect(result.stderr).toContain( + '--database does not go with --engine none. The backend has its database already.' + ) + }) + + test('is offered by a starter that lists no engines', async () => { + await serve(() => {}) + const result = await init(['--yes', '--engine', 'none', '--base-url', URL]) + expect(result.code).toBe(0) + expect(backend()).toMatchObject({ engine: 'none', baseUrl: URL }) + expect(result.stderr).toContain( + `Warning: The quickstart starter does not say where it reads its backend URL from. Point it at ${URL} yourself.` + ) + expect(has('drupal/.ddev/config.yaml')).toBe(true) + }) + + test('is the only engine of a starter that lists none', async () => { + await serve(() => {}) + const result = await init(['--yes', '--engine', 'ddev']) + expect(result.code).toBe(1) + expect(result.stderr).toContain( + 'The quickstart starter has no engine named "ddev". It offers: none.' + ) + }) +}) + +describe('drx init with no engine named', () => { + test('takes the first engine whose commands are all present', async () => { + await init(['--yes'], { findCommand: on(['php', 'lando']) }) + expect(backend().engine).toBe('lando') + }) + + test('takes the first engine of the starter when none is present, and warns of its commands only', async () => { + const result = await init([], { findCommand: on(['composer']) }) + expect(result.code).toBe(0) + expect(backend().engine).toBe('php') + expect(result.stderr.match(/Warning/g)).toHaveLength(1) + expect(result.stderr).toContain( + 'Warning: The php engine needs php and composer. Not found on PATH: php. Install what is missing before you set up the site.' + ) + }) + + test('records no engine for a starter that lists none', async () => { + await serve(() => {}) + await init(['--yes']) + expect(backend()).toEqual({ + role: 'backend', + kind: 'drupal', + path: 'drupal', + }) + }) +}) + +describe('drx init at a terminal with engines', () => { + const base = { + 'Which layout?': 'monorepo', + 'Install its dependencies now?': false, + } + + test('lists the installed engines first, marks the others, and ends with none', async () => { + const { prompter, asked } = answering({ + ...base, + 'How should the backend run?': 'ddev', + }) + const result = await init([], { + interactive: true, + prompter, + findCommand: on(['ddev', 'composer']), + }) + expect(result.code).toBe(0) + const engine = asked.find(({ message }) => message.startsWith('How')) + expect(engine?.choices).toEqual([ + { value: 'ddev', label: 'DDEV' }, + { + value: 'php', + label: 'Local PHP with Composer', + hint: 'not installed: php', + }, + { value: 'lando', label: 'Lando', hint: 'not installed: lando' }, + { value: 'none', label: 'None: use a backend that exists already' }, + ]) + expect(backend().engine).toBe('ddev') + // DDEV offers one database, so there is nothing to ask. + expect(asked.map(({ message }) => message)).toEqual([ + 'Which layout?', + 'How should the backend run?', + 'Install its dependencies now?', + ]) + }) + + test('asks for the database when the engine offers more than one', async () => { + const { prompter, asked } = answering({ + ...base, + 'How should the backend run?': 'php', + 'Which database?': 'mysql', + }) + await init([], { interactive: true, prompter }) + expect( + asked.find(({ message }) => message === 'Which database?')?.choices + ).toEqual([ + { value: 'sqlite', label: 'sqlite' }, + { value: 'mysql', label: 'mysql' }, + ]) + expect(backend().database).toBe('mysql') + }) + + test('asks for the URL of a backend that exists already', async () => { + const { prompter } = answering({ + ...base, + 'How should the backend run?': 'none', + 'What is the URL of the backend?': 'https://cms.example.com', + }) + const result = await init([], { interactive: true, prompter }) + expect(result.code).toBe(0) + expect(backend().baseUrl).toBe('https://cms.example.com') + }) + + test('refuses an answer that is not a URL', async () => { + const { prompter } = answering({ + ...base, + 'How should the backend run?': 'none', + 'What is the URL of the backend?': 'cms', + }) + const result = await init([], { interactive: true, prompter }) + expect(result.code).toBe(1) + expect(result.stderr).toContain( + '--base-url must be an http or https URL: "cms".' + ) + }) + + test('asks nothing the flags answered', async () => { + const { prompter, asked } = answering(base) + await init(['--engine', 'php', '--database', 'sqlite'], { + interactive: true, + prompter, + }) + expect(asked.map(({ message }) => message)).toEqual([ + 'Which layout?', + 'Install its dependencies now?', + ]) + }) +}) + +describe('drx init --setup', () => { + test('says it is not available yet, and creates nothing', async () => { + const result = await init(['--yes', '--setup']) + expect(result.code).toBe(1) + expect(result.stderr).toContain( + '--setup is not available yet. init prints the steps for you to run.' + ) + expect(registry.requests).toEqual([]) + expect(has()).toBe(false) + }) +}) + +describe('drx info after an engine was chosen', () => { + test('prints the engine, the database and the URL of the backend', async () => { + await init(['--yes', '--engine', 'ddev']) + const ddev = await run(['info'], { cwd: site() }) + expect(ddev.stdout).toContain( + [ + 'backend drupal drupal/', + ' Engine ddev', + ' Database mariadb', + ].join('\n') + ) + + const again = await init([ + '--yes', + '--force', + '--engine', + 'none', + '--base-url', + 'https://example.com', + ]) + expect(again.stderr).not.toContain('Error') + expect(again.code).toBe(0) + const none = await run(['info', '--json'], { cwd: site() }) + expect(JSON.parse(none.stdout).project.parts[1]).toMatchObject({ + engine: 'none', + baseUrl: 'https://example.com', + }) + const text = await run(['info'], { cwd: site() }) + expect(text.stdout).toContain( + [' Engine none', ' Backend URL https://example.com'].join('\n') + ) + }) +}) diff --git a/packages/cli/test/commands/init.test.ts b/packages/cli/test/commands/init.test.ts index bbafb80..7fa4eea 100644 --- a/packages/cli/test/commands/init.test.ts +++ b/packages/cli/test/commands/init.test.ts @@ -105,7 +105,12 @@ describe('drx init', () => { ...CONFIG, installed: false, requires: { node: '16.18.1', tools: ['DDEV'] }, + engine: null, + database: null, + baseUrl: null, + removed: [], commands: null, + notes: [], next: ['cd site', 'npm run setup', 'npm run dev'], }) expect(result.stderr).toContain('Reading starters from') diff --git a/packages/cli/test/e2e/quickstart.test.ts b/packages/cli/test/e2e/quickstart.test.ts index 4e5d1dd..68520bf 100644 --- a/packages/cli/test/e2e/quickstart.test.ts +++ b/packages/cli/test/e2e/quickstart.test.ts @@ -1,6 +1,7 @@ import { existsSync, readFileSync } from 'node:fs' import { join } from 'node:path' import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest' +import { openRegistry } from '../../src/registry/registry.js' import { run } from '../helpers/run.js' import { cleanTmp, tmp } from '../helpers/tmp.js' @@ -17,6 +18,56 @@ describe.skipIf(process.env.DRX_E2E !== '1')('the quickstart starter', () => { cleanTmp() }) + test('holds every file its engines name, and the file its backend URL goes in', async () => { + const cwd = tmp('drx-e2e-') + const created = await run( + ['init', 'site', '--yes', '--keep-engines', '--json'], + { cwd } + ) + expect(created.code).toBe(0) + const site = join(cwd, 'site') + + const registry = await openRegistry() + const { engines = [], backendUrl } = (await registry.entry('quickstart')) + .druxt + expect(engines.length).toBeGreaterThan(0) + for (const engine of engines) { + for (const file of engine.files ?? []) { + expect(existsSync(join(site, file)), file).toBe(true) + } + for (const step of engine.steps) { + if (typeof step !== 'string') { + expect(existsSync(join(site, step.dir)), step.dir).toBe(true) + } + } + } + expect(existsSync(join(site, backendUrl?.template ?? 'missing'))).toBe(true) + }, 120_000) + + test('is left without the other engines when one is chosen', async () => { + const cwd = tmp('drx-e2e-') + const created = await run( + ['init', 'site', '--yes', '--engine', 'lando', '--json'], + { cwd } + ) + expect(created.code).toBe(0) + const site = join(cwd, 'site') + // The starter's own scripts run the local tooling in drupal/.devtools whatever the engine, so it stays. + expect(JSON.parse(created.stdout).removed).toEqual([ + 'drupal/.ddev/config.yaml', + 'drupal/.ddev/docker-compose.env.yaml', + 'drupal/.ddev/docker-compose.network-mtu.yaml', + ]) + expect(existsSync(join(site, 'drupal/.lando.yml'))).toBe(true) + expect(existsSync(join(site, 'drupal/.devtools'))).toBe(true) + expect( + existsSync(join(site, 'drupal/.ddev/commands/web/drupal-install')) + ).toBe(true) + expect(readFileSync(join(site, '.env'), 'utf8')).toContain( + 'BASE_URL=https://druxt-quickstart.lndo.site' + ) + }, 120_000) + test('is created by drx init and read back by drx info', async () => { const cwd = tmp('drx-e2e-') const created = await run(['init', 'site', '--yes', '--json'], { cwd }) diff --git a/packages/cli/test/engines/engines.test.ts b/packages/cli/test/engines/engines.test.ts new file mode 100644 index 0000000..8d72eed --- /dev/null +++ b/packages/cli/test/engines/engines.test.ts @@ -0,0 +1,60 @@ +import { describe, expect, test } from 'vitest' +import { engineFor, knownEngines } from '../../src/engines/index.js' +import { DrxError } from '../../src/errors.js' +import type { Part } from '../../src/parts.js' + +const part: Part = { role: 'backend', kind: 'drupal', path: 'drupal' } + +describe('engineFor', () => { + test('knows the engines this version can run tools through', () => { + expect(knownEngines()).toEqual(['php', 'ddev', 'lando', 'none']) + expect(engineFor('docker-compose')).toBeUndefined() + }) +}) + +describe('the php engine', () => { + const php = engineFor('php')! + + test('runs composer as it is, in the part', () => { + expect(php.run(part, 'composer', ['require', 'drupal/druxt'])).toEqual({ + command: 'composer', + args: ['require', 'drupal/druxt'], + cwd: 'drupal', + }) + }) + + test('runs another tool from the bin directory Composer installs into', () => { + expect(php.run(part, 'drush', ['en', 'druxt', '-y'])).toEqual({ + command: 'vendor/bin/drush', + args: ['en', 'druxt', '-y'], + cwd: 'drupal', + }) + }) +}) + +describe.each(['ddev', 'lando'])('the %s engine', (name) => { + test('runs a tool through its own command, in the part', () => { + const engine = engineFor(name)! + expect(engine.name).toBe(name) + expect(engine.run(part, 'composer', ['require', 'drupal/druxt'])).toEqual({ + command: name, + args: ['composer', 'require', 'drupal/druxt'], + cwd: 'drupal', + }) + expect(engine.run(part, 'drush', ['en', 'druxt'])).toEqual({ + command: name, + args: ['drush', 'en', 'druxt'], + cwd: 'drupal', + }) + }) +}) + +describe('the none engine', () => { + test('cannot run a tool, and says the backend is elsewhere', () => { + const attempt = () => engineFor('none')!.run(part, 'drush', ['en', 'druxt']) + expect(attempt).toThrow(DrxError) + expect(attempt).toThrow( + 'The backend of this project is not on this machine, so drush cannot be run from here. Run "drush en druxt" where the backend is.' + ) + }) +}) diff --git a/packages/cli/test/engines/files.test.ts b/packages/cli/test/engines/files.test.ts new file mode 100644 index 0000000..920580b --- /dev/null +++ b/packages/cli/test/engines/files.test.ts @@ -0,0 +1,172 @@ +import { existsSync, readFileSync, symlinkSync } from 'node:fs' +import { join } from 'node:path' +import { afterEach, describe, expect, test } from 'vitest' +import { writeBackendUrl } from '../../src/engines/backend-url.js' +import { removeEngineFiles } from '../../src/engines/files.js' +import { cleanTmp, tmp, writeTree } from '../helpers/tmp.js' + +afterEach(cleanTmp) + +function site(): string { + const root = tmp('drx-site-') + writeTree(root, { + 'README.md': '# Site\n', + 'drupal/composer.json': {}, + 'drupal/Makefile': 'build:\n', + 'drupal/.devtools/start': '#!/bin/sh\n', + 'drupal/.ddev/config.yaml': 'name: fixture\n', + 'drupal/.ddev/commands/web/drupal-install': '#!/bin/sh\n', + 'drupal/.lando.yml': 'name: fixture\n', + }) + return root +} + +describe('removeEngineFiles', () => { + test('removes files and directories, and says which', async () => { + const root = site() + const removed = await removeEngineFiles( + root, + ['drupal/.devtools', 'drupal/Makefile', 'drupal/.lando.yml'], + [] + ) + expect(removed).toEqual([ + 'drupal/.devtools', + 'drupal/Makefile', + 'drupal/.lando.yml', + ]) + expect(existsSync(join(root, 'drupal/.devtools'))).toBe(false) + expect(existsSync(join(root, 'drupal/Makefile'))).toBe(false) + expect(existsSync(join(root, 'drupal/.ddev/config.yaml'))).toBe(true) + expect(existsSync(join(root, 'drupal/composer.json'))).toBe(true) + }) + + test('skips a path that is not there', async () => { + expect(await removeEngineFiles(site(), ['drupal/.docker'], [])).toEqual([]) + }) + + test('keeps a path the chosen engine lists too', async () => { + const root = site() + const removed = await removeEngineFiles( + root, + ['drupal/.ddev/commands', 'drupal/.lando.yml'], + ['drupal/.ddev'] + ) + expect(removed).toEqual(['drupal/.lando.yml']) + expect( + existsSync(join(root, 'drupal/.ddev/commands/web/drupal-install')) + ).toBe(true) + }) + + test('removes around a path the chosen engine needs inside a directory', async () => { + const root = site() + const removed = await removeEngineFiles( + root, + ['drupal/.ddev'], + ['drupal/.ddev/commands'] + ) + expect(removed).toEqual(['drupal/.ddev/config.yaml']) + expect(existsSync(join(root, 'drupal/.ddev/config.yaml'))).toBe(false) + expect( + existsSync(join(root, 'drupal/.ddev/commands/web/drupal-install')) + ).toBe(true) + }) + + test.each([ + '../outside.txt', + '/etc/hostname', + 'drupal/../../outside.txt', + '.', + ])('refuses %s and removes nothing', async (path) => { + const parent = tmp('drx-parent-') + writeTree(parent, { 'outside.txt': 'keep', 'site/README.md': '# Site\n' }) + await expect( + removeEngineFiles(join(parent, 'site'), ['README.md', path], []) + ).rejects.toThrow(`Refusing to remove ${path}: it is not inside the site.`) + expect(readFileSync(join(parent, 'outside.txt'), 'utf8')).toBe('keep') + expect(existsSync(join(parent, 'site', 'README.md'))).toBe(true) + }) + + test.skipIf(process.platform === 'win32')( + 'refuses a path that leaves the site through a link', + async () => { + const parent = tmp('drx-parent-') + writeTree(parent, { 'elsewhere/precious.txt': 'keep', 'site/a.txt': '' }) + symlinkSync(join(parent, 'elsewhere'), join(parent, 'site', 'link')) + await expect( + removeEngineFiles(join(parent, 'site'), ['link/precious.txt'], []) + ).rejects.toThrow( + 'Refusing to remove link/precious.txt: it is not inside the site.' + ) + expect(existsSync(join(parent, 'elsewhere', 'precious.txt'))).toBe(true) + } + ) + + test.skipIf(process.platform === 'win32')( + 'removes a link itself, not what it points at', + async () => { + const parent = tmp('drx-parent-') + writeTree(parent, { 'elsewhere/precious.txt': 'keep', 'site/a.txt': '' }) + symlinkSync(join(parent, 'elsewhere'), join(parent, 'site', 'link')) + expect( + await removeEngineFiles(join(parent, 'site'), ['link'], []) + ).toEqual(['link']) + expect(existsSync(join(parent, 'elsewhere', 'precious.txt'))).toBe(true) + } + ) +}) + +describe('writeBackendUrl', () => { + const target = { + file: '.env', + template: '.env.example', + variable: 'BASE_URL', + } + + test('starts from the template and sets the variable', async () => { + const root = tmp() + writeTree(root, { + '.env.example': + '# Backend URL\nBASE_URL=http://old.ddev.site\n\nOAUTH_CLIENT_ID=\n', + }) + await writeBackendUrl(root, target, 'https://example.com') + expect(readFileSync(join(root, '.env'), 'utf8')).toBe( + '# Backend URL\nBASE_URL=https://example.com\n\nOAUTH_CLIENT_ID=\n' + ) + expect(readFileSync(join(root, '.env.example'), 'utf8')).toContain( + 'old.ddev.site' + ) + }) + + test('changes the variable in a file that exists, and leaves the rest', async () => { + const root = tmp() + writeTree(root, { + '.env': 'OAUTH_CLIENT_ID=abc\nBASE_URL=http://127.0.0.1:8888\n', + '.env.example': 'BASE_URL=http://old.ddev.site\n', + }) + await writeBackendUrl(root, target, 'https://example.com') + expect(readFileSync(join(root, '.env'), 'utf8')).toBe( + 'OAUTH_CLIENT_ID=abc\nBASE_URL=https://example.com\n' + ) + }) + + test('adds the variable when neither file has it', async () => { + const root = tmp() + writeTree(root, { '.env.example': 'OAUTH_CLIENT_ID=' }) + await writeBackendUrl(root, target, 'https://example.com') + expect(readFileSync(join(root, '.env'), 'utf8')).toBe( + 'OAUTH_CLIENT_ID=\nBASE_URL=https://example.com\n' + ) + }) + + test('writes the file with no template to start from', async () => { + const root = tmp() + await writeBackendUrl( + root, + { file: 'config/.env', variable: 'API' }, + 'https://example.com' + ) + expect(readFileSync(join(root, 'config/.env'), 'utf8')).toBe( + 'API=https://example.com\n' + ) + }) +}) diff --git a/packages/cli/test/helpers/engines.ts b/packages/cli/test/helpers/engines.ts new file mode 100644 index 0000000..5ff8c87 --- /dev/null +++ b/packages/cli/test/helpers/engines.ts @@ -0,0 +1,44 @@ +/** Engines in the shape a registry entry gives them, for tests to change. */ +export function validEngines(): Record[] { + return [ + { + name: 'php', + label: 'Local PHP with Composer', + commands: ['php', 'composer'], + databases: ['sqlite', 'mysql'], + steps: ['npm run setup', 'npm run dev'], + files: ['drupal/.devtools', 'drupal/Makefile'], + }, + { + name: 'ddev', + label: 'DDEV', + commands: ['ddev'], + databases: ['mariadb'], + baseUrl: 'http://fixture.ddev.site', + steps: [ + 'npm run setup', + { run: 'ddev start', dir: 'drupal' }, + { run: 'ddev drupal-install', dir: 'drupal' }, + 'npm run dev', + ], + notes: ['Copy the printed OAUTH_CLIENT_ID into .env.'], + files: ['drupal/.ddev'], + }, + { + name: 'lando', + label: 'Lando', + commands: ['lando'], + steps: [{ run: 'lando start', dir: 'drupal' }], + files: ['drupal/.lando.yml', 'drupal/.ddev/commands'], + }, + ] +} + +/** The valid engines with one field of one engine set, or removed. */ +export function enginesWith(index: number, key: string, value: unknown) { + const engines = validEngines() + const engine = engines[index] as Record + if (value === undefined) delete engine[key] + else engine[key] = value + return engines +} diff --git a/packages/cli/test/helpers/server.ts b/packages/cli/test/helpers/server.ts index b200dfb..c307009 100644 --- a/packages/cli/test/helpers/server.ts +++ b/packages/cli/test/helpers/server.ts @@ -34,8 +34,10 @@ export async function serve( url: `http://127.0.0.1:${port}`, files, requests, + // Closing twice is allowed, so a test may replace its server early. close: () => new Promise((resolve, reject) => { + if (!server.listening) return resolve() server.closeAllConnections() server.close((error) => (error ? reject(error) : resolve())) }), diff --git a/packages/cli/test/project.test.ts b/packages/cli/test/project.test.ts index 718bae7..1de3c09 100644 --- a/packages/cli/test/project.test.ts +++ b/packages/cli/test/project.test.ts @@ -77,6 +77,52 @@ describe('loadProjectConfig', () => { ) }) + test('reads a file again after it has changed', async () => { + const root = tmp() + await writeProjectConfig(root, config) + expect((await loadProjectConfig(root)).line).toBe('0.x') + await writeProjectConfig(root, { ...config, line: '2.x' }) + expect((await loadProjectConfig(root)).line).toBe('2.x') + }) + + test('reads the engine, the database and the URL of a backend part', async () => { + const root = tmp() + const recorded: ProjectConfig = { + ...config, + parts: [ + config.parts[0]!, + { + ...config.parts[1]!, + engine: 'none', + database: 'mariadb', + baseUrl: 'https://example.com', + }, + ], + } + await writeProjectConfig(root, recorded) + expect(await loadProjectConfig(root)).toEqual(recorded) + }) + + test.each([ + [{ engine: '' }, 'parts[1].engine must be a non-empty string'], + [{ database: 7 }, 'parts[1].database must be a non-empty string'], + [ + { baseUrl: 'example.com' }, + 'parts[1].baseUrl must be an http or https URL', + ], + ])('names the bad field of a part in %j', async (extra, message) => { + const root = tmp() + writeTree(root, { + 'drx.config.json': { + ...config, + parts: [config.parts[0], { ...config.parts[1], ...extra }], + }, + }) + await expect(loadProjectConfig(root)).rejects.toThrow( + `${join(root, 'drx.config.json')} is invalid: ${message}.` + ) + }) + test('fails on a file that is not JSON', async () => { const root = tmp() writeTree(root, { 'drx.config.json': '{ nope' }) diff --git a/packages/cli/test/registry/entry.test.ts b/packages/cli/test/registry/entry.test.ts index 5bbba93..567009d 100644 --- a/packages/cli/test/registry/entry.test.ts +++ b/packages/cli/test/registry/entry.test.ts @@ -1,6 +1,7 @@ import { describe, expect, test } from 'vitest' import { DrxError } from '../../src/errors.js' import { validateEntry } from '../../src/registry/entry.js' +import { enginesWith, validEngines } from '../helpers/engines.js' import { entryWith, validEntry } from '../helpers/entry.js' describe('validateEntry', () => { @@ -153,3 +154,127 @@ describe('validateEntry', () => { ) }) }) + +describe('validateEntry and engines', () => { + const E = 'druxt.engines' + const backendUrl = { + file: '.env', + template: '.env.example', + variable: 'BASE_URL', + } + + test('accepts engines and where the backend URL goes', () => { + const entry = entryWith(E, validEngines()) + ;(entry.druxt as Record).backendUrl = backendUrl + expect(validateEntry(entry, 'quickstart')).toEqual(entry) + }) + + test.each([ + ['php', `${E} must be a non-empty array`], + [[], `${E} must be a non-empty array`], + [['php'], `${E}[0] must be an object`], + [ + enginesWith(1, 'name', undefined), + `${E}[1].name must be a lower-case name`, + ], + [ + enginesWith(1, 'name', 'My Engine'), + `${E}[1].name must be a lower-case name`, + ], + [ + enginesWith(1, 'name', 'none'), + `${E}[1].name cannot be none, which every starter has`, + ], + [enginesWith(1, 'name', 'php'), `${E}[1].name repeats the name php`], + [enginesWith(0, 'label', ''), `${E}[0].label must be a non-empty string`], + [ + enginesWith(0, 'commands', undefined), + `${E}[0].commands must be an array of command names`, + ], + [ + enginesWith(0, 'commands', ['php', 'bin/composer']), + `${E}[0].commands[1] must be a command name with no path or spaces`, + ], + [ + enginesWith(0, 'databases', []), + `${E}[0].databases must be a non-empty array of names`, + ], + [ + enginesWith(0, 'databases', ['sqlite', 7]), + `${E}[0].databases must be a non-empty array of names`, + ], + [enginesWith(0, 'steps', undefined), `${E}[0].steps must be an array`], + [ + enginesWith(0, 'steps', [7]), + `${E}[0].steps[0] must be a command, or an object with run and dir`, + ], + [ + enginesWith(0, 'steps', [{ run: 'x' }]), + `${E}[0].steps[0].dir must be a relative path inside the starter`, + ], + [ + enginesWith(0, 'steps', [{ run: '', dir: 'drupal' }]), + `${E}[0].steps[0].run must be a non-empty string`, + ], + [ + enginesWith(0, 'steps', [{ run: 'x', dir: '../up' }]), + `${E}[0].steps[0].dir must be a relative path inside the starter`, + ], + [ + enginesWith(1, 'notes', 'a note'), + `${E}[1].notes must be an array of strings`, + ], + [ + enginesWith(1, 'baseUrl', 'fixture.ddev.site'), + `${E}[1].baseUrl must be an http or https URL`, + ], + [ + enginesWith(2, 'files', 'drupal/.lando.yml'), + `${E}[2].files must be an array of paths`, + ], + [ + enginesWith(2, 'files', ['/etc/passwd']), + `${E}[2].files[0] must be a relative path inside the starter`, + ], + [ + enginesWith(2, 'files', ['drupal/.lando.yml', 'drupal/../../outside']), + `${E}[2].files[1] must be a relative path inside the starter`, + ], + [ + enginesWith(2, 'files', ['C:\\Windows']), + `${E}[2].files[0] must be a relative path inside the starter`, + ], + [ + enginesWith(2, 'files', ['.']), + `${E}[2].files[0] must be a relative path inside the starter`, + ], + ])('names the bad engine field in %j', (engines, message) => { + expect(() => validateEntry(entryWith(E, engines), 'quickstart')).toThrow( + `Starter entry "quickstart" is invalid: ${message}.` + ) + }) + + test.each([ + ['.env', 'druxt.backendUrl must be an object'], + [ + { variable: 'BASE_URL' }, + 'druxt.backendUrl.file must be a relative path inside the starter', + ], + [ + { file: '../.env', variable: 'BASE_URL' }, + 'druxt.backendUrl.file must be a relative path inside the starter', + ], + [ + { file: '.env', variable: 'BASE URL' }, + 'druxt.backendUrl.variable must be the name of a variable', + ], + [ + { file: '.env', variable: 'BASE_URL', template: '/etc/env' }, + 'druxt.backendUrl.template must be a relative path inside the starter', + ], + ])('names the bad backendUrl field in %j', (value, message) => { + expect(() => + validateEntry(entryWith('druxt.backendUrl', value), 'quickstart') + ).toThrow(`Starter entry "quickstart" is invalid: ${message}.`) + }) +}) diff --git a/packages/cli/test/registry/registry.test.ts b/packages/cli/test/registry/registry.test.ts index 0c100fa..62ca336 100644 --- a/packages/cli/test/registry/registry.test.ts +++ b/packages/cli/test/registry/registry.test.ts @@ -199,10 +199,12 @@ describe('the bundled registry', () => { 'https://codeload.github.com/druxt/quickstart/tar.gz/refs/heads/develop' ) expect(starter.druxt.default).toBe(true) - expect(starter.druxt.requires.commands).toEqual([ - ['php', 'composer'], - ['ddev'], + expect(starter.druxt.engines?.map(({ name }) => name)).toEqual([ + 'php', + 'ddev', + 'lando', ]) + expect(starter.druxt.backendUrl?.variable).toBe('BASE_URL') expect((await defaultStarter(registry))?.name).toBe('quickstart') }) }) diff --git a/packages/cli/test/seams.test.ts b/packages/cli/test/seams.test.ts index e3bc89e..83e9f67 100644 --- a/packages/cli/test/seams.test.ts +++ b/packages/cli/test/seams.test.ts @@ -4,6 +4,7 @@ import { describe, expect, test } from 'vitest' import { bundledRegistryDir, packageRoot } from '../src/package-root.js' const KIND_WORD = /nuxt|drupal/i +const ENGINE_WORD = /\b(ddev|lando|php)\b/i /** Every file under a directory, as paths relative to it. */ function filesUnder(dir: string): string[] { @@ -42,3 +43,15 @@ describe('the names of kinds', () => { expect(keys.filter((key) => KIND_WORD.test(key))).toEqual([]) }) }) + +// An engine is a name in a registry entry and an adapter in engines/. A +// command asks the adapter, so adding an engine changes no command. +describe('the names of engines', () => { + test('appear in the sources only inside engines/', () => { + const src = join(packageRoot(), 'src') + const offenders = filesUnder(src) + .filter((file) => !file.startsWith('engines')) + .filter((file) => ENGINE_WORD.test(readFileSync(join(src, file), 'utf8'))) + expect(offenders).toEqual([]) + }) +}) diff --git a/starters/quickstart.json b/starters/quickstart.json index ebc2455..b6f7297 100644 --- a/starters/quickstart.json +++ b/starters/quickstart.json @@ -12,11 +12,64 @@ ], "requires": { "node": "16.18.1", - "tools": ["PHP 8.3 or newer with Composer, or DDEV"], - "commands": [["php", "composer"], ["ddev"]] + "tools": ["PHP 8.3 or newer with Composer, or DDEV, or Lando"] }, - "maintained": "2026-11-15", + "maintained": "2026-11-16", "default": true, - "steps": ["npm run setup", "npm run dev"] + "steps": ["npm run setup", "npm run dev"], + "backendUrl": { + "file": ".env", + "template": ".env.example", + "variable": "BASE_URL" + }, + "engines": [ + { + "name": "php", + "label": "PHP 8.3 or newer with the pdo_sqlite extension, and Composer", + "commands": ["php", "composer"], + "databases": ["sqlite"], + "steps": ["npm run setup", "npm run dev"], + "notes": [ + "This engine does not run on Windows itself. Use WSL2 there, or another engine." + ], + "files": [] + }, + { + "name": "ddev", + "label": "DDEV", + "commands": ["ddev"], + "databases": ["mariadb"], + "baseUrl": "http://quickstart-druxtsite.ddev.site", + "steps": [ + "npm run setup", + { "run": "ddev start", "dir": "drupal" }, + { "run": "ddev drupal-install", "dir": "drupal" }, + { "run": "ddev druxt-add-consumer", "dir": "drupal" }, + "npm run dev" + ], + "notes": [ + "ddev druxt-add-consumer prints OAUTH_CLIENT_ID. Copy it into .env before npm run dev." + ], + "files": ["drupal/.ddev"] + }, + { + "name": "lando", + "label": "Lando", + "commands": ["lando"], + "databases": ["mariadb"], + "baseUrl": "https://druxt-quickstart.lndo.site", + "steps": [ + "npm run setup", + { "run": "lando start", "dir": "drupal" }, + { "run": "lando drupal-install", "dir": "drupal" }, + { "run": "lando druxt-add-consumer", "dir": "drupal" }, + "npm run dev" + ], + "notes": [ + "lando druxt-add-consumer prints OAUTH_CLIENT_ID. Copy it into .env before npm run dev." + ], + "files": ["drupal/.lando.yml", "drupal/.ddev/commands"] + } + ] } } From 8820aae7ee91c1df47c2088920790b7e82446a1c Mon Sep 17 00:00:00 2001 From: Stuart Clark Date: Wed, 18 Nov 2026 04:35:06 +0000 Subject: [PATCH 2/6] fix(cli): trim a step's directory in linear time --- packages/cli/src/engines/choose.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/packages/cli/src/engines/choose.ts b/packages/cli/src/engines/choose.ts index 45c9011..bc56369 100644 --- a/packages/cli/src/engines/choose.ts +++ b/packages/cli/src/engines/choose.ts @@ -8,6 +8,7 @@ import { type StarterEntry, } from '../registry/entry.js' import { isHttpUrl } from '../validate.js' +import { trimEndSlashes } from '../slashes.js' /** What the flags say about the engine. Each is undefined when not given. */ export interface EngineOptions { @@ -234,7 +235,7 @@ export function stepLines(steps: EngineStep[]): string[] { const lines: string[] = [] let here = '' for (const step of steps) { - const dir = typeof step === 'string' ? '' : step.dir.replace(/\/+$/, '') + const dir = typeof step === 'string' ? '' : trimEndSlashes(step.dir) if (dir !== here) { const back = here .split('/') From 0d3efa7cd748351c78d14634a9b89c6a6d0beec9 Mon Sep 17 00:00:00 2001 From: Stuart Clark Date: Wed, 18 Nov 2026 21:30:18 +0000 Subject: [PATCH 3/6] fix(cli): say which engine the dev server starts the backend for - The quickstart's note printed after `drx init --install` said the dev server starts the backend again. That is so for the `php` engine only, and the note now says so and where the other backends start. - The README says that `install.runs` also applies to the steps of an engine, and a test covers it. --- README.md | 2 +- .../cli/test/commands/init-engines.test.ts | 23 +++++++++++++++++++ starters/quickstart.json | 2 +- 3 files changed, 25 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 8116f1f..2acc2f3 100644 --- a/README.md +++ b/README.md @@ -250,7 +250,7 @@ A registry is a URL that answers `/.json` for each starter, in the format | `steps` | Optional. The commands to run in the new site, in order, when no engine is chosen and for the `none` engine | | `engines` | Optional. The ways the backend can be run, described below | | `backendUrl` | Optional. The `file` and `variable` the starter reads its backend URL from, and a `template` to start the file from | -| `install.runs` | Optional. The steps the install runs itself, left out of "Next" after one | +| `install.runs` | Optional. The steps the install runs itself, left out of "Next" after one, from an engine's steps too | | `install.notes` | Optional. Lines printed under "Note" after an install | `index.json` is `{ "starters": ["quickstart"] }`. diff --git a/packages/cli/test/commands/init-engines.test.ts b/packages/cli/test/commands/init-engines.test.ts index ab57d40..4c1e544 100644 --- a/packages/cli/test/commands/init-engines.test.ts +++ b/packages/cli/test/commands/init-engines.test.ts @@ -168,6 +168,29 @@ describe('drx init --engine', () => { ) }) + test('after --install leaves the steps the install ran out of the engine steps', async () => { + await serve((druxt) => { + withEngines(druxt) + druxt.install = { runs: ['npm run setup'], notes: ['After install.'] } + }) + const result = await init( + ['--yes', '--engine', 'ddev', '--install', '--json'], + { install: async () => {} } + ) + expect(JSON.parse(result.stdout)).toMatchObject({ + next: [ + 'cd site', + 'cd drupal', + 'ddev start', + 'ddev drupal-install', + 'cd ..', + 'npm run dev', + ], + // The engine's notes come first, then the install's. + notes: ['Copy the printed OAUTH_CLIENT_ID into .env.', 'After install.'], + }) + }) + test('--json has the engine, the database and what was removed', async () => { const result = await init(['--yes', '--engine', 'ddev', '--json']) expect(JSON.parse(result.stdout)).toMatchObject({ diff --git a/starters/quickstart.json b/starters/quickstart.json index f26a732..813decf 100644 --- a/starters/quickstart.json +++ b/starters/quickstart.json @@ -75,7 +75,7 @@ "runs": ["npm run setup"], "notes": [ "npm install ran the setup. If it said it could not, run npm run setup once what it named is in place.", - "npm run dev starts the backend again when it is not running." + "With the php engine, npm run dev starts the backend again when it is not running. A DDEV, Lando or existing backend is started where it runs." ] } } From bd732119d84f4929a87671446ae7c17b59b78a79 Mon Sep 17 00:00:00 2001 From: Stuart Clark Date: Wed, 18 Nov 2026 23:15:24 +0000 Subject: [PATCH 4/6] fix(cli): leave engine files in place when init writes into a directory that holds files `drx init --force` into a directory that was not empty removed the paths of the engines not chosen, whoever had put them there. A `.lando.yml` or a `.ddev` directory of the user's own went with them. - `init` looks at the directory before the download. When it held files, no engine file is removed, and a warning lists the paths that were left. `--force` is a yes to writing the starter's files, and to nothing else. - A directory that is new or empty is handled as before. - The README says what `--force` does in a project that exists. --- README.md | 1 + packages/cli/src/commands/init.ts | 18 ++++- packages/cli/src/engines/files.ts | 8 ++- .../cli/test/commands/init-engines.test.ts | 68 ++++++++++++++++++- 4 files changed, 89 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index bc32b43..73043c9 100644 --- a/README.md +++ b/README.md @@ -74,6 +74,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. 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. diff --git a/packages/cli/src/commands/init.ts b/packages/cli/src/commands/init.ts index 2b05427..2feac64 100644 --- a/packages/cli/src/commands/init.ts +++ b/packages/cli/src/commands/init.ts @@ -339,6 +339,8 @@ async function runInit( }) : defaultDir) const target = targetDirectory(context.cwd, dir, options.force) + // Looked at before the download, which fills the directory. + const held = existsSync(target) && readdirSync(target).length > 0 const install = options.install ?? @@ -382,8 +384,20 @@ async function runInit( let removed: string[] = [] if (engine && !options.keepEngines) { - removed = await removeEngineFiles(target, engine.remove, engine.keep) - if (removed.length > 0) { + // In a directory that held files, a path of another engine may be the + // user's own, and --force was a yes to writing, not to deleting. + const paths = await removeEngineFiles( + target, + engine.remove, + engine.keep, + held + ) + if (held && paths.length > 0) { + output.warn( + `${target} was not empty, so the files of the engines not chosen were left in place: ${paths.join(', ')}. --force writes the files of the starter and deletes nothing.` + ) + } else if (paths.length > 0) { + removed = paths output.note( `Removed the files of the engines not chosen: ${removed.join(', ')}.` ) diff --git a/packages/cli/src/engines/files.ts b/packages/cli/src/engines/files.ts index b5c973f..234fb82 100644 --- a/packages/cli/src/engines/files.ts +++ b/packages/cli/src/engines/files.ts @@ -41,11 +41,15 @@ function assertInsideSite(root: string, path: string): void { * * Every path is checked before anything is removed, so a bad one removes * nothing. A link is removed as a link, never followed. + * + * With `leave`, nothing is removed and the paths that would have been are + * returned: for a site whose files were not all put there by the starter. */ export async function removeEngineFiles( root: string, remove: string[], - keep: string[] + keep: string[], + leave = false ): Promise { for (const path of remove) assertInsideSite(root, path) @@ -66,7 +70,7 @@ export async function removeEngineFiles( } return } - await rm(file, { recursive: true, force: true }) + if (!leave) await rm(file, { recursive: true, force: true }) removed.push(path) } for (const path of remove) await visit(normalise(path)) diff --git a/packages/cli/test/commands/init-engines.test.ts b/packages/cli/test/commands/init-engines.test.ts index 4c1e544..93fe1c1 100644 --- a/packages/cli/test/commands/init-engines.test.ts +++ b/packages/cli/test/commands/init-engines.test.ts @@ -1,4 +1,4 @@ -import { existsSync, readFileSync } from 'node:fs' +import { existsSync, readFileSync, rmSync } from 'node:fs' import { join } from 'node:path' import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest' import type { Choice, CliContext, Prompter } from '../../src/context.js' @@ -9,7 +9,7 @@ import { STARTER_FILES, type FixtureRegistry, } from '../helpers/starter.js' -import { cleanTmp, tmp } from '../helpers/tmp.js' +import { cleanTmp, tmp, writeTree } from '../helpers/tmp.js' const FILES = { ...STARTER_FILES, @@ -284,6 +284,70 @@ describe('drx init --database', () => { }) }) +describe('drx init --engine --force, into a directory that holds files', () => { + const LEFT = + 'was not empty, so the files of the engines not chosen were left in place: drupal/.devtools, drupal/Makefile, drupal/.lando.yml. --force writes the files of the starter and deletes nothing.' + + test('removes no engine file, and says so', async () => { + writeTree(cwd, { + 'site/drupal/.lando.yml': 'name: mine\n', + 'site/drupal/.devtools/mine.sh': '#!/bin/sh\n', + 'site/notes.txt': 'keep me', + }) + const result = await init(['--yes', '--engine', 'ddev', '--force']) + expect(result.code).toBe(0) + expect(readFileSync(site('drupal/.devtools/mine.sh'), 'utf8')).toBe( + '#!/bin/sh\n' + ) + expect(has('drupal/.lando.yml')).toBe(true) + expect(has('drupal/Makefile')).toBe(true) + expect(has('drupal/.ddev/config.yaml')).toBe(true) + expect(readFileSync(site('notes.txt'), 'utf8')).toBe('keep me') + expect(result.stderr).toContain(`Warning: ${site()} ${LEFT}`) + expect(result.stderr).not.toContain('Removed the files') + expect(backend().engine).toBe('ddev') + }) + + test('reports nothing removed in the JSON', async () => { + writeTree(cwd, { 'site/drupal/.lando.yml': 'name: mine\n' }) + const result = await init([ + '--yes', + '--engine', + 'none', + '--base-url', + 'https://example.com', + '--force', + '--json', + ]) + expect(result.code).toBe(0) + expect(JSON.parse(result.stdout).removed).toEqual([]) + expect(has('drupal/.lando.yml')).toBe(true) + expect(has('drupal/.ddev/config.yaml')).toBe(true) + }) + + test('still removes them from a directory that exists and is empty', async () => { + writeTree(cwd, { 'site/.keep': '' }) + rmSync(site('.keep')) + const result = await init(['--yes', '--engine', 'ddev', '--force']) + expect(result.code).toBe(0) + expect(has('drupal/.lando.yml')).toBe(false) + expect(result.stderr).toContain('Removed the files of the engines') + }) + + test('says nothing with --keep-engines, which removes nothing anyway', async () => { + writeTree(cwd, { 'site/notes.txt': 'keep me' }) + const result = await init([ + '--yes', + '--engine', + 'ddev', + '--force', + '--keep-engines', + ]) + expect(result.code).toBe(0) + expect(result.stderr).not.toContain('left in place') + }) +}) + describe('drx init --engine none', () => { const URL = 'https://example.com' From 8ce2c171f0383f9fac57d88cfe818c06741c162a Mon Sep 17 00:00:00 2001 From: Stuart Clark Date: Thu, 19 Nov 2026 07:33:20 +0000 Subject: [PATCH 5/6] chore(cli): raise the revision of the starter registry The entries gained fields at this level, so a build from it has to prefer its bundled copy over a published registry that does not have them yet. --- README.md | 2 +- starters/index.json | 6 ++++-- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index e5af336..537727f 100644 --- a/README.md +++ b/README.md @@ -267,7 +267,7 @@ A registry is a URL that answers `/.json` for each starter, in the format | `install.runs` | Optional. The steps the install runs itself, left out of "Next" after one, from an engine's steps too | | `install.notes` | Optional. Lines printed under "Note" after an install | -`index.json` is `{ "revision": 1, "starters": ["quickstart"] }`. The revision is a whole number that goes up whenever the entries gain something a version of `drx` depends on. A `drx` whose bundled copy has a higher revision than the default registry reads the bundled copy, so a build made ahead of what is published keeps working. +`index.json` is `{ "revision": 2, "starters": ["quickstart"] }`. The revision is a whole number that goes up whenever the entries gain something a version of `drx` depends on. A `drx` whose bundled copy has a higher revision than the default registry reads the bundled copy, so a build made ahead of what is published keeps working. An entry in `engines` has: diff --git a/starters/index.json b/starters/index.json index ffe14f6..4d014fc 100644 --- a/starters/index.json +++ b/starters/index.json @@ -1,4 +1,6 @@ { - "revision": 1, - "starters": ["quickstart"] + "revision": 2, + "starters": [ + "quickstart" + ] } From c0eb7eea4df310bad03667a82083db8c5e2794ae Mon Sep 17 00:00:00 2001 From: Stuart Clark Date: Thu, 19 Nov 2026 07:35:33 +0000 Subject: [PATCH 6/6] style: format the starter registry index --- starters/index.json | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/starters/index.json b/starters/index.json index 4d014fc..26e1176 100644 --- a/starters/index.json +++ b/starters/index.json @@ -1,6 +1,4 @@ { "revision": 2, - "starters": [ - "quickstart" - ] + "starters": ["quickstart"] }