diff --git a/.changeset/first-release-cli.md b/.changeset/first-release-cli.md index e47f745..602e1b1 100644 --- a/.changeset/first-release-cli.md +++ b/.changeset/first-release-cli.md @@ -7,4 +7,5 @@ First release of the Druxt command-line tool, with the binary `drx`. - `drx init` creates a site from a starter in a registry, records its layout and parts in `drx.config.json` and prints what the site needs next. `--engine` chooses how the backend runs, from the engines the starter lists or `none` for a backend that exists already. `init` keeps that engine's files only and warns when its commands are not on `PATH`. - `drx module list`, `drx module search` and `drx module info` read the Druxt module registry, and in a project show what is installed and whether each module's range admits the Druxt there. - `drx info` prints the versions of the CLI, Node and the packages of each part of a project. +- At a terminal, bare `drx` opens a menu and `drx init` is a guided run that asks before it writes. `--no-interactive`, `DRX_NO_INTERACTIVE=1`, `CI` or no terminal turn every prompt off. - The registry holds one starter, `quickstart`, and the `monorepo` layout is the one available. diff --git a/.cspell-project-words.txt b/.cspell-project-words.txt index 152e2e1..c8cb243 100644 --- a/.cspell-project-words.txt +++ b/.cspell-project-words.txt @@ -1,46 +1,47 @@ # Add a term here rather than switching the check off for a file. # Words this project uses that the standard dictionaries do not carry. actionlint +alacritty +autobuild automerge citty clack +COLORTERM commitlint consola corepack cspell +cweagans dbaeumer DDEV +docroot +drush druxt druxtjs +druxtsite esbenp giget gitleaks +gpgsign interruptible knip Ksection Lando +linkify lndo +magicast markdownlint mise Nuxt nvmrc opencode -unjs -unstub -vitest -yamllint -drush PATHEXT -alacritty -COLORTERM -truecolor -wordmark -magicast -cweagans -docroot relock repatch -autobuild -linkify SARIF -gpgsign +truecolor +unjs +unstub +vitest +wordmark +yamllint diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index ec20d3b..eb1243d 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -147,6 +147,9 @@ jobs: test -f node_modules/@druxt/cli/starters/index.json ./node_modules/.bin/drx info ./node_modules/.bin/create-druxt --help + # The unattended path, as a pipeline runs it: no prompt, defaults applied. + ./node_modules/.bin/drx init pack-site --yes --no-interactive --json + test -f pack-site/drx.config.json # The one step that needs the network: a site from the real quickstart # tarball the registry entry points at. diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index 979a200..e91097a 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -233,6 +233,9 @@ test:pack: - test -f node_modules/@druxt/cli/starters/index.json - ./node_modules/.bin/drx info - ./node_modules/.bin/create-druxt --help + # The unattended path, as a pipeline runs it: no prompt, defaults applied. + - ./node_modules/.bin/drx init pack-site --yes --no-interactive --json + - test -f pack-site/drx.config.json - section_end "pack" # The one job that needs the network: it creates a site from the real diff --git a/README.md b/README.md index 537727f..fce062b 100644 --- a/README.md +++ b/README.md @@ -44,6 +44,8 @@ The tools a command starts, such as the site's package manager, come from your o ## Commands +An option goes before or after the name of its command, with its value as the next argument or after `=`. `drx --json module --type contrib list` is `drx module list --json --type=contrib`, and `drx --json info` is `drx info --json`. An option the command does not have is refused wherever it is. + ### `drx init [dir]` 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. @@ -60,18 +62,19 @@ Creates a site from a starter in a registry, writes `drx.config.json` at its roo | `--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. | | +| `--no-banner` | Do not draw the wordmark at the start of a guided run | Draw it | | `--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: +At a terminal, `init` is a guided run. It asks for whatever the flags left out, then shows a summary and waits for a yes before it writes. See [At a terminal](#at-a-terminal). A flag answers each question, so the command runs unattended: ```bash 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. +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. The message names what kept it from asking: no terminal, `--json`, or the flag or variable that turned the questions off. See [CI and scripts](#ci-and-scripts). #### Engines @@ -87,7 +90,7 @@ An engine is a way to run the site's backend on your machine. The starter lists - The prompt lists the engines whose commands are installed first, and marks the others as not installed. You can still choose one of those. `init` then warns which commands are missing, and creates the site. - With `--yes` or no terminal, the engine is the first whose commands are all installed, or the starter's first when none is. - `init` removes the files of the engines you did not choose, so a DDEV site has no `.lando.yml`. `--keep-engines` leaves them all. -- **`--force` into a project that exists.** `--force` writes the starter's files into a directory that holds files, and a file the starter also has is replaced by the starter's. It deletes nothing. The files of the engines you did not choose stay, since any of them may be your own. `init` warns with their paths. Commit or copy the project first. +- **`--force` into a project that exists.** `--force` writes the starter's files into a directory that holds files, and a file the starter also has is replaced by the starter's. It deletes nothing. The files of the engines you did not choose stay, since any of them may be your own. `init` warns with their paths, and a guided run says so in its summary before it asks. 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. @@ -97,7 +100,11 @@ 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. The steps printed under "Next" then leave out what the install ran, so nothing is set up twice. +`--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. The steps printed under "Next" then leave out what the install ran, so nothing is set up twice. A starter's entry can name a file that proves the install ran them, in `druxt.install.done`. The file must exist afterwards and hold each string the entry lists, or the steps stay listed. + +The install's own output is not shown. When the install fails, the end of that output is in the error. + +`init` warns when the directory is inside a git repository, as the site would become part of that repository's tree. ### `drx info` @@ -141,6 +148,10 @@ The Druxt version compared is the one installed in the part, or the range the pa The same table, for the modules whose name, package name or description contains the text. Case is ignored. It takes the options of `drx module list`. +### `drx module` + +With no command, at a terminal: a list of the modules that narrows as you type. Pick one and it is shown as `drx module info` shows it. Anywhere else it fails and names the commands. + ### `drx module info ` Shows one module, found by its registry name or its package name: the package, type, status, category, Druxt range, repository and website, and the backend modules it needs, with the ones that are part of Drupal core marked. When the registry marks no module as core, the text says so and `core` is `null` in the JSON. It is `false` only in a registry that marks the modules that are core. Inside a project it adds the installed version and the compatibility. It takes `--module-registry`, `--refresh` and `--json`. @@ -157,6 +168,84 @@ Usage for the CLI or one command, and the version. - Progress, warnings, errors and prompts go to stderr. - A command that fails exits with 1. With `--json` it also prints `{ "ok": false, "error": { "code", "message" } }` on stdout. +## At a terminal + +`drx` with no command opens a menu when a person is at the terminal. It names the project you are in, which it reads from `drx.config.json`. Below that are the actions for where you are: + +- Outside a project: create a site. +- Inside one: list, search or view modules, and view the project's details. Adding, removing and configuring a module and managing patches are listed as not available yet. + +Each entry runs the command it stands for, so the menu and the commands cannot differ. + +`drx init` with values missing is a guided run: + +1. It asks for the directory, the starter when the registry has more than one, the layout, the engine with its database or URL, and whether to install. +2. It lists what it will do, from the directory it will create to the files it will remove. +3. It asks before it writes. Answer no, or press Ctrl-C at any prompt, and nothing has been written. The exit code is 1. + +Every run that asked for something ends with the command that repeats it, with each choice as a flag: + +```text +Repeat this with: drx init my-site --starter quickstart --layout monorepo --engine ddev --database mariadb --no-install --yes +``` + +### The wordmark and the header + +The Druxt wordmark is drawn in two places only: at the start of a guided `init`, and above the menu. Other commands that print a report start with one line, `druxt` and the version. Both go to stderr. + +The wordmark is not drawn with `--json`, without a terminal, under `CI`, or in a terminal narrower than its 58 columns. To turn it off yourself: + +- `--no-banner` on `drx` or `drx init`, for one run. +- `"banner": false` in the [user configuration](#the-user-configuration), for every run. + +### Colour and marks + +Blue is the backend and green is the frontend: the wordmark runs from one to the other, and a part is printed in the colour of its role wherever parts are listed. The role is always there in words too. Each line on stderr starts with a mark, and the marks differ in shape as well as colour. A running step has one, a finished step another, and a warning and a failure have their own. `Warning:` and `Error:` are spelled out beside them. + +| Setting | What it does | +| -------------------- | ------------------------------------------------------------------------- | +| `NO_COLOR=1` | No colour anywhere. It wins over `FORCE_COLOR` | +| `FORCE_COLOR=1` | Colour with no terminal. `2` is 256 colours and `3` is 24-bit, `0` is off | +| `--json` | Plain text, without marks or the wordmark | +| No terminal, or `CI` | Plain text, without marks or the wordmark | + +A terminal with 16 colours gets its own blue and green. One that cannot draw Unicode gets `*`, `+`, `!` and `x` for the marks. + +## CI and scripts + +The CLI never asks anything when nobody is there to answer. Each of these is enough: + +| Condition | How | +| ---------------------- | ------------------------------------------------ | +| No terminal | stdin or stderr is not a terminal | +| `CI` is set | Most CI services set it | +| `DRX_NO_INTERACTIVE=1` | For a script run from a terminal | +| `--no-interactive` | The same, as a flag, before or after the command | +| `--json` | The command prints JSON and asks nothing | + +Prompts, the menu, the wordmark and animation are then all off. A value with a default takes it, and a value with none fails with a message naming the flag to pass. Bare `drx` prints its usage. `--yes` accepts the defaults and can be combined with any of them. `init` needs it only when no directory is given. + +A complete unattended `init`: + +```bash +npx @druxt/cli init my-site \ + --starter quickstart \ + --layout monorepo \ + --engine ddev \ + --no-install \ + --no-interactive \ + --json > result.json +``` + +stdout is the JSON result and nothing else. stderr has one plain line per step. + +| Exit code | Meaning | +| --------- | ------------------------------------------ | +| `0` | The command did what it was asked | +| `1` | It did not. The message on stderr says why | + +With `--json`, a failure prints `{ "ok": false, "error": { "code", "message" } }` on stdout, and `code` says which kind it was: `usage`, `not-available`, `registry`, `invalid-entry`, `unknown-starter`, `unknown-source`, `unknown-module`, `directory-not-empty`, `config`, `download`, `install` or `cancelled`. + ## The project configuration `drx init` writes `drx.config.json` at the root of the site. Later commands find the project by it. @@ -267,20 +356,24 @@ 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": 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. +`index.json` is `{ "revision": 3, "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: -| 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 | +| Key | What it holds | +| ----------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `name` | The name `--engine` takes. Lower case. `none` is taken | +| `label` | The engine's name as the prompt shows it | +| `needs` | Optional. What the engine needs on the machine, printed under "It needs". The label when absent | +| `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 | +| `project` | Optional. `{ "name", "files" }`: the project name the starter has, and the files that hold it. `init` writes a name made from the site's directory in its place, there and in `baseUrl`, so two sites from one starter are two projects | + +A starter can also say what it still needs from a backend that exists already, in `druxt.existingBackend.notes`. `init` prints those lines when the `none` engine is chosen. `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. @@ -322,6 +415,7 @@ The copy is kept in `~/.cache/drx`, or under `XDG_CACHE_HOME` when that is set. "registries": { "team": "https://example.com/starters" }, + "banner": false, "moduleRegistries": { "team": "https://example.com/modules.json" }, @@ -334,6 +428,7 @@ The copy is kept in `~/.cache/drx`, or under `XDG_CACHE_HOME` when that is set. - `--registry team` reads starters from that URL. `GIGET_AUTH` is giget's own variable, and giget sends it as a bearer token with every tarball it downloads. The CLI also sends it to a registry you name, and never to the public registry. - `--module-registry team` reads modules from that URL, with `GIGET_AUTH` sent to it in the same way. +- `"banner": false` stops the wordmark being drawn. - `--source` takes `npm`, `git:#`, or a name defined here. Only `npm` creates a site in this version. The others are read and answer that they are not available yet. ## Not there yet diff --git a/packages/cli/src/cli.ts b/packages/cli/src/cli.ts index 02b686e..6aad430 100644 --- a/packages/cli/src/cli.ts +++ b/packages/cli/src/cli.ts @@ -1,19 +1,37 @@ import { stripVTControlCharacters } from 'node:util' -import { defineCommand, renderUsage, runCommand, type CommandDef } from 'citty' +import { + defineCommand, + renderUsage, + runCommand, + type ArgsDef, + type CommandDef, +} from 'citty' import { infoCommand } from './commands/info.js' import { initCommand } from './commands/init.js' +import { runMenu } from './commands/menu.js' import { moduleCommand } from './commands/module.js' import { defaultContext, type CliContext, type TextStream } from './context.js' import { DrxError } from './errors.js' +import { createOutput } from './output.js' import { cliVersion } from './package-root.js' -function mainCommand(context: CliContext) { - return defineCommand({ +/** `drx` and every command under it. */ +export function mainCommand(context: CliContext): CommandDef { + return defineCommand({ meta: { name: 'drx', version: cliVersion(), description: 'The Druxt command-line tool', }, + args: { + interactive: { + type: 'boolean', + default: true, + description: 'Ask for what is missing when there is a terminal', + negativeDescription: + 'Never ask, draw or wait: for CI and scripts. DRX_NO_INTERACTIVE=1 does the same', + }, + }, subCommands: { init: initCommand(context), info: infoCommand(context), @@ -45,7 +63,9 @@ async function usage( let command = main let parent: CommandDef | undefined let path = 'drx' - for (const name of argv.filter((argument) => !argument.startsWith('-'))) { + // With the options after the command, a value is never taken for a name. + const names = optionsAfterCommand(main, argv) + for (const name of names.filter((argument) => !argument.startsWith('-'))) { const next = ( command.subCommands as Record | undefined )?.[name] @@ -61,6 +81,102 @@ async function usage( return renderUsage(command, parent) } +/** True when an option takes the argument after it as its value. */ +function takesValue(option: string, args: ArgsDef): boolean { + if (option.includes('=')) return false + const name = option.replace(/^--?/, '') + return Object.entries(args).some(([key, definition]) => { + if (definition.type !== 'string' && definition.type !== 'enum') return false + const alias = 'alias' in definition ? definition.alias : undefined + return key === name || [alias ?? []].flat().includes(name) + }) +} + +const argsOf = (command: CommandDef) => (command.args ?? {}) as ArgsDef + +/** Every command under one, each with the names that lead to it. */ +function commandPaths( + command: CommandDef, + path: string[] = [] +): { path: string[]; command: CommandDef }[] { + const below = (command.subCommands ?? {}) as Record + return [ + ...(path.length > 0 ? [{ path, command }] : []), + ...Object.entries(below).flatMap(([name, next]) => + commandPaths(next, [...path, name]) + ), + ] +} + +/** + * Where the names that lead to a command are in the arguments, when nothing + * but options comes before each. An option is read as the command itself + * defines it, so the argument after one that takes a value is its value and + * never a name. Undefined when the arguments do not name the command. + */ +function namesAt( + argv: string[], + path: string[], + args: ArgsDef +): number[] | undefined { + const found: number[] = [] + let index = 0 + for (const name of path) { + while (argv[index]?.startsWith('-') && argv[index] !== '--') { + index += takesValue(argv[index] as string, args) ? 2 : 1 + } + if (argv[index] !== name) return undefined + found.push(index) + index += 1 + } + return found +} + +/** + * The arguments with every option moved to after the command it was given + * before, so `--json module --type contrib list` reads as + * `module list --json --type contrib`. citty hands a command only what + * follows its name, and an option before it would be dropped without a + * word, or its value taken for the name of a command. The command then + * takes the option or refuses it, as it does one given after its name. The + * options of `drx` itself stay where they are. + */ +export function optionsAfterCommand( + main: CommandDef, + argv: string[] +): string[] { + // The longest run of names the arguments start with is the command. Of + // two as long, it is the one that takes more of what comes first as the + // values of its own options. + let names: number[] = [] + for (const { path, command } of commandPaths(main)) { + const found = namesAt(argv, path, argsOf(command)) + if (!found || found.length < names.length) continue + const later = (found.at(-1) as number) > (names.at(-1) ?? -1) + if (found.length > names.length || later) names = found + } + const last = names.at(-1) + if (last === undefined) return argv + + const own = new Set( + Object.entries(argsOf(main)).flatMap(([name, definition]) => + definition.type === 'boolean' ? [`--${name}`, `--no-${name}`] : [] + ) + ) + const kept: string[] = [] + const moved: string[] = [] + for (const [index, argument] of argv.slice(0, last).entries()) { + if (names.includes(index)) continue + ;(own.has(argument) ? kept : moved).push(argument) + } + return [ + ...kept, + ...names.map((index) => argv[index] as string), + ...moved, + ...argv.slice(last + 1), + ] +} + /** The code and message to report for anything a command throws. */ function describe(error: unknown): { code: string; message: string } { if (error instanceof DrxError) { @@ -81,17 +197,31 @@ function describe(error: unknown): { code: string; message: string } { } } +/** The flag that turns every prompt off. It goes before or after a command. */ +const NO_INTERACTIVE = '--no-interactive' + /** - * Runs the CLI with the given arguments and returns the exit code. It never - * exits the process or throws, so a caller decides what to do with the code. + * What says nothing may be asked although there is a terminal: `CI`, + * `DRX_NO_INTERACTIVE` or `--no-interactive`, each of which says no whatever + * the terminal is. A command then takes its defaults, and fails naming the + * flag of a value that has none. Undefined when nothing turned the questions + * off, or when there is no terminal to ask on in the first place. */ -export async function runCli( - argv: string[], - overrides: Partial = {} -): Promise { - const context = { ...defaultContext(), ...overrides } +function questionsOff(context: CliContext, argv: string[]): string | undefined { + const on = (value: string | undefined) => + value !== undefined && value !== '' && value !== '0' && value !== 'false' + if (!context.interactive) return undefined + if (argv.includes(NO_INTERACTIVE)) return NO_INTERACTIVE + if (on(context.env.DRX_NO_INTERACTIVE)) return 'DRX_NO_INTERACTIVE' + if (on(context.env.CI)) return 'CI' + return undefined +} + +/** Runs one command line in a context that is already settled. */ +async function execute(argv: string[], context: CliContext): Promise { const main = mainCommand(context) const { stdout, stderr } = context + const json = argv.includes('--json') try { if (argv.includes('--help') || argv.includes('-h')) { @@ -104,20 +234,49 @@ export async function runCli( stdout.write(`${cliVersion()}\n`) return 0 } - if (argv.length === 0) { + // Bare `drx`: a menu for a person, the usage for anything else. + if (argv.every((argument) => argument === '--no-banner')) { + if (context.interactive) { + return await runMenu(context, { banner: argv.length === 0 }, (next) => + execute(next, context) + ) + } stderr.write(`${plain(stderr, await renderUsage(main))}\n`) return 1 } - await runCommand(main, { rawArgs: argv }) + await runCommand(main, { rawArgs: optionsAfterCommand(main, argv) }) return 0 } catch (error) { const failure = describe(error) - if (argv.includes('--json')) { + if (json) { stdout.write( `${JSON.stringify({ ok: false, error: failure }, null, 2)}\n` ) } - stderr.write(`Error: ${failure.message}\n`) + // In a terminal the line carries the mark for a failure. The word stays. + const output = createOutput(context, json) + const mark = output.decorated ? `${output.err.mark('failed')} ` : '' + stderr.write(`${mark}Error: ${failure.message}\n`) return 1 } } + +/** + * Runs the CLI with the given arguments and returns the exit code. It never + * exits the process or throws, so a caller decides what to do with the code. + */ +export async function runCli( + argv: string[], + overrides: Partial = {} +): Promise { + const context = { ...defaultContext(), ...overrides } + const off = questionsOff(context, argv) + return execute( + argv.filter((argument) => argument !== NO_INTERACTIVE), + { + ...context, + interactive: context.interactive && off === undefined, + ...(off === undefined ? {} : { questionsOff: off }), + } + ) +} diff --git a/packages/cli/src/commands/info.ts b/packages/cli/src/commands/info.ts index 2c2f720..7a2b082 100644 --- a/packages/cli/src/commands/info.ts +++ b/packages/cli/src/commands/info.ts @@ -4,7 +4,7 @@ import { defineCommand, type ArgsDef } from 'citty' import { adapterFor, type PackageVersion } from '../adapters/index.js' import { assertKnownOptions } from '../args.js' import type { CliContext } from '../context.js' -import { columns, createOutput } from '../output.js' +import { columns, createOutput, type Output } from '../output.js' import { cliVersion } from '../package-root.js' import type { Part } from '../parts.js' import { @@ -46,9 +46,10 @@ async function reportPart(root: string, part: Part): Promise { } } -function partLines(part: PartReport): string[] { +function partLines(part: PartReport, output: Output): string[] { const heading = [ - `${part.role} ${part.kind} ${part.path}/`, + // The role is in words and in its colour: blue backend, green frontend. + output.out.role(part.role, `${part.role} ${part.kind} ${part.path}/`), ...columns( [ ...(part.engine ? [['Engine', part.engine]] : []), @@ -82,7 +83,7 @@ function partLines(part: PartReport): string[] { return [...heading, ...columns(rows, ' ')] } -function text(report: InfoReport, cwd: string): string { +function text(report: InfoReport, cwd: string, output: Output): string { const lines = columns([ ['drx', report.cli.version], ['Node', report.node], @@ -105,7 +106,7 @@ function text(report: InfoReport, cwd: string): string { ]) ) for (const part of project.parts) { - lines.push('', ...partLines(part)) + lines.push('', ...partLines(part, output)) } return lines.join('\n') } @@ -128,6 +129,7 @@ export function infoCommand(context: CliContext) { async run({ args: parsed, rawArgs }) { assertKnownOptions(rawArgs, args, 'info') const output = createOutput(context, parsed.json === true) + output.header() const report: InfoReport = { cli: { name: '@druxt/cli', version: cliVersion() }, @@ -143,7 +145,7 @@ export function infoCommand(context: CliContext) { } report.project = { root, ...config, parts } } - output.result(report, text(report, context.cwd)) + output.result(report, text(report, context.cwd, output)) }, }) } diff --git a/packages/cli/src/commands/init.ts b/packages/cli/src/commands/init.ts index ab2e03e..02a445e 100644 --- a/packages/cli/src/commands/init.ts +++ b/packages/cli/src/commands/init.ts @@ -1,6 +1,6 @@ import { createHash } from 'node:crypto' -import { existsSync, readdirSync, statSync } from 'node:fs' -import { isAbsolute, join, relative, resolve } from 'node:path' +import { existsSync, readFileSync, readdirSync, statSync } from 'node:fs' +import { dirname, isAbsolute, join, relative, resolve } from 'node:path' import { defineCommand, type ArgsDef } from 'citty' import { assertKnownOptions } from '../args.js' import { @@ -8,7 +8,7 @@ import { describeAlternatives, type CommandCheck, } from '../commands-on-path.js' -import type { CliContext } from '../context.js' +import type { Choice, CliContext, Prompter } from '../context.js' import { writeBackendUrl } from '../engines/backend-url.js' import { assertBaseUrl, @@ -18,6 +18,11 @@ import { type EngineChoice, } from '../engines/choose.js' import { removeEngineFiles } from '../engines/files.js' +import { + renamed, + renameProject, + siteProjectName, +} from '../engines/project-name.js' import { DrxError } from '../errors.js' import { assertLayoutAvailable, @@ -26,10 +31,10 @@ import { LAYOUTS, type Layout, } from '../layouts.js' -import { createOutput, type Output } from '../output.js' +import { columns, createOutput, type Output } from '../output.js' import { writeProjectConfig, type ProjectConfig } from '../project.js' -import { shellQuote } from '../repeat.js' -import type { StarterEntry } from '../registry/entry.js' +import type { StarterEntry, StarterInstall } from '../registry/entry.js' +import { repeatCommand, shellQuote } from '../repeat.js' import { defaultStarter, openRegistry, @@ -93,6 +98,11 @@ const args = { type: 'boolean', description: 'Keep the files of the engines that were not chosen', }, + banner: { + type: 'boolean', + description: 'Draw the wordmark at the start of a guided run', + negativeDescription: 'Do not draw the wordmark', + }, setup: { type: 'boolean', description: @@ -129,6 +139,8 @@ interface InitOptions { baseUrl?: string keepEngines: boolean setup: boolean + /** False when --no-banner was given. */ + banner?: boolean install?: boolean force: boolean yes: boolean @@ -143,25 +155,26 @@ function valueOf(name: string, value: unknown): string | undefined { return value } -async function chooseStarter( +/** One starter as a choice: its line, the Node it needs and what it is. */ +function starterChoice(entry: StarterEntry): Choice { + const { line, requires, description } = entry.druxt + const about = description ?? requires.tools.join('; ') + return { + value: entry.name, + label: entry.name, + hint: `${line}, Node ${requires.node}. ${about}`.trim(), + } +} + +/** The starter the flags name, or the default of the registry. */ +async function namedOrDefaultStarter( registry: Registry, - options: InitOptions, - context: CliContext, - canAsk: boolean + options: InitOptions ): Promise { if (options.starter) return registry.entry(options.starter) - - const names = await registry.names() - if (canAsk && names.length > 1) { - const chosen = await context.prompter.select({ - message: 'Which starter?', - choices: names.map((name) => ({ value: name, label: name })), - }) - return registry.entry(chosen) - } - const entry = await defaultStarter(registry) if (!entry) { + const names = await registry.names() throw new DrxError( 'unknown-starter', `The registry marks no starter as the default. Pass --starter with one of: ${names.join(', ')}.` @@ -170,6 +183,22 @@ async function chooseStarter( return entry } +async function askStarter( + registry: Registry, + names: string[], + context: CliContext +): Promise { + const entries: StarterEntry[] = [] + for (const name of names) entries.push(await registry.entry(name)) + const initial = entries.find((entry) => entry.druxt.default)?.name + const chosen = await context.prompter.select({ + message: 'Which starter?', + choices: entries.map(starterChoice), + ...(initial ? { initial } : {}), + }) + return entries.find((entry) => entry.name === chosen) as StarterEntry +} + async function chooseLayout( entry: StarterEntry, options: InitOptions, @@ -186,7 +215,7 @@ async function chooseLayout( label: value, ...(AVAILABLE_LAYOUTS.includes(value) ? {} - : { hint: 'not available yet' }), + : { hint: 'not available yet', disabled: true }), })), initial: own, }) @@ -281,19 +310,194 @@ function warnAboutStarter( return commands } -async function runInit( +/** Everything `init` has settled before it writes anything. */ +interface Plan { + entry: StarterEntry + layout: Layout + engine: EngineChoice | undefined + dir: string + target: string + /** True when the directory holds files already, which are the user's. */ + held: boolean + install: boolean +} + +/** The nearest directory above a path that is a git repository, if any. */ +function enclosingRepository(target: string): string | undefined { + for (let dir = dirname(target); ; dir = dirname(dir)) { + if (existsSync(join(dir, '.git'))) return dir + if (dirname(dir) === dir) return undefined + } +} + +/** + * Whether the install ran the steps its entry says it runs. An entry with no + * `done` check is taken at its word. + */ +function installFinished(target: string, install: StarterInstall): boolean { + if (!install.done) return true + let text: string + try { + text = readFileSync(join(target, install.done.file), 'utf8') + } catch { + return false + } + return (install.done.contains ?? []).every((piece) => text.includes(piece)) +} + +/** What a guided run is about to do, for the user to confirm. */ +function summary(plan: Plan, options: InitOptions, output: Output): string[] { + const { entry, engine } = plan + const rows = [ + ['Create', plan.target], + [ + 'From', + `the ${entry.name} starter (${entry.druxt.line}), ${plan.layout} layout`, + ], + ] + if (engine) { + rows.push([ + 'Backend', + engine.baseUrl + ? `a backend that exists already, at ${engine.baseUrl}` + : `${engine.name} engine${engine.database ? `, ${engine.database} database` : ''}`, + ]) + if (engine.remove.length > 0) { + rows.push( + options.keepEngines + ? ['Keep', 'the files of every engine'] + : plan.held + ? ['Keep', 'the files of every engine: the directory is not empty'] + : ['Remove', 'the files of the other engines'] + ) + } + const where = entry.druxt.backendUrl + if (engine.writeUrl && where) { + rows.push([ + 'Write', + `${where.variable}=${engine.writeUrl} to ${where.file}`, + ]) + } + } + rows.push(['Install', plan.install ? 'yes' : 'no']) + + return [ + 'This will:', + // The label of the backend row is in the colour of a backend part. + ...columns(rows, ' ').map((line) => + line.replace( + /^( +)(Backend)/, + (_, indent: string, label: string) => + `${indent}${output.err.role('backend', label)}` + ) + ), + ] +} + +/** The arguments that run the same `init` again with nothing to ask. */ +function repeatArguments(plan: Plan, options: InitOptions): string[] { + const { engine } = plan + return [ + 'init', + plan.dir, + '--starter', + plan.entry.name, + '--layout', + plan.layout, + ...(engine ? ['--engine', engine.name] : []), + ...(engine?.database ? ['--database', engine.database] : []), + ...(engine?.baseUrl ? ['--base-url', engine.baseUrl] : []), + ...(options.registry ? ['--registry', options.registry] : []), + ...(options.source ? ['--source', options.source] : []), + ...(options.keepEngines ? ['--keep-engines'] : []), + plan.install ? '--install' : '--no-install', + ...(options.force ? ['--force'] : []), + '--yes', + ] +} + +/** + * Settles every choice, asking for what the flags left out. Nothing is + * written here, so cancelling a prompt leaves the disk as it was. + */ +async function plan( + registry: Registry, options: InitOptions, context: CliContext, + canAsk: boolean +): Promise { + // With one starter, or one named, there is no starter to ask about and the + // directory prompt can offer that starter's own default. + const names = options.starter ? [] : await registry.names() + const askForStarter = canAsk && names.length > 1 + let entry = askForStarter + ? undefined + : await namedOrDefaultStarter(registry, options) + + const defaultDir = (entry ?? (await defaultStarter(registry)))?.defaultDir + const dir = + options.dir ?? + (canAsk + ? await context.prompter.text({ + message: 'Where should the site be created?', + initial: defaultDir ?? entry?.name ?? 'my-druxt-site', + }) + : (defaultDir ?? (entry as StarterEntry).name)) + 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 + + entry ??= await askStarter(registry, names, context) + const layout = await chooseLayout(entry, options, context, canAsk) + const chosen = await chooseEngine(entry, options, context, canAsk) + // The starter's project name gives way to the site's, in the URL too. + const projectName = chosen?.project ? siteProjectName(target) : undefined + const engine = + chosen?.project && projectName + ? { + ...chosen, + projectName, + ...(chosen.writeUrl + ? { + writeUrl: renamed(chosen.writeUrl, chosen.project, projectName), + } + : {}), + ...(chosen.baseUrl + ? { baseUrl: renamed(chosen.baseUrl, chosen.project, projectName) } + : {}), + } + : chosen + const install = + options.install ?? + (canAsk + ? await context.prompter.confirm({ + message: 'Install its dependencies now?', + initial: false, + }) + : false) + + return { entry, layout, engine, dir, target, held, install } +} + +async function runInit( + options: InitOptions, + shared: CliContext, output: Output ): Promise { - const canAsk = context.interactive && !options.yes + // --json never asks: a script reading stdout cannot answer. + const canAsk = shared.interactive && !options.yes && !output.json if (!options.dir && !canAsk && !options.yes) { + // Why nothing was asked: the terminal may be there and the questions off. + const why = shared.questionsOff + ? `, and ${shared.questionsOff} turns the questions off` + : shared.interactive + ? ', and nothing is asked with --json' + : ' and there is no terminal to ask on' throw new DrxError( 'usage', - 'No directory was given and there is no terminal to ask on. Pass a directory, as in "drx init my-site", or --yes to use the default of the starter.' + `No directory was given${why}. Pass a directory, as in "drx init my-site", or --yes to use the default of the starter.` ) } - if (options.setup) { throw new DrxError( 'not-available', @@ -303,7 +507,7 @@ async function runInit( 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 userConfig = await loadUserConfig(shared.env) const source = resolveSource(options.source ?? DEFAULT_SOURCE, userConfig) assertSourceAvailable(source) if (options.layout) assertLayoutAvailable(options.layout) @@ -311,6 +515,39 @@ async function runInit( ? resolveRegistryUrl(options.registry, userConfig) : undefined + // A run that will ask for the basics is a guided one, and opens with the + // wordmark. Any other run gets the small header. + const guided = + canAsk && (!options.dir || !options.layout || options.install === undefined) + const drawn = + guided && + output.banner({ + ...(options.banner === undefined ? {} : { flag: options.banner }), + ...(userConfig.banner === undefined + ? {} + : { configured: userConfig.banner }), + }) + if (!drawn) output.header() + + // The prompts are counted, so a run that asked for something can end by + // saying how to repeat it without being asked. + let asked = 0 + const counting = + (ask: (...args: T) => Promise) => + (...args: T) => { + asked += 1 + return ask(...args) + } + const context: CliContext = { + ...shared, + prompter: { + text: counting(shared.prompter.text), + select: counting(shared.prompter.select) as Prompter['select'], + search: counting(shared.prompter.search) as Prompter['search'], + confirm: counting(shared.prompter.confirm), + }, + } + const registry = await openRegistry({ ...(registryUrl ? { url: registryUrl } : {}), defaultUrl: context.defaultRegistry, @@ -319,37 +556,43 @@ async function runInit( ...(context.env.GIGET_AUTH ? { auth: context.env.GIGET_AUTH } : {}), }) if (registry.origin === 'bundled') { - output.note(`${registry.fallbackReason}`) - output.note('Reading starters from the copy bundled with this version.') + // One line: the fallback is routine while a registry cannot be read. + output.note( + `Reading starters from the copy bundled with this version. ${registry.fallbackReason}` + ) + } else if (output.decorated) { + output.done(`Read the starters from ${registry.location}.`) } else { output.note(`Reading starters from ${registry.location}.`) } - 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 = - options.dir ?? - (canAsk - ? await context.prompter.text({ - message: 'Where should the site be created?', - initial: defaultDir, - }) - : 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 + let settled: Plan + try { + settled = await plan(registry, options, context, canAsk) + if (asked > 0) { + output.line() + for (const line of summary(settled, options, output)) output.line(line) + output.line() + const go = await context.prompter.confirm({ + message: 'Create the site?', + initial: true, + }) + if (!go) throw new DrxError('cancelled', 'Cancelled.') + } + } catch (error) { + if (error instanceof DrxError && error.code === 'cancelled') { + throw new DrxError('cancelled', 'Cancelled. Nothing was written.') + } + throw error + } + const { entry, layout, engine, target, held, install } = settled - const install = - options.install ?? - (canAsk - ? await context.prompter.confirm({ - message: 'Install its dependencies now?', - initial: false, - }) - : false) + const repository = enclosingRepository(target) + if (repository) { + output.warn( + `${target} is inside the git repository at ${repository}. The site will be part of that repository's tree, and may pick up its tool versions.` + ) + } output.note(`Fetching the ${entry.name} starter from ${entry.tar}.`) try { @@ -381,6 +624,7 @@ async function runInit( `Could not fetch the ${entry.name} starter: ${detail}` ) } + output.done(`Fetched the ${entry.name} starter.`) let removed: string[] = [] if (engine && !options.keepEngines) { @@ -398,18 +642,28 @@ async function runInit( ) } else if (paths.length > 0) { removed = paths - output.note( + output.did( `Removed the files of the engines not chosen: ${removed.join(', ')}.` ) } } + if (engine?.project && engine.projectName) { + const files = await renameProject( + target, + engine.project, + engine.projectName + ) + if (files.length > 0) { + output.did( + `Named the ${engine.name} project ${engine.projectName}, in ${files.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}.` - ) + output.did(`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.` @@ -439,7 +693,7 @@ async function runInit( const commands = warnAboutStarter(entry, engine, target, context, output) if (install) { - output.note('Installing dependencies.') + output.note('Installing dependencies. This can take a few minutes.') try { await context.install(target) } catch (error) { @@ -449,13 +703,16 @@ async function runInit( `The site was created in ${target}, but installing its dependencies failed: ${detail}` ) } + output.done('Installed dependencies.') } const fromCwd = relative(context.cwd, target) const inside = fromCwd !== '' && !fromCwd.startsWith('..') // A step the install ran is not left to run: running a setup twice can // undo the first. - const ran = install ? entry.druxt.install : undefined + const declared = install ? entry.druxt.install : undefined + const finished = declared ? installFinished(target, declared) : false + const ran = finished ? declared : undefined const shown = inside && !isAbsolute(fromCwd) ? fromCwd : target const next = [ // A name that starts with a hyphen is written as a path: a shell reads @@ -468,8 +725,16 @@ async function runInit( ), ] const { requires } = entry.druxt - const needs = engine ? [engine.label] : requires.tools - const notes = [...(engine?.notes ?? []), ...(ran?.notes ?? [])] + const needs = engine ? [engine.needs] : requires.tools + const notes = [ + ...(engine?.notes ?? []), + ...(ran?.notes ?? []), + ...(declared && !finished + ? [ + 'The install did not finish the setup, so it is still listed. It needs what the lines above name.', + ] + : []), + ] output.result( { @@ -501,6 +766,13 @@ async function runInit( : []), ].join('\n') ) + + if (asked > 0) { + output.line() + output.line( + `Repeat this with: ${repeatCommand(repeatArguments(settled, options))}` + ) + } } export function initCommand(context: CliContext) { @@ -534,6 +806,7 @@ export function initCommand(context: CliContext) { if (source) options.source = source if (isLayout(parsed.layout)) options.layout = parsed.layout if (typeof parsed.install === 'boolean') options.install = parsed.install + if (typeof parsed.banner === 'boolean') options.banner = parsed.banner await runInit( options, diff --git a/packages/cli/src/commands/menu.ts b/packages/cli/src/commands/menu.ts new file mode 100644 index 0000000..f4fcaca --- /dev/null +++ b/packages/cli/src/commands/menu.ts @@ -0,0 +1,106 @@ +import type { Choice, CliContext } from '../context.js' +import { DrxError } from '../errors.js' +import { createOutput } from '../output.js' +import { findProjectRoot, loadProjectConfig } from '../project.js' +import { repeatCommand } from '../repeat.js' +import { loadUserConfig } from '../user-config.js' + +const NOT_YET = { hint: 'not available yet', disabled: true } + +const OUTSIDE: Choice[] = [ + { value: 'init', label: 'Create a site' }, + { value: 'quit', label: 'Quit' }, +] + +/** What can be done in a project. What is not built is shown, and says so. */ +const INSIDE: Choice[] = [ + { value: 'list', label: 'List the modules' }, + { value: 'search', label: 'Search the modules' }, + { value: 'show', label: "View a module's details" }, + { value: 'info', label: "View this project's details" }, + { value: 'add', label: 'Add a module', ...NOT_YET }, + { value: 'remove', label: 'Remove a module', ...NOT_YET }, + { value: 'configure', label: 'Configure a module', ...NOT_YET }, + { value: 'patches', label: 'Manage patches', ...NOT_YET }, + { value: 'quit', label: 'Quit' }, +] + +/** + * What bare `drx` shows a person at a terminal: the wordmark, the project + * they are in, and the actions that apply there. Each action is run as the + * command it stands for, through `run`, so the menu has no behaviour of its + * own to keep in step. + */ +export async function runMenu( + context: CliContext, + options: { banner: boolean }, + run: (argv: string[]) => Promise +): Promise { + const output = createOutput(context, false) + const userConfig = await loadUserConfig(context.env) + const drawn = output.banner({ + ...(options.banner ? {} : { flag: false }), + ...(userConfig.banner === undefined + ? {} + : { configured: userConfig.banner }), + }) + if (!drawn) output.header() + + const root = findProjectRoot(context.cwd) + if (root) { + const config = await loadProjectConfig(root) + output.line(`Project ${root}`) + output.line( + ` ${config.starter} starter, ${config.layout} layout, ${config.line}` + ) + for (const part of config.parts) { + const engine = part.engine ? ` ${part.engine} engine` : '' + output.line( + ` ${output.err.role(part.role, `${part.role} ${part.kind} ${part.path}/`)}${engine}` + ) + } + } else { + output.line(`No Druxt project in ${context.cwd}.`) + } + output.line() + + const choice = await context.prompter.select({ + message: 'What would you like to do?', + choices: root ? INSIDE : OUTSIDE, + }) + + /** Runs a command and then says how to run it without the menu. */ + const repeatable = async (argv: string[]) => { + const code = await run(argv) + if (code === 0) { + output.line() + output.line(`Repeat this with: ${repeatCommand(argv)}`) + } + return code + } + + switch (choice) { + case 'quit': + return 0 + // The wordmark is on the screen already. These two say how to repeat + // themselves, since only they know what was chosen along the way. + case 'init': + return run(['init', '--no-banner']) + case 'show': + return run(['module']) + case 'list': + return repeatable(['module', 'list']) + case 'info': + return repeatable(['info']) + case 'search': { + const text = await context.prompter.text({ message: 'Search for what?' }) + return repeatable(['module', 'search', text]) + } + case 'add': + case 'remove': + case 'configure': + return run(['module', choice]) + default: + throw new DrxError('not-available', `"${choice}" is not available yet.`) + } +} diff --git a/packages/cli/src/commands/module.ts b/packages/cli/src/commands/module.ts index d70a503..f3c7164 100644 --- a/packages/cli/src/commands/module.ts +++ b/packages/cli/src/commands/module.ts @@ -14,6 +14,7 @@ import { type LoadedModules, } from '../modules/registry.js' import { columns, createOutput, type Output } from '../output.js' +import { repeatCommand } from '../repeat.js' import { loadUserConfig, resolveModuleRegistryUrl } from '../user-config.js' const registryArgs = { @@ -223,6 +224,7 @@ function listCommand(context: CliContext) { async run({ args: parsed, rawArgs }) { assertKnownOptions(rawArgs, args, 'module list') const output = createOutput(context, parsed.json === true) + output.header() const loaded = await openModules(context, parsed, output) const project = await moduleProject(context.cwd) if (project) noteProject(project, output) @@ -264,6 +266,7 @@ function searchCommand(context: CliContext) { ) } const output = createOutput(context, parsed.json === true) + output.header() const loaded = await openModules(context, parsed, output) const project = await moduleProject(context.cwd) if (project) noteProject(project, output) @@ -358,7 +361,8 @@ function infoText( module: ModuleEntry, backend: ReturnType, project: ModuleProject | undefined, - states: ModuleInPart[] + states: ModuleInPart[], + output: Output ): string { const lines = [module.name] if (module.description) lines.push(module.description) @@ -404,7 +408,8 @@ function infoText( const asked = state.declared ? ` (asked for as ${state.declared})` : '' lines.push( '', - `In ${state.path}/:`, + // Every part a module is installed in is a frontend part. + output.out.role('frontend', `In ${state.path}/:`), ...columns( [ ['Installed', `${state.installed ?? 'no'}${asked}`], @@ -437,7 +442,7 @@ function infoCommand(context: CliContext) { return defineCommand({ meta: { name: 'info', - description: 'Show one module: its package, range, needs and links', + description: 'Details of one module: its package, range, needs and links', }, args, async run({ args: parsed, rawArgs }) { @@ -450,30 +455,71 @@ function infoCommand(context: CliContext) { ) } const output = createOutput(context, parsed.json === true) + output.header() const loaded = await openModules(context, parsed, output) - const module = findModule(loaded.modules, wanted) - const project = await moduleProject(context.cwd) - const states = project ? await project.state(module) : [] - const backend = backendReport(module, loaded.modules) - - output.result( - { - registry: registryReport(loaded), - project: projectReport(project), - module: { - ...rowReport(module), - repository: repositoryUrl(module), - ...(module.website ? { website: module.website } : {}), - backend, - ...(project ? { parts: states } : {}), - }, - }, - infoText(module, backend, project, states) + await showModule( + findModule(loaded.modules, wanted), + loaded, + context, + output ) }, }) } +/** Prints one module in full, with its state in the project around `cwd`. */ +async function showModule( + module: ModuleEntry, + loaded: LoadedModules, + context: CliContext, + output: Output +): Promise { + const project = await moduleProject(context.cwd) + const states = project ? await project.state(module) : [] + const backend = backendReport(module, loaded.modules) + output.result( + { + registry: registryReport(loaded), + project: projectReport(project), + module: { + ...rowReport(module), + repository: repositoryUrl(module), + ...(module.website ? { website: module.website } : {}), + backend, + ...(project ? { parts: states } : {}), + }, + }, + infoText(module, backend, project, states, output) + ) +} + +/** + * `drx module` with no command, in a terminal: a list of the modules to + * narrow by typing, then the one picked shown as `drx module info` shows it. + */ +async function pickModule( + context: CliContext, + parsed: Parsed, + output: Output +): Promise { + output.header() + const loaded = await openModules(context, parsed, output) + const listed = loaded.modules + .filter((module) => !module.archived) + .sort((a, b) => a.name.localeCompare(b.name)) + const name = await context.prompter.search({ + message: 'Which module?', + choices: listed.map((module) => ({ + value: module.name, + label: module.name, + hint: `${module.npm ?? 'not published'}. ${module.description}`.trim(), + })), + }) + await showModule(findModule(listed, name), loaded, context, output) + output.line() + output.line(`Repeat this with: ${repeatCommand(['module', 'info', name])}`) +} + /** * A command that changes a project. The name is taken now, so scripts and * documentation can rely on it, and it fails until it is built. @@ -491,18 +537,32 @@ function notAvailable(name: string, description: string) { } export function moduleCommand(context: CliContext) { + const subCommands = { + list: listCommand(context), + search: searchCommand(context), + info: infoCommand(context), + add: notAvailable('add', 'Install a module and add it to the project'), + remove: notAvailable('remove', 'Take a module out of the project'), + configure: notAvailable('configure', 'Set the options of a module'), + } return defineCommand({ meta: { name: 'module', - description: 'List, search and show the modules in the Druxt registry', + description: 'List, search and view the modules in the Druxt registry', }, - subCommands: { - list: listCommand(context), - search: searchCommand(context), - info: infoCommand(context), - add: notAvailable('add', 'Install a module and add it to the project'), - remove: notAvailable('remove', 'Take a module out of the project'), - configure: notAvailable('configure', 'Set the options of a module'), + args: registryArgs, + subCommands, + // citty runs this after a subcommand as well as in place of one. + async run({ args: parsed, rawArgs }) { + if (rawArgs.some((argument) => argument in subCommands)) return + if (!context.interactive || parsed.json === true) { + throw new DrxError( + 'usage', + 'No command specified. Run "drx module --help" for the module commands.' + ) + } + assertKnownOptions(rawArgs, registryArgs, 'module') + await pickModule(context, parsed, createOutput(context, false)) }, }) } diff --git a/packages/cli/src/context.ts b/packages/cli/src/context.ts index fc82312..833573a 100644 --- a/packages/cli/src/context.ts +++ b/packages/cli/src/context.ts @@ -12,12 +12,16 @@ import { DEFAULT_REGISTRY } from './registry/registry.js' export interface TextStream { write(chunk: string): unknown isTTY?: boolean + /** The width of the terminal, when the stream is one. */ + columns?: number } export interface Choice { value: T label: string hint?: string + /** Shown, and not selectable. */ + disabled?: boolean } /** The questions a command may ask a person at the terminal. */ @@ -28,6 +32,11 @@ export interface Prompter { choices: Choice[] initial?: T }): Promise + /** A list the user narrows by typing, for more choices than fit a screen. */ + search(question: { + message: string + choices: Choice[] + }): Promise confirm(question: { message: string; initial: boolean }): Promise } @@ -49,6 +58,11 @@ export interface CliContext { stderr: TextStream /** True when a person is at the terminal to answer a prompt. */ interactive: boolean + /** + * The flag or variable that turned the questions off when there is a + * terminal to ask on. Undefined when nothing did, or there is none. + */ + questionsOff?: string /** The running Node version, without the leading `v`. */ nodeVersion: string now: () => Date diff --git a/packages/cli/src/engines/choose.ts b/packages/cli/src/engines/choose.ts index bc56369..7effccd 100644 --- a/packages/cli/src/engines/choose.ts +++ b/packages/cli/src/engines/choose.ts @@ -9,6 +9,7 @@ import { } from '../registry/entry.js' import { isHttpUrl } from '../validate.js' import { trimEndSlashes } from '../slashes.js' +import type { EngineProject } from './project-name.js' /** What the flags say about the engine. Each is undefined when not given. */ export interface EngineOptions { @@ -20,8 +21,10 @@ export interface EngineOptions { /** 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. */ + /** The engine's name as the user reads it. */ label: string + /** What the site needs for this engine, as a phrase. */ + needs: string /** The commands the engine needs on PATH. */ commands: string[] database?: string @@ -29,6 +32,10 @@ export interface EngineChoice { baseUrl?: string /** The URL to write where the starter reads its backend URL from. */ writeUrl?: string + /** The project name the starter ships with, to be replaced by the site's. */ + project?: EngineProject + /** The site's own project name, once the directory is known. */ + projectName?: string steps: EngineStep[] notes: string[] /** The paths the chosen engine needs. */ @@ -159,11 +166,12 @@ async function existingBackend( return { name: EXISTING_BACKEND, label: `A backend that exists already, at ${baseUrl}`, + needs: `A backend that exists already, at ${baseUrl}`, commands: [], baseUrl, writeUrl: baseUrl, steps: entry.druxt.steps ?? [], - notes: [], + notes: entry.druxt.existingBackend?.notes ?? [], keep: [], remove: engines.flatMap((engine) => engine.files ?? []), } @@ -215,9 +223,11 @@ export async function chooseEngine( return { name, label: engine.label, + needs: engine.needs ?? engine.label, commands: engine.commands, ...(database ? { database } : {}), ...(engine.baseUrl ? { writeUrl: engine.baseUrl } : {}), + ...(engine.project ? { project: engine.project } : {}), steps: engine.steps, notes: engine.notes ?? [], keep: engine.files ?? [], diff --git a/packages/cli/src/engines/project-name.ts b/packages/cli/src/engines/project-name.ts new file mode 100644 index 0000000..29995df --- /dev/null +++ b/packages/cli/src/engines/project-name.ts @@ -0,0 +1,55 @@ +import { readFile, writeFile } from 'node:fs/promises' +import { basename, join } from 'node:path' + +/** The name a starter gives its engine's project, and the files that hold it. */ +export interface EngineProject { + name: string + files: string[] +} + +/** + * A project name for a site: its directory's name in lower case, with every + * run of other characters as one hyphen. Engines use the name as a host name. + */ +export function siteProjectName(target: string): string { + // One pass over the characters, so the time grows with the name's length + // whatever it holds. + let name = '' + for (const char of basename(target).toLowerCase()) { + const kept = /[a-z0-9]/.test(char) + if (kept) name += char + else if (name !== '' && !name.endsWith('-')) name += '-' + } + if (name.endsWith('-')) name = name.slice(0, -1) + return name || 'druxt-site' +} + +/** The text with the starter's project name replaced by the site's. */ +export function renamed(text: string, project: EngineProject, name: string) { + return text.split(project.name).join(name) +} + +/** + * Writes the site's project name where the starter had its own, in each file + * the starter lists. Returns the files it changed. + */ +export async function renameProject( + target: string, + project: EngineProject, + name: string +): Promise { + const changed: string[] = [] + for (const file of project.files) { + let text: string + try { + text = await readFile(join(target, file), 'utf8') + } catch { + continue + } + const next = renamed(text, project, name) + if (next === text) continue + await writeFile(join(target, file), next) + changed.push(file) + } + return changed +} diff --git a/packages/cli/src/install.ts b/packages/cli/src/install.ts index 221ab27..59e2294 100644 --- a/packages/cli/src/install.ts +++ b/packages/cli/src/install.ts @@ -23,9 +23,15 @@ export async function packageManagerOf( return MANAGERS.find((manager) => manager === declared) ?? 'npm' } +/** How much of a failed install's output is repeated in the error. */ +const OUTPUT_LINES = 40 + /** - * Runs the install of the directory's package manager. Its output goes to - * stderr, so the stdout of the CLI stays the result of the command. + * Runs the install of the directory's package manager. + * + * What it prints is kept, not shown: a starter's own install messages would + * sit in the middle of this command's. When the install fails, the end of + * its output is in the error. */ export async function installDependencies( dir: string, @@ -39,16 +45,28 @@ export async function installDependencies( const child = spawn(manager, ['install'], { cwd: dir, env, - stdio: ['ignore', process.stderr, process.stderr], + stdio: ['ignore', 'pipe', 'pipe'], shell: process.platform === 'win32', }) + let printed = '' + for (const stream of [child.stdout, child.stderr]) { + stream?.setEncoding('utf8') + stream?.on('data', (chunk: string) => (printed += chunk)) + } child.on('error', (error) => reject(new Error(`${manager} install could not start: ${error.message}`)) ) child.on('close', (code) => code === 0 ? resolve() - : reject(new Error(`${manager} install exited with code ${code}`)) + : reject( + new Error( + [ + `${manager} install exited with code ${code}`, + ...printed.trimEnd().split('\n').slice(-OUTPUT_LINES), + ].join('\n') + ) + ) ) }) } diff --git a/packages/cli/src/output.ts b/packages/cli/src/output.ts index 0fb5a58..f075cfd 100644 --- a/packages/cli/src/output.ts +++ b/packages/cli/src/output.ts @@ -1,29 +1,102 @@ import type { CliContext } from './context.js' +import { cliVersion } from './package-root.js' +import { + bannerAllowed, + presentationFor, + type Presentation, +} from './presentation.js' + +/** + * The streams that already have the wordmark or the small header. The menu + * draws one and then runs a command, which makes an output of its own. + */ +const HEADED = new WeakSet() /** * Where a command writes. The result goes to stdout: text, or JSON with * `--json`. Everything said along the way goes to stderr, so stdout can be * piped or parsed whichever form it takes. + * + * In a terminal the lines on stderr carry a mark. Anywhere else they are the + * plain sentences, with nothing added, so a log reads the same as before. */ export interface Output { readonly json: boolean - /** Progress, on stderr. */ + /** True when stderr is a terminal a person is reading. */ + readonly decorated: boolean + /** How to dress text for stdout. */ + readonly out: Presentation + /** How to dress text for stderr. */ + readonly err: Presentation + /** A step that is starting, on stderr. */ note(message: string): void + /** A step that finished. Printed in a terminal only. */ + done(message: string): void + /** Something that was done, said once it is done. Printed everywhere. */ + did(message: string): void /** Something the user should know that does not stop the command. */ warn(message: string): void + /** A line on stderr with nothing added. */ + line(message?: string): void + /** + * The small header, `druxt` and the version, for a command that prints + * more than a line or two. Printed once, in a terminal only. + */ + header(): void + /** + * The wordmark, when the terminal and the settings allow it. Returns + * whether it was drawn. The small header is not printed after it. + */ + banner(settings: { flag?: boolean; configured?: boolean }): boolean /** The result, on stdout. `text` is used unless `--json` was given. */ result(data: unknown, text: string): void } export function createOutput(context: CliContext, json: boolean): Output { + const { stdout, stderr, env } = context + const out = presentationFor(stdout, env, json) + const err = presentationFor(stderr, env, json) + const decorated = stderr.isTTY === true && !json + const write = (text: string) => stderr.write(`${text}\n`) + const marked = (kind: Parameters[0], text: string) => + decorated ? `${err.mark(kind)} ${text}` : text + let headed = false + return { json, - note: (message) => context.stderr.write(`${message}\n`), - warn: (message) => context.stderr.write(`Warning: ${message}\n`), + decorated, + out, + err, + note: (message) => write(marked('working', message)), + done: (message) => { + if (decorated) write(marked('done', message)) + }, + did: (message) => write(marked('done', message)), + warn: (message) => write(marked('warning', `Warning: ${message}`)), + line: (message = '') => write(message), + header() { + if (!decorated || headed || HEADED.has(stderr)) return + headed = true + HEADED.add(stderr) + write(marked('working', err.bold(`druxt ${cliVersion()}`))) + }, + banner({ flag, configured }) { + const allowed = bannerAllowed({ + env, + isTTY: stderr.isTTY === true, + columns: stderr.columns, + json, + flag, + configured, + }) + if (!allowed) return false + headed = true + HEADED.add(stderr) + write(`\n${err.wordmark()}\n`) + return true + }, result: (data, text) => - context.stdout.write( - json ? `${JSON.stringify(data, null, 2)}\n` : `${text}\n` - ), + stdout.write(json ? `${JSON.stringify(data, null, 2)}\n` : `${text}\n`), } } diff --git a/packages/cli/src/presentation.ts b/packages/cli/src/presentation.ts new file mode 100644 index 0000000..56db965 --- /dev/null +++ b/packages/cli/src/presentation.ts @@ -0,0 +1,200 @@ +import type { Role } from './parts.js' + +type Env = Record + +/** How many colours the terminal a stream is attached to can show. */ +export type ColorLevel = 'truecolor' | '256' | '16' | 'none' + +/** + * The colour depth to write a stream in. + * + * `--json` output is never coloured. `NO_COLOR` turns colour off and + * `FORCE_COLOR` turns it on at a depth of 1, 2 or 3, whatever the stream is. + * Otherwise colour needs a terminal that is not `dumb` and is not under `CI`, + * and the depth is read from `COLORTERM` and `TERM`. + */ +export function detectColor(options: { + env: Env + isTTY: boolean + json: boolean +}): ColorLevel { + const { env } = options + if (options.json || env.NO_COLOR) return 'none' + + const forced = env.FORCE_COLOR + if (forced !== undefined) { + if (forced === '0' || forced === 'false') return 'none' + if (forced === '3') return 'truecolor' + if (forced === '2') return '256' + return '16' + } + + if (!options.isTTY || env.CI || env.TERM === 'dumb') return 'none' + if (env.COLORTERM === 'truecolor' || env.COLORTERM === '24bit') { + return 'truecolor' + } + if (env.TERM?.includes('256color')) return '256' + return '16' +} + +/** True when the terminal can be expected to draw marks and block letters. */ +export function supportsUnicode( + env: Env, + platform: string = process.platform +): boolean { + if (platform !== 'win32') return env.TERM !== 'linux' + return Boolean( + env.WT_SESSION || + env.TERM_PROGRAM === 'vscode' || + env.TERM === 'xterm-256color' || + env.TERM === 'alacritty' + ) +} + +/** + * The Druxt wordmark, as the quickstart starter prints it. It says DRUXT.JS + * whatever the frontend is built with, since the frontend is JavaScript. + */ +export const WORDMARK = `██████╗ ██████╗ ██╗ ██╗██╗ ██╗████████╗ ██╗███████╗ +██╔══██╗██╔══██╗██║ ██║╚██╗██╔╝╚══██╔══╝ ██║██╔════╝ +██║ ██║██████╔╝██║ ██║ ╚███╔╝ ██║ ██║███████╗ +██║ ██║██╔══██╗██║ ██║ ██╔██╗ ██║ ██ ██║╚════██║ +██████╔╝██║ ██╗╚██████╔╝██╔╝ ██╗ ██║██╗╚█████╔╝███████║ +╚═════╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝ ╚═╝╚═╝ ╚════╝ ╚══════╝` + +export const WORDMARK_WIDTH = Math.max( + ...WORDMARK.split('\n').map((line) => line.length) +) + +/** The brand pair: blue for the backend, green for the frontend. */ +const BLUE = { rgb: [52, 152, 219], basic: 34 } as const +const GREEN = { rgb: [65, 184, 131], basic: 32 } as const +const YELLOW = { rgb: [241, 196, 15], basic: 33 } as const +const RED = { rgb: [231, 76, 60], basic: 31 } as const +type Colour = { rgb: readonly [number, number, number]; basic: number } + +const ESC = '\u001B[' +const RESET = `${ESC}39m` + +/** The nearest colour of the 256-colour cube. */ +function cube([r, g, b]: readonly [number, number, number]): number { + const step = (value: number) => Math.round((value / 255) * 5) + return 16 + 36 * step(r) + 6 * step(g) + step(b) +} + +function open(level: ColorLevel, colour: Colour): string { + if (level === 'truecolor') return `${ESC}38;2;${colour.rgb.join(';')}m` + if (level === '256') return `${ESC}38;5;${cube(colour.rgb)}m` + return `${ESC}${colour.basic}m` +} + +const MARKS = { + done: { unicode: '\u2714', ascii: '+', colour: GREEN }, + working: { unicode: '\u25C6', ascii: '*', colour: BLUE }, + warning: { unicode: '\u25B2', ascii: '!', colour: YELLOW }, + failed: { unicode: '\u2716', ascii: 'x', colour: RED }, +} as const + +export type Mark = keyof typeof MARKS + +/** How text is dressed for one stream. Every method returns plain text when colour is off. */ +export interface Presentation { + readonly color: ColorLevel + readonly unicode: boolean + /** One of the four marks. Each is a different shape, so it reads without colour. */ + mark(kind: Mark): string + /** Text in the colour of a part's role: blue for a backend, green for a frontend. */ + role(role: Role, text: string): string + bold(text: string): string + dim(text: string): string + /** The wordmark, running from blue on the left to green on the right. */ + wordmark(): string +} + +export function createPresentation(options: { + color: ColorLevel + unicode: boolean +}): Presentation { + const { color, unicode } = options + const on = color !== 'none' + const paint = (colour: Colour, text: string) => + on ? `${open(color, colour)}${text}${RESET}` : text + + /** The colour of one column of the wordmark. */ + const across = (column: number): Colour => { + const t = column / (WORDMARK_WIDTH - 1) + if (color === '16') return t < 0.5 ? BLUE : GREEN + const mix = (index: 0 | 1 | 2) => + Math.round(BLUE.rgb[index] + (GREEN.rgb[index] - BLUE.rgb[index]) * t) + return { rgb: [mix(0), mix(1), mix(2)], basic: BLUE.basic } + } + + return { + color, + unicode, + mark: (kind) => + paint( + MARKS[kind].colour, + unicode ? MARKS[kind].unicode : MARKS[kind].ascii + ), + role: (role, text) => paint(role === 'backend' ? BLUE : GREEN, text), + bold: (text) => (on ? `${ESC}1m${text}${ESC}22m` : text), + dim: (text) => (on ? `${ESC}2m${text}${ESC}22m` : text), + + wordmark() { + if (!unicode) return 'DRUXT.JS' + if (!on) return WORDMARK + return WORDMARK.split('\n') + .map((line) => { + let drawn = '' + let last = '' + for (const [column, character] of [...line].entries()) { + // A new code only where the colour changes keeps the line short. + const code = open(color, across(column)) + if (code !== last) drawn += code + last = code + drawn += character + } + return drawn + RESET + }) + .join('\n') + }, + } +} + +/** The presentation for a stream, from the environment it writes in. */ +export function presentationFor( + stream: { isTTY?: boolean }, + env: Env, + json: boolean +): Presentation { + return createPresentation({ + color: detectColor({ env, isTTY: stream.isTTY === true, json }), + unicode: supportsUnicode(env), + }) +} + +/** + * Whether the wordmark may be shown: in a terminal at least as wide as the + * art, not under `CI`, not with `--json`, and not turned off by `--no-banner` + * or by `"banner": false` in the user configuration. + */ +export function bannerAllowed(options: { + env: Env + isTTY: boolean + columns: number | undefined + json: boolean + /** The value of the banner flag, when it was given. */ + flag: boolean | undefined + /** The value of `banner` in the user configuration, when it is set. */ + configured: boolean | undefined +}): boolean { + return ( + options.isTTY && + !options.json && + !options.env.CI && + options.flag !== false && + options.configured !== false && + (options.columns ?? 0) >= WORDMARK_WIDTH + ) +} diff --git a/packages/cli/src/prompts.ts b/packages/cli/src/prompts.ts index b9c4e53..d47c06e 100644 --- a/packages/cli/src/prompts.ts +++ b/packages/cli/src/prompts.ts @@ -1,6 +1,6 @@ import type { Readable, Writable } from 'node:stream' -import { confirm, isCancel, select, text } from '@clack/prompts' -import type { Prompter } from './context.js' +import { autocomplete, confirm, isCancel, select, text } from '@clack/prompts' +import type { Choice, Prompter } from './context.js' import { DrxError } from './errors.js' /** The value a prompt returned, or an error when the user cancelled it. */ @@ -9,6 +9,15 @@ function answered(value: T | symbol): T { return value as T } +function clackOptions(choices: Choice[]) { + return choices.map(({ value, label, hint, disabled }) => ({ + value: value as string, + label, + ...(hint === undefined ? {} : { hint }), + ...(disabled ? { disabled } : {}), + })) +} + /** * Prompts on the terminal. They are drawn on stderr, so stdout holds only * the result of the command. @@ -31,11 +40,7 @@ export function terminalPrompter( ), select: async ({ message, choices, initial }) => { - const options = choices.map(({ value, label, hint }) => ({ - value: value as string, - label, - ...(hint === undefined ? {} : { hint }), - })) + const options = clackOptions(choices) const value = await select({ message, options, @@ -46,6 +51,17 @@ export function terminalPrompter( return answered(value) as (typeof choices)[number]['value'] }, + search: async ({ message, choices }) => { + const value = await autocomplete({ + message, + options: clackOptions(choices), + maxItems: 10, + input, + output, + }) + return answered(value) as (typeof choices)[number]['value'] + }, + confirm: async ({ message, initial }) => answered( await confirm({ message, initialValue: initial, input, output }) diff --git a/packages/cli/src/registry/entry.ts b/packages/cli/src/registry/entry.ts index 57ceec5..2a0962f 100644 --- a/packages/cli/src/registry/entry.ts +++ b/packages/cli/src/registry/entry.ts @@ -33,8 +33,10 @@ export type EngineStep = string | { run: string; dir: string } */ export interface StarterEngine { name: string - /** What the user reads in a prompt and under "It needs". */ + /** The engine's name as the user reads it in a prompt. */ label: string + /** What the engine needs on the machine, as a phrase. The label when absent. */ + needs?: string /** The commands the engine needs on PATH. */ commands: string[] /** The databases it can be set up with, the default first. */ @@ -50,6 +52,12 @@ export interface StarterEngine { files?: string[] /** The URL the engine serves the backend at, when it is fixed. */ baseUrl?: string + /** + * The project name the starter ships with, and the files that hold it. + * `init` writes a name made from the site's directory in its place, there + * and in `baseUrl`, so two sites from one starter are two projects. + */ + project?: { name: string; files: string[] } } /** Where a starter reads the URL of its backend from. */ @@ -80,11 +88,15 @@ export interface StarterDetails { * the backend exists already. */ steps?: string[] + /** One sentence on what the starter is, for the prompt that lists it. */ + description?: string /** The ways the backend can be run. Supersedes `requires.commands`. */ engines?: StarterEngine[] backendUrl?: BackendUrlTarget /** What the install of the site's package manager does past installing. */ install?: StarterInstall + /** What the starter still needs from a backend that exists already. */ + existingBackend?: { notes?: string[] } } export interface StarterInstall { @@ -92,6 +104,12 @@ export interface StarterInstall { runs?: string[] /** What to know once it has run, such as how to start the backend again. */ notes?: string[] + /** + * How to tell that the install did run those steps: a file in the site that + * exists afterwards and holds each of these strings. Without it, the install + * is taken at its word. + */ + done?: { file: string; contains?: string[] } } /** A giget registry entry with the `druxt` object `init` needs. */ @@ -173,6 +191,9 @@ function enginesProblem(value: unknown): string | undefined { if (!isNonEmptyString(engine.label)) { return `${at}.label must be a non-empty string` } + if (engine.needs !== undefined && !isNonEmptyString(engine.needs)) { + return `${at}.needs must be a non-empty string` + } if (!Array.isArray(engine.commands)) { return `${at}.commands must be an array of command names` } @@ -201,6 +222,24 @@ function enginesProblem(value: unknown): string | undefined { if (engine.baseUrl !== undefined && !isHttpUrl(engine.baseUrl)) { return `${at}.baseUrl must be an http or https URL` } + const project = engine.project + if (project !== undefined) { + if (!isRecord(project)) return `${at}.project must be an object` + if ( + typeof project.name !== 'string' || + !/^[a-z0-9][a-z0-9-]*$/.test(project.name) + ) { + return `${at}.project.name must be a lower-case name` + } + if (!Array.isArray(project.files)) { + return `${at}.project.files must be an array of paths` + } + for (const [position, file] of project.files.entries()) { + if (!isInsidePath(file)) { + return `${at}.project.files[${position}] ${INSIDE}` + } + } + } if (engine.files !== undefined) { if (!Array.isArray(engine.files)) { return `${at}.files must be an array of paths` @@ -277,6 +316,12 @@ function entryProblem(entry: unknown): string | undefined { if (druxt.steps !== undefined && !isStringArray(druxt.steps)) { return 'druxt.steps must be an array of strings' } + if ( + druxt.description !== undefined && + typeof druxt.description !== 'string' + ) { + return 'druxt.description must be a string' + } const install = druxt.install if (install !== undefined) { if (!isRecord(install)) return 'druxt.install must be an object' @@ -285,6 +330,23 @@ function entryProblem(entry: unknown): string | undefined { return `druxt.install.${key} must be an array of strings` } } + const done = install.done + if (done !== undefined) { + if (!isRecord(done)) return 'druxt.install.done must be an object' + if (!isNonEmptyString(done.file) || !isInsidePath(done.file)) { + return 'druxt.install.done.file must be a path inside the site' + } + if (done.contains !== undefined && !isStringArray(done.contains)) { + return 'druxt.install.done.contains must be an array of strings' + } + } + } + const existing = druxt.existingBackend + if (existing !== undefined) { + if (!isRecord(existing)) return 'druxt.existingBackend must be an object' + if (existing.notes !== undefined && !isStringArray(existing.notes)) { + return 'druxt.existingBackend.notes must be an array of strings' + } } return enginesProblem(druxt.engines) ?? backendUrlProblem(druxt.backendUrl) } diff --git a/packages/cli/src/repeat.ts b/packages/cli/src/repeat.ts index 34fc07b..874667f 100644 --- a/packages/cli/src/repeat.ts +++ b/packages/cli/src/repeat.ts @@ -7,3 +7,8 @@ export function shellQuote(value: string): string { if (/^[A-Za-z0-9_@%+:,./-]+$/.test(value)) return value return `'${value.replaceAll("'", `'\\''`)}'` } + +/** The command line that runs `drx` with these arguments. */ +export function repeatCommand(argv: string[]): string { + return ['drx', ...argv.map(shellQuote)].join(' ') +} diff --git a/packages/cli/src/user-config.ts b/packages/cli/src/user-config.ts index 199659d..582d6fb 100644 --- a/packages/cli/src/user-config.ts +++ b/packages/cli/src/user-config.ts @@ -22,6 +22,8 @@ export interface UserConfig { /** Module registries by name, for `--module-registry`. */ moduleRegistries: Record sources: Record + /** False to never draw the wordmark. */ + banner?: boolean } type Env = Record @@ -47,6 +49,10 @@ function configProblem(config: unknown): string | undefined { } } + if (config.banner !== undefined && typeof config.banner !== 'boolean') { + return 'banner must be true or false' + } + const sources = config.sources ?? {} if (!isRecord(sources)) return 'sources must be an object' for (const [name, source] of Object.entries(sources)) { @@ -104,6 +110,7 @@ export async function loadUserConfig(env: Env): Promise { registries: config.registries ?? {}, moduleRegistries: config.moduleRegistries ?? {}, sources: config.sources ?? {}, + ...(config.banner === undefined ? {} : { banner: config.banner }), } } diff --git a/packages/cli/test/cli.test.ts b/packages/cli/test/cli.test.ts index 021b6db..240c323 100644 --- a/packages/cli/test/cli.test.ts +++ b/packages/cli/test/cli.test.ts @@ -8,7 +8,11 @@ afterEach(cleanTmp) describe('drx', () => { test('--version prints the version and nothing else', async () => { const result = await run(['--version']) - expect(result).toEqual({ code: 0, stdout: `${cliVersion()}\n`, stderr: '' }) + expect(result).toMatchObject({ + code: 0, + stdout: `${cliVersion()}\n`, + stderr: '', + }) }) test('--help lists the commands', async () => { diff --git a/packages/cli/test/commands/init-engines.test.ts b/packages/cli/test/commands/init-engines.test.ts index 93fe1c1..ee03631 100644 --- a/packages/cli/test/commands/init-engines.test.ts +++ b/packages/cli/test/commands/init-engines.test.ts @@ -82,6 +82,7 @@ function answering(answers: Record) { return answers[message] } const prompter: Prompter = { + search: async ({ message, choices }) => answer(message, choices) as never, text: async ({ message }) => answer(message) as string, select: async ({ message, choices }) => answer(message, choices) as never, confirm: async ({ message }) => answer(message) as boolean, @@ -142,6 +143,119 @@ describe('drx init --engine', () => { expect(has('.env')).toBe(false) }) + test('names an engine by its label and lists what it needs apart from it', async () => { + await serve((druxt) => { + withEngines(druxt) + const engines = druxt.engines as Record[] + engines[0]!.label = 'Local PHP with SQLite' + engines[0]!.needs = 'PHP 8.3 or newer, and Composer' + }) + const result = await init(['--yes', '--engine', 'php']) + expect(result.stdout).toContain( + 'It needs:\n Node 16.18.1\n PHP 8.3 or newer, and Composer\n' + ) + expect(result.stdout).not.toContain('Local PHP with SQLite') + }) + + // A starter ships with one project name. Two sites made from it would otherwise be one project to the + // engine, sharing a database and an address. + test('names the project of the engine after the site, in its files and in the URL', async () => { + await serve((druxt) => { + withEngines(druxt) + const engines = druxt.engines as Record[] + engines[1]!.project = { + name: 'fixture', + files: ['drupal/.ddev/config.yaml'], + } + }) + const result = await run( + [ + 'init', + 'My Site_2', + '--yes', + '--engine', + 'ddev', + '--json', + '--registry', + registry.url, + ], + { cwd, nodeVersion: '16.18.1', findCommand: everything } + ) + expect(result.code).toBe(0) + const made = join(cwd, 'My Site_2') + expect(readFileSync(join(made, 'drupal/.ddev/config.yaml'), 'utf8')).toBe( + 'name: my-site-2\n' + ) + expect(readFileSync(join(made, '.env'), 'utf8')).toContain( + 'BASE_URL=http://my-site-2.ddev.site' + ) + }) + + test('makes a project name in one pass, whatever the directory is called', async () => { + const { siteProjectName } = + await import('../../src/engines/project-name.js') + expect(siteProjectName('/tmp/--My Shop__2--')).toBe('my-shop-2') + expect(siteProjectName('/tmp/___')).toBe('druxt-site') + const started = performance.now() + expect(siteProjectName(`/tmp/${'-'.repeat(200_000)}x`)).toBe('x') + expect(performance.now() - started).toBeLessThan(500) + }) + + test('refuses a project name that is not a plain lower-case name', async () => { + await serve((druxt) => { + withEngines(druxt) + const engines = druxt.engines as Record[] + engines[1]!.project = { + name: 'Not Plain', + files: ['drupal/.ddev/config.yaml'], + } + }) + const result = await init(['--yes', '--engine', 'ddev', '--json']) + expect(result.code).toBe(1) + expect(JSON.parse(result.stdout).error.message).toContain( + 'druxt.engines[1].project.name' + ) + }) + + // A backend that exists already is set up by nobody here, so the starter says what it still needs from it. + test('prints what the starter needs from a backend that exists already', async () => { + await serve((druxt) => { + withEngines(druxt) + druxt.existingBackend = { + notes: [ + 'Set OAUTH_CLIENT_ID in .env to the client ID of a consumer on that backend.', + ], + } + }) + const result = await init([ + '--yes', + '--engine', + 'none', + '--base-url', + 'https://example.com', + '--json', + ]) + expect(JSON.parse(result.stdout).notes).toContain( + 'Set OAUTH_CLIENT_ID in .env to the client ID of a consumer on that backend.' + ) + const local = await run( + [ + 'init', + 'local', + '--yes', + '--engine', + 'php', + '--json', + '--registry', + registry.url, + ], + { cwd, nodeVersion: '16.18.1', findCommand: everything } + ) + expect(JSON.parse(local.stdout).notes.join(' ')).not.toContain( + 'OAUTH_CLIENT_ID' + ) + }) + test('prints what the engine needs, its steps and its notes', async () => { const result = await init(['--yes', '--engine', 'ddev']) expect(result.stdout).toBe( @@ -499,6 +613,7 @@ describe('drx init at a terminal with engines', () => { const base = { 'Which layout?': 'monorepo', 'Install its dependencies now?': false, + 'Create the site?': true, } test('lists the installed engines first, marks the others, and ends with none', async () => { @@ -529,6 +644,7 @@ describe('drx init at a terminal with engines', () => { 'Which layout?', 'How should the backend run?', 'Install its dependencies now?', + 'Create the site?', ]) }) @@ -581,6 +697,7 @@ describe('drx init at a terminal with engines', () => { expect(asked.map(({ message }) => message)).toEqual([ 'Which layout?', 'Install its dependencies now?', + 'Create the site?', ]) }) }) diff --git a/packages/cli/test/commands/init-guided.test.ts b/packages/cli/test/commands/init-guided.test.ts new file mode 100644 index 0000000..55095d0 --- /dev/null +++ b/packages/cli/test/commands/init-guided.test.ts @@ -0,0 +1,295 @@ +import { existsSync, readdirSync } from 'node:fs' +import { join } from 'node:path' +import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest' +import type { CliContext } from '../../src/context.js' +import { cliVersion } from '../../src/package-root.js' +import { WORDMARK } from '../../src/presentation.js' +import { validEngines } from '../helpers/engines.js' +import { answering } from '../helpers/prompter.js' +import { run } from '../helpers/run.js' +import { + fixtureRegistry, + STARTER_FILES, + type FixtureRegistry, +} from '../helpers/starter.js' +import { cleanTmp, tmp, writeTree } from '../helpers/tmp.js' + +const FILES = { + ...STARTER_FILES, + '.env.example': 'BASE_URL=http://template.example\n', + 'drupal/.ddev/config.yaml': 'name: fixture\n', + 'drupal/.lando.yml': 'name: fixture\n', +} + +let registry: FixtureRegistry +let cwd: string + +beforeEach(async () => { + vi.stubEnv('XDG_CACHE_HOME', tmp('drx-cache-')) + vi.stubEnv('GIGET_REGISTRY', undefined) + vi.stubEnv('GIGET_AUTH', undefined) + registry = await fixtureRegistry(FILES, (entry) => { + const druxt = entry.druxt as Record + druxt.description = 'A fixture site' + druxt.engines = validEngines() + druxt.backendUrl = { + file: '.env', + template: '.env.example', + variable: 'BASE_URL', + } + }) + cwd = tmp('drx-cwd-') +}) + +afterEach(async () => { + await registry.close() + vi.unstubAllEnvs() + cleanTmp() +}) + +const ANSWERS = { + 'Where should the site be created?': 'guided', + 'Which layout?': 'monorepo', + 'How should the backend run?': 'ddev', + 'Install its dependencies now?': false, + 'Create the site?': true, +} + +/** `drx init` in a terminal 100 columns wide, with colour off. */ +const guided = ( + argv: string[], + answers: Record = ANSWERS, + overrides: Partial = {}, + options: { cancelAt?: number; columns?: number } = {} +) => { + const { prompter, asked } = answering(answers, options) + return run( + ['init', ...argv, '--registry', registry.url], + { + cwd, + env: { XDG_CONFIG_HOME: tmp('drx-config-'), NO_COLOR: '1' }, + nodeVersion: '16.18.1', + findCommand: (name) => `/usr/bin/${name}`, + prompter, + ...overrides, + }, + { columns: options.columns ?? 100 } + ).then((result) => ({ ...result, asked })) +} + +const fetched = () => + registry.requests.some(({ path }) => path === '/quickstart.tar.gz') + +describe('a guided drx init', () => { + test('asks in order, shows what it will do, and asks before it writes', async () => { + const result = await guided([]) + expect(result.code).toBe(0) + expect(result.asked.map(({ message }) => message)).toEqual([ + 'Where should the site be created?', + 'Which layout?', + 'How should the backend run?', + 'Install its dependencies now?', + 'Create the site?', + ]) + expect(result.stderr).toContain( + [ + 'This will:', + ` Create ${join(cwd, 'guided')}`, + ' From the quickstart starter (0.x), monorepo layout', + ' Backend ddev engine, mariadb database', + ' Remove the files of the other engines', + ' Write BASE_URL=http://fixture.ddev.site to .env', + ' Install no', + '', + ].join('\n') + ) + expect(existsSync(join(cwd, 'guided', 'drx.config.json'))).toBe(true) + }) + + test('says the engine files stay when the directory holds files', async () => { + writeTree(cwd, { 'guided/drupal/.lando.yml': 'name: mine\n' }) + const result = await guided(['--force']) + expect(result.code).toBe(0) + expect(result.stderr).toContain( + ' Keep the files of every engine: the directory is not empty\n' + ) + expect(result.stderr).not.toContain('Remove the files') + expect(existsSync(join(cwd, 'guided', 'drupal', '.lando.yml'))).toBe(true) + }) + + test('starts with the wordmark', async () => { + const result = await guided([]) + expect(result.stderr.startsWith(`\n${WORDMARK}\n`)).toBe(true) + expect(result.stdout).not.toContain('█') + }) + + test('ends with the command that repeats it, every choice a flag', async () => { + const result = await guided([]) + expect(result.stderr.trimEnd().split('\n').at(-1)).toBe( + `Repeat this with: drx init guided --starter quickstart --layout monorepo --engine ddev --database mariadb --registry ${registry.url} --no-install --yes` + ) + }) + + test('quotes a directory with a space and quotes in it', async () => { + const dir = `my "site" isn't` + const result = await guided([], { + ...ANSWERS, + 'Where should the site be created?': dir, + }) + expect(result.code).toBe(0) + expect(existsSync(join(cwd, dir, 'drx.config.json'))).toBe(true) + expect(result.stderr).toContain( + `Repeat this with: drx init 'my "site" isn'\\''t' --starter quickstart` + ) + }) + + test('repeats a backend that exists already with its URL, and the other flags', async () => { + writeTree(cwd, { 'guided/notes.txt': 'keep' }) + const result = await guided( + ['--force', '--keep-engines'], + { + ...ANSWERS, + 'How should the backend run?': 'none', + 'What is the URL of the backend?': 'https://cms.example.com/?a=1', + 'Install its dependencies now?': true, + }, + { install: async () => {} } + ) + expect(result.code).toBe(0) + expect(result.stderr).toContain( + `--engine none --base-url 'https://cms.example.com/?a=1' --registry ${registry.url} --keep-engines --install --force --yes` + ) + expect(result.stderr).toContain(' Keep the files of every engine') + expect(result.stderr).toContain(' Install yes') + }) + + test('lists a starter with its line, what it needs and its description', async () => { + registry.files['/index.json'] = JSON.stringify({ + starters: ['quickstart', 'second'], + }) + registry.files['/second.json'] = JSON.stringify({ + ...registry.entry, + name: 'second', + }) + const result = await guided([], { ...ANSWERS, 'Which starter?': 'second' }) + expect(result.code).toBe(0) + expect(result.asked.slice(0, 2).map(({ message }) => message)).toEqual([ + 'Where should the site be created?', + 'Which starter?', + ]) + expect(result.asked[1]?.choices?.[0]).toEqual({ + value: 'quickstart', + label: 'quickstart', + hint: '0.x, Node 16.18.1. A fixture site', + }) + }) + + test('shows the layouts that are not built as unavailable', async () => { + const result = await guided([]) + expect(result.asked[1]?.choices).toEqual([ + { value: 'monorepo', label: 'monorepo' }, + { + value: 'split', + label: 'split', + hint: 'not available yet', + disabled: true, + }, + { + value: 'workspace', + label: 'workspace', + hint: 'not available yet', + disabled: true, + }, + ]) + }) + + test('marks each step as it finishes', async () => { + const result = await guided( + [], + { ...ANSWERS, 'Install its dependencies now?': true }, + { + install: async () => {}, + } + ) + for (const line of [ + `✔ Read the starters from ${registry.url}.`, + '✔ Fetched the quickstart starter.', + '✔ Installed dependencies.', + ]) { + expect(result.stderr).toContain(line) + } + }) +}) + +describe('a guided drx init that is not confirmed', () => { + test('writes nothing when the answer is no', async () => { + const result = await guided([], { ...ANSWERS, 'Create the site?': false }) + expect(result.code).toBe(1) + expect(result.stderr.trimEnd().split('\n').at(-1)).toBe( + '✖ Error: Cancelled. Nothing was written.' + ) + expect(readdirSync(cwd)).toEqual([]) + expect(fetched()).toBe(false) + }) + + test.each([0, 1, 2, 3, 4])( + 'writes nothing when prompt %i is cancelled', + async (cancelAt) => { + const result = await guided([], ANSWERS, {}, { cancelAt }) + expect(result.asked).toHaveLength(cancelAt + 1) + expect(result.code).toBe(1) + expect(result.stderr.match(/Error/g)).toHaveLength(1) + expect(result.stderr).toContain('Error: Cancelled. Nothing was written.') + expect(readdirSync(cwd)).toEqual([]) + expect(fetched()).toBe(false) + } + ) +}) + +describe('the wordmark at init', () => { + const small = `◆ druxt ${cliVersion()}\n` + + test.each([ + ['--no-banner', ['--no-banner'], {}, {}], + ['a terminal narrower than the art', [], {}, { columns: 57 }], + ])( + 'gives way to the small header with %s', + async (_name, argv, overrides, options) => { + const result = await guided(argv, ANSWERS, overrides, options) + expect(result.code).toBe(0) + expect(result.stderr).not.toContain('█') + expect(result.stderr.startsWith(small)).toBe(true) + } + ) + + test('gives way when the user configuration turns it off', async () => { + const home = tmp('drx-config-') + writeTree(home, { 'drx/config.json': { banner: false } }) + const result = await guided([], ANSWERS, { + env: { XDG_CONFIG_HOME: home, NO_COLOR: '1' }, + }) + expect(result.stderr).not.toContain('█') + expect(result.stderr.startsWith(small)).toBe(true) + }) + + test('is not drawn when every value came from a flag, and nothing is confirmed', async () => { + const result = await guided( + ['site', '--layout', 'monorepo', '--engine', 'ddev', '--no-install'], + {} + ) + expect(result.code).toBe(0) + expect(result.asked).toEqual([]) + expect(result.stderr).not.toContain('█') + expect(result.stderr.startsWith(small)).toBe(true) + expect(result.stderr).not.toContain('This will:') + expect(result.stderr).not.toContain('Repeat this with') + }) + + test('is not drawn with --json, which asks nothing and prints JSON alone', async () => { + const result = await guided(['site', '--json'], {}) + expect(result.asked).toEqual([]) + expect(result.stderr).not.toContain('█') + expect(result.stderr).not.toContain('druxt ') + expect(JSON.parse(result.stdout).ok).toBe(true) + }) +}) diff --git a/packages/cli/test/commands/init.test.ts b/packages/cli/test/commands/init.test.ts index 69a51be..4724340 100644 --- a/packages/cli/test/commands/init.test.ts +++ b/packages/cli/test/commands/init.test.ts @@ -1,4 +1,4 @@ -import { existsSync, readFileSync } from 'node:fs' +import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs' import { join } from 'node:path' import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest' import type { CliContext, Prompter } from '../../src/context.js' @@ -54,6 +54,7 @@ function scripted(answers: unknown[]) { return answers.shift() } const prompter: Prompter = { + search: async ({ message }) => next(message) as never, text: async ({ message }) => next(message) as string, select: async ({ message }) => next(message) as never, confirm: async ({ message }) => next(message) as boolean, @@ -209,13 +210,19 @@ describe('drx init with no terminal', () => { describe('drx init at a terminal', () => { test('asks for what the flags left out', async () => { - const { prompter, asked } = scripted(['monorepo', 'asked-site', false]) + const { prompter, asked } = scripted([ + 'asked-site', + 'monorepo', + false, + true, + ]) const result = await init([], { interactive: true, prompter }) expect(result.code).toBe(0) expect(asked).toEqual([ - 'Which layout?', 'Where should the site be created?', + 'Which layout?', 'Install its dependencies now?', + 'Create the site?', ]) expect(existsSync(join(cwd, 'asked-site', 'drx.config.json'))).toBe(true) }) @@ -228,10 +235,19 @@ describe('drx init at a terminal', () => { ...registry.entry, name: 'second', }) - const { prompter, asked } = scripted(['second', 'monorepo', 'site', false]) + const { prompter, asked } = scripted([ + 'site', + 'second', + 'monorepo', + false, + true, + ]) const result = await init([], { interactive: true, prompter }) expect(result.code).toBe(0) - expect(asked[0]).toBe('Which starter?') + expect(asked.slice(0, 2)).toEqual([ + 'Where should the site be created?', + 'Which starter?', + ]) expect(readJson(join(cwd, 'site', 'drx.config.json')).starter).toBe( 'second' ) @@ -410,9 +426,14 @@ describe('drx init --registry', () => { }) expect(result.code).toBe(0) expect(result.stderr).toContain(`Could not read ${unreachable}/index.json`) - expect(result.stderr).toContain( - 'Reading starters from the copy bundled with this version.' - ) + // One line: the fallback is routine while a registry cannot be read. + expect( + result.stderr + .split('\n') + .filter((line) => line.includes('bundled with this version')) + ).toEqual([ + expect.stringContaining(`Could not read ${unreachable}/index.json`), + ]) expect(JSON.parse(result.stdout).registry).toEqual({ origin: 'bundled', location: bundled, @@ -422,6 +443,46 @@ describe('drx init --registry', () => { }) describe('drx init --install', () => { + // A starter's install may run its setup only when the tools are there. The entry says how to tell. + test('keeps a step in Next when the install did not finish it', async () => { + await registry.close() + registry = await fixtureRegistry(STARTER_FILES, (entry) => { + ;(entry.druxt as Record).install = { + runs: ['npm run setup'], + notes: ['npm run dev starts the backend again.'], + done: { file: '.env', contains: ['BASE_URL='] }, + } + }) + const skipped = await init(['one', '--yes', '--install', '--json'], { + install: vi.fn(async () => {}), + }) + const first = JSON.parse(skipped.stdout) + expect(first.next).toEqual(['cd one', 'npm run setup', 'npm run dev']) + expect(first.notes).toEqual([ + 'The install did not finish the setup, so it is still listed. It needs what the lines above name.', + ]) + + const finished = await init(['two', '--yes', '--install', '--json'], { + install: vi.fn(async (dir: string) => { + writeFileSync(join(dir, '.env'), 'BASE_URL=http://127.0.0.1:8888\n') + }), + }) + const second = JSON.parse(finished.stdout) + expect(second.next).toEqual(['cd two', 'npm run dev']) + expect(second.notes).toEqual(['npm run dev starts the backend again.']) + }) + + test('warns when the site would sit inside another git repository', async () => { + mkdirSync(join(cwd, '.git')) + const result = await init(['site', '--yes', '--json']) + expect(result.code).toBe(0) + expect(result.stderr).toContain( + `${join(cwd, 'site')} is inside the git repository at ${cwd}.` + ) + const clean = await init(['../elsewhere-' + Date.now(), '--yes', '--json']) + expect(clean.stderr).not.toContain('is inside the git repository') + }) + test('installs after the site is written', async () => { const install = vi.fn(async (dir: string) => { expect(existsSync(join(dir, 'drx.config.json'))).toBe(true) diff --git a/packages/cli/test/commands/menu.test.ts b/packages/cli/test/commands/menu.test.ts new file mode 100644 index 0000000..3a3d03a --- /dev/null +++ b/packages/cli/test/commands/menu.test.ts @@ -0,0 +1,355 @@ +import { existsSync } from 'node:fs' +import { join } from 'node:path' +import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest' +import type { CliContext } from '../../src/context.js' +import { cliVersion } from '../../src/package-root.js' +import { WORDMARK } from '../../src/presentation.js' +import { moduleRegistry } from '../helpers/modules.js' +import { answering } from '../helpers/prompter.js' +import { run } from '../helpers/run.js' +import { serve, type TestServer } from '../helpers/server.js' +import { fixtureRegistry, type FixtureRegistry } from '../helpers/starter.js' +import { cleanTmp, tmp, writeTree } from '../helpers/tmp.js' + +const MENU = 'What would you like to do?' +const BLUE = '\u001B[38;2;52;152;219m' +const GREEN = '\u001B[38;2;65;184;131m' +const RESET = '\u001B[39m' +const ART = WORDMARK.split('\n')[0] as string + +let modules: TestServer +let starters: FixtureRegistry + +beforeEach(async () => { + vi.stubEnv('XDG_CACHE_HOME', tmp('drx-cache-')) + vi.stubEnv('GIGET_REGISTRY', undefined) + vi.stubEnv('GIGET_AUTH', undefined) + modules = await serve({ '/modules.json': JSON.stringify(moduleRegistry()) }) + starters = await fixtureRegistry() +}) + +afterEach(async () => { + await modules.close() + await starters.close() + vi.unstubAllEnvs() + cleanTmp() +}) + +/** Bare `drx`, or any command, in a terminal with colour off. */ +const terminal = ( + argv: string[], + answers: Record, + overrides: Partial = {}, + options: { cancelAt?: number } = {} +) => { + const { prompter, asked } = answering(answers, options) + return run( + argv, + { + env: { XDG_CONFIG_HOME: tmp('drx-config-'), NO_COLOR: '1' }, + defaultModuleRegistry: `${modules.url}/modules.json`, + defaultRegistry: starters.url, + nodeVersion: '16.18.1', + prompter, + ...overrides, + }, + { columns: 100 } + ).then((result) => ({ ...result, asked })) +} + +function project(): string { + const root = tmp('drx-project-') + writeTree(root, { + 'drx.config.json': { + layout: 'monorepo', + line: '0.x', + starter: 'quickstart', + source: 'npm', + parts: [ + { role: 'frontend', kind: 'nuxt', path: 'nuxt' }, + { role: 'backend', kind: 'drupal', path: 'drupal', engine: 'ddev' }, + ], + }, + 'nuxt/package.json': { dependencies: { nuxt: '2.15.8' } }, + }) + return root +} + +describe('bare drx with no terminal', () => { + test('prints the usage and asks nothing', async () => { + const { prompter, asked } = answering({}) + const result = await run([], { prompter }) + expect(result.code).toBe(1) + expect(result.stderr).toContain('USAGE drx') + expect(result.stderr).not.toContain('█') + expect(asked).toEqual([]) + }) +}) + +describe('bare drx in a terminal, outside a project', () => { + test('draws the wordmark, says there is no project and offers to create a site', async () => { + const cwd = tmp() + const result = await terminal([], { [MENU]: 'quit' }, { cwd }) + expect(result.code).toBe(0) + expect(result.stderr.startsWith(`\n${WORDMARK}\n`)).toBe(true) + expect(result.stderr).toContain(`No Druxt project in ${cwd}.`) + expect(result.asked).toEqual([ + { + message: MENU, + choices: [ + { value: 'init', label: 'Create a site' }, + { value: 'quit', label: 'Quit' }, + ], + }, + ]) + expect(result.stdout).toBe('') + }) + + test('runs init from the menu, with the wordmark drawn once', async () => { + const cwd = tmp() + const result = await terminal( + [], + { + [MENU]: 'init', + 'Where should the site be created?': 'from-menu', + 'Which layout?': 'monorepo', + 'Install its dependencies now?': false, + 'Create the site?': true, + }, + { cwd } + ) + expect(result.code).toBe(0) + expect(existsSync(join(cwd, 'from-menu', 'drx.config.json'))).toBe(true) + expect(result.stderr.split(ART)).toHaveLength(2) + expect(result.stderr).toContain('Repeat this with: drx init from-menu ') + }) + + test('--no-banner leaves the small header', async () => { + const result = await terminal(['--no-banner'], { [MENU]: 'quit' }) + expect(result.code).toBe(0) + expect(result.stderr).not.toContain('█') + expect(result.stderr.startsWith(`◆ druxt ${cliVersion()}\n`)).toBe(true) + }) + + test('exits with one line when the menu is cancelled', async () => { + const result = await terminal([], {}, {}, { cancelAt: 0 }) + expect(result.code).toBe(1) + expect(result.stderr.trimEnd().split('\n').at(-1)).toBe( + '✖ Error: Cancelled.' + ) + }) +}) + +describe('bare drx in a terminal, inside a project', () => { + test('says what the project is and lists what can be done, built or not', async () => { + const cwd = project() + const result = await terminal([], { [MENU]: 'quit' }, { cwd }) + expect(result.stderr).toContain( + [ + `Project ${cwd}`, + ' quickstart starter, monorepo layout, 0.x', + ' frontend nuxt nuxt/', + ' backend drupal drupal/ ddev engine', + '', + ].join('\n') + ) + const unavailable = { hint: 'not available yet', disabled: true } + expect(result.asked[0]?.choices).toEqual([ + { value: 'list', label: 'List the modules' }, + { value: 'search', label: 'Search the modules' }, + { value: 'show', label: "View a module's details" }, + { value: 'info', label: "View this project's details" }, + { value: 'add', label: 'Add a module', ...unavailable }, + { value: 'remove', label: 'Remove a module', ...unavailable }, + { value: 'configure', label: 'Configure a module', ...unavailable }, + { value: 'patches', label: 'Manage patches', ...unavailable }, + { value: 'quit', label: 'Quit' }, + ]) + }) + + test('lists the modules, as drx module list does, and says how to repeat it', async () => { + const cwd = project() + const menu = await terminal([], { [MENU]: 'list' }, { cwd }) + const direct = await terminal(['module', 'list'], {}, { cwd }) + expect(menu.code).toBe(0) + expect(menu.stdout).toBe(direct.stdout) + expect(menu.stdout).toContain('blocks') + expect(menu.stderr.trimEnd().split('\n').at(-1)).toBe( + 'Repeat this with: drx module list' + ) + }) + + test('searches the modules for what is typed', async () => { + const result = await terminal( + [], + { [MENU]: 'search', 'Search for what?': 'unsaved content' }, + { cwd: project() } + ) + expect(result.stdout).toContain('node-preview') + expect(result.stdout).not.toContain('blocks') + expect(result.stderr).toContain( + "Repeat this with: drx module search 'unsaved content'" + ) + }) + + test('shows a module picked from a list', async () => { + const result = await terminal( + [], + { [MENU]: 'show', 'Which module?': 'blocks' }, + { cwd: project() } + ) + expect(result.code).toBe(0) + expect(result.stdout).toContain('Package druxt-blocks') + expect(result.stderr).toContain('Repeat this with: drx module info blocks') + }) + + test('shows the project, as drx info does', async () => { + const cwd = project() + const menu = await terminal([], { [MENU]: 'info' }, { cwd }) + const direct = await terminal(['info'], {}, { cwd }) + expect(menu.stdout).toBe(direct.stdout) + expect(menu.stderr).toContain('Repeat this with: drx info') + }) + + test.each(['add', 'remove', 'configure', 'patches'])( + 'says %s is not available yet if it is chosen all the same', + async (choice) => { + const result = await terminal([], { [MENU]: choice }, { cwd: project() }) + expect(result.code).toBe(1) + expect(result.stderr).toContain('is not available yet') + } + ) +}) + +describe('drx module with no subcommand', () => { + test('in a terminal is a searchable list that shows the module picked', async () => { + const result = await terminal(['module'], { 'Which module?': 'auth' }) + expect(result.code).toBe(0) + expect(result.asked[0]?.choices?.slice(0, 3)).toEqual([ + { + value: 'auth', + label: 'auth', + hint: 'druxt-auth. Authentication module for DruxtJS', + }, + { + value: 'blocks', + label: 'blocks', + hint: 'druxt-blocks. Drupal Blocks, Block Regions and more', + }, + { + value: 'ckeditor', + label: 'ckeditor', + hint: 'not published. Render CKEditor content with components', + }, + ]) + expect(result.asked[0]?.choices?.map(({ value }) => value)).not.toContain( + 'legacy' + ) + expect(result.stdout).toContain('Package druxt-auth') + expect(result.stderr.trimEnd().split('\n').at(-1)).toBe( + 'Repeat this with: drx module info auth' + ) + expect(result.stderr.startsWith(`◆ druxt ${cliVersion()}\n`)).toBe(true) + }) + + test('with no terminal fails and asks nothing', async () => { + const { prompter, asked } = answering({}) + const result = await run(['module'], { prompter }) + expect(result.code).toBe(1) + expect(result.stderr).toContain('No command specified') + expect(asked).toEqual([]) + }) + + test('with --json fails as JSON and asks nothing', async () => { + const result = await terminal(['module', '--json'], {}) + expect(result.code).toBe(1) + expect(result.asked).toEqual([]) + expect(JSON.parse(result.stdout).error.code).toBe('usage') + }) +}) + +describe('the look of a command in a terminal', () => { + test('a command that prints a report starts with the small header', async () => { + const cwd = project() + for (const argv of [ + ['info'], + ['module', 'list'], + ['module', 'info', 'blocks'], + ]) { + const result = await terminal(argv, {}, { cwd }) + expect( + result.stderr.startsWith(`◆ druxt ${cliVersion()}\n`), + argv.join(' ') + ).toBe(true) + expect(result.stderr).not.toContain('█') + } + }) + + test('--version and --help print neither header nor wordmark', async () => { + for (const argv of [['--version'], ['--help'], ['info', '--help']]) { + const result = await terminal(argv, {}) + expect(result.stderr).toBe('') + expect(result.stdout).not.toContain('█') + } + }) + + test('a part is in the colour of its role, and still says its role', async () => { + const result = await terminal( + ['info'], + {}, + { + cwd: project(), + env: { XDG_CONFIG_HOME: tmp('drx-config-'), COLORTERM: 'truecolor' }, + } + ) + expect(result.raw.stdout).toContain(`${GREEN}frontend nuxt nuxt/${RESET}`) + expect(result.raw.stdout).toContain( + `${BLUE}backend drupal drupal/${RESET}` + ) + }) + + test('nothing is coloured with NO_COLOR', async () => { + const result = await terminal(['info'], {}, { cwd: project() }) + expect(result.raw.stdout).toBe(result.stdout) + expect(result.raw.stderr).toBe(result.stderr) + }) +}) + +describe('--json in a terminal, with the banner settings at their defaults', () => { + test.each([ + [['info', '--json']], + [['module', 'list', '--json']], + [['module', 'list', '--all', '--type', 'contrib', '--json']], + [['module', 'search', 'block', '--json']], + [['module', 'info', 'blocks', '--json']], + [['module', 'info', 'nothing-like-it', '--json']], + [['module', 'add', 'blocks', '--json']], + [['module', 'remove', 'blocks', '--json']], + [['module', 'configure', 'blocks', '--json']], + [['module', '--json']], + [['init', 'site', '--yes', '--json']], + [['init', 'site', '--json']], + [['init', '--json']], + [['init', 'site', '--yes', '--layout', 'split', '--json']], + [['init', 'site', '--yes', '--setup', '--json']], + [['info', '--json', '--unknown']], + ])('drx %j prints one JSON document on stdout', async (argv) => { + for (const cwd of [tmp(), project()]) { + const result = await terminal( + argv, + {}, + { + cwd, + env: { XDG_CONFIG_HOME: tmp('drx-config-'), COLORTERM: 'truecolor' }, + } + ) + expect(result.asked).toEqual([]) + expect( + () => JSON.parse(result.raw.stdout), + result.raw.stdout + ).not.toThrow() + expect(result.raw.stderr).not.toContain('█') + expect(result.raw.stderr).not.toContain('\u001B[') + } + }) +}) diff --git a/packages/cli/test/e2e/quickstart.test.ts b/packages/cli/test/e2e/quickstart.test.ts index 68520bf..0dc9187 100644 --- a/packages/cli/test/e2e/quickstart.test.ts +++ b/packages/cli/test/e2e/quickstart.test.ts @@ -63,8 +63,12 @@ describe.skipIf(process.env.DRX_E2E !== '1')('the quickstart starter', () => { expect( existsSync(join(site, 'drupal/.ddev/commands/web/drupal-install')) ).toBe(true) + // The project carries the site's name, not the starter's, in its file and in the URL. expect(readFileSync(join(site, '.env'), 'utf8')).toContain( - 'BASE_URL=https://druxt-quickstart.lndo.site' + 'BASE_URL=https://site.lndo.site' + ) + expect(readFileSync(join(site, 'drupal/.lando.yml'), 'utf8')).toContain( + 'name: site' ) }, 120_000) diff --git a/packages/cli/test/helpers/prompter.ts b/packages/cli/test/helpers/prompter.ts new file mode 100644 index 0000000..bd144f6 --- /dev/null +++ b/packages/cli/test/helpers/prompter.ts @@ -0,0 +1,37 @@ +import type { Choice, Prompter } from '../../src/context.js' +import { DrxError } from '../../src/errors.js' + +export interface Asked { + message: string + choices?: Choice[] +} + +/** + * A prompter that answers each question by its message and records what it + * was asked. `cancelAt` makes the prompt at that position behave as Ctrl-C + * does, and an unexpected question fails the test. + */ +export function answering( + answers: Record, + options: { cancelAt?: number } = {} +): { prompter: Prompter; asked: Asked[] } { + const asked: Asked[] = [] + const answer = (message: string, choices?: Choice[]) => { + if (asked.length === options.cancelAt) { + asked.push({ message }) + throw new DrxError('cancelled', 'Cancelled.') + } + asked.push(choices ? { message, choices } : { message }) + if (!(message in answers)) throw new Error(`Unexpected prompt: ${message}`) + return answers[message] + } + return { + asked, + prompter: { + text: async ({ message }) => answer(message) as string, + select: async ({ message, choices }) => answer(message, choices) as never, + search: async ({ message, choices }) => answer(message, choices) as never, + confirm: async ({ message }) => answer(message) as boolean, + }, + } +} diff --git a/packages/cli/test/helpers/run.ts b/packages/cli/test/helpers/run.ts index 966a2d6..f54ec43 100644 --- a/packages/cli/test/helpers/run.ts +++ b/packages/cli/test/helpers/run.ts @@ -8,6 +8,8 @@ export interface RunResult { code: number stdout: string stderr: string + /** The output with its escape codes left in. */ + raw: { stdout: string; stderr: string } } /** @@ -16,17 +18,20 @@ export interface RunResult { */ export async function run( argv: string[], - overrides: Partial = {} + overrides: Partial = {}, + terminal?: { columns: number } ): Promise { let stdout = '' let stderr = '' + // A terminal: both streams say so, and somebody is there to answer. + const tty = terminal ? { isTTY: true, columns: terminal.columns } : {} const code = await runCli(argv, { cwd: tmp(), env: { XDG_CONFIG_HOME: tmp('drx-config-') }, cacheDir: tmp('drx-cache-'), - stdout: { write: (chunk) => (stdout += chunk) }, - stderr: { write: (chunk) => (stderr += chunk) }, - interactive: false, + stdout: { write: (chunk) => (stdout += chunk), ...tty }, + stderr: { write: (chunk) => (stderr += chunk), ...tty }, + interactive: terminal !== undefined, nodeVersion: '24.18.0', // A test that serves its own default registry is about that registry. With // no bundled copy to compare revisions with, the one served is read. @@ -39,5 +44,6 @@ export async function run( code, stdout: stripVTControlCharacters(stdout), stderr: stripVTControlCharacters(stderr), + raw: { stdout, stderr }, } } diff --git a/packages/cli/test/install.test.ts b/packages/cli/test/install.test.ts index a1d1620..2becc94 100644 --- a/packages/cli/test/install.test.ts +++ b/packages/cli/test/install.test.ts @@ -49,6 +49,22 @@ describe.skipIf(process.platform === 'win32')('installDependencies', () => { expect(readFileSync(join(dir, 'called-with.txt'), 'utf8')).toBe('install\n') }) + test('says what the manager printed when the install fails', async () => { + const dir = tmp() + writeTree(dir, { 'package.json': {} }) + const bin = tmp('drx-bin-') + writeTree(bin, { npm: '#!/bin/sh\necho "peer conflict: boom"\nexit 1\n' }) + chmodSync(join(bin, 'npm'), 0o755) + await expect( + installDependencies(dir, { + ...process.env, + PATH: `${bin}:${process.env.PATH}`, + }) + ).rejects.toThrow( + /npm install exited with code 1[\s\S]*peer conflict: boom/ + ) + }) + test('fails when the install exits non-zero', async () => { const dir = tmp() writeTree(dir, { 'package.json': {} }) diff --git a/packages/cli/test/non-interactive.test.ts b/packages/cli/test/non-interactive.test.ts new file mode 100644 index 0000000..e75fffb --- /dev/null +++ b/packages/cli/test/non-interactive.test.ts @@ -0,0 +1,437 @@ +import { existsSync } from 'node:fs' +import { join } from 'node:path' +import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest' +import type { Prompter } from '../src/context.js' +import { validEngines } from './helpers/engines.js' +import { moduleRegistry } from './helpers/modules.js' +import { run } from './helpers/run.js' +import { serve, type TestServer } from './helpers/server.js' +import { fixtureRegistry, type FixtureRegistry } from './helpers/starter.js' +import { cleanTmp, tmp } from './helpers/tmp.js' + +let modules: TestServer +let starters: FixtureRegistry + +beforeEach(async () => { + vi.stubEnv('XDG_CACHE_HOME', tmp('drx-cache-')) + vi.stubEnv('GIGET_REGISTRY', undefined) + vi.stubEnv('GIGET_AUTH', undefined) + modules = await serve({ '/modules.json': JSON.stringify(moduleRegistry()) }) + starters = await fixtureRegistry(undefined, (entry) => { + ;(entry.druxt as Record).engines = validEngines() + }) +}) + +afterEach(async () => { + await modules.close() + await starters.close() + vi.unstubAllEnvs() + cleanTmp() +}) + +/** The four ways a run is told that nobody is there to answer. */ +const CONDITIONS = [ + { + name: '--no-interactive', + flag: ['--no-interactive'], + env: {}, + terminal: true, + }, + { + name: 'DRX_NO_INTERACTIVE=1', + flag: [], + env: { DRX_NO_INTERACTIVE: '1' }, + terminal: true, + }, + { name: 'CI=true', flag: [], env: { CI: 'true' }, terminal: true }, + { name: 'no terminal', flag: [], env: {}, terminal: false }, +] as const + +/** Every command and subcommand, with the exit code it has unattended. */ +const COMMANDS: { argv: string[]; code: number; says?: string }[] = [ + { argv: [], code: 1, says: 'USAGE drx' }, + { argv: ['--no-banner'], code: 1, says: 'USAGE drx' }, + { argv: ['--help'], code: 0 }, + { argv: ['--version'], code: 0 }, + { argv: ['init'], code: 1, says: 'Pass a directory' }, + { argv: ['init', 'site'], code: 0 }, + { argv: ['init', 'site', '--yes'], code: 0 }, + { argv: ['init', '--yes'], code: 0 }, + { argv: ['init', 'site', '--engine', 'none'], code: 1, says: '--base-url' }, + { argv: ['init', 'site', '--engine', 'php', '--json'], code: 0 }, + { argv: ['info'], code: 0 }, + { argv: ['info', '--json'], code: 0 }, + { argv: ['--json', 'info'], code: 0 }, + { argv: ['--engine', 'none', 'init', 'site'], code: 1, says: '--base-url' }, + { argv: ['--engine=none', 'init', 'site'], code: 1, says: '--base-url' }, + { argv: ['--yes', 'init'], code: 0 }, + { argv: ['module'], code: 1, says: 'No command specified' }, + { argv: ['module', 'list'], code: 0 }, + { argv: ['module', '--json', 'list'], code: 0 }, + { argv: ['module', '--refresh', 'search', 'block'], code: 0 }, + { argv: ['--json', 'module', 'list'], code: 0 }, + { argv: ['module', '--type', 'contrib', 'list'], code: 0 }, + { argv: ['module', '--type=contrib', 'list'], code: 0 }, + { argv: ['--type', 'contrib', 'module', 'list'], code: 0 }, + { + argv: ['module', '--category', 'site-and-layout', 'search', 'block'], + code: 0, + }, + { argv: ['module', 'search', 'block'], code: 0 }, + { argv: ['module', 'search'], code: 1, says: 'Give the text to search for' }, + { argv: ['module', 'info', 'blocks'], code: 0 }, + { argv: ['module', 'info'], code: 1, says: 'Give the name of a module' }, + { argv: ['module', 'add', 'blocks'], code: 1, says: 'not available yet' }, + { argv: ['module', 'remove', 'blocks'], code: 1, says: 'not available yet' }, + { + argv: ['module', 'configure', 'blocks'], + code: 1, + says: 'not available yet', + }, +] + +describe.each(CONDITIONS)('with $name', (condition) => { + test.each(COMMANDS)( + 'drx $argv asks nothing', + async ({ argv, code, says }) => { + const ask = vi.fn(() => { + throw new Error('A prompt was shown.') + }) + const prompter = { + text: ask, + select: ask, + search: ask, + confirm: ask, + } as unknown as Prompter + const cwd = tmp('drx-cwd-') + + const result = await run( + [...argv, ...condition.flag], + { + cwd, + env: { XDG_CONFIG_HOME: tmp('drx-config-'), ...condition.env }, + defaultRegistry: starters.url, + defaultModuleRegistry: `${modules.url}/modules.json`, + prompter, + findCommand: () => undefined, + }, + condition.terminal ? { columns: 100 } : undefined + ) + + expect(ask).not.toHaveBeenCalled() + expect(result.stderr).not.toContain('A prompt was shown.') + expect(result.raw.stderr).not.toContain('█') + expect(result.code, result.stderr).toBe(code) + if (says) expect(result.stderr).toContain(says) + if (argv[0] === 'init' && code === 0) { + const dir = argv.includes('site') ? 'site' : 'my-druxt-site' + expect(existsSync(join(cwd, dir, 'drx.config.json'))).toBe(true) + } + } + ) +}) + +describe('an option given before the command of a group', () => { + let cwd: string + beforeEach(() => { + cwd = tmp('drx-cwd-') + }) + const unattended = (argv: string[]) => + run(argv, { + cwd, + env: { XDG_CONFIG_HOME: tmp('drx-config-') }, + defaultModuleRegistry: `${modules.url}/modules.json`, + now: () => new Date('2026-11-18T00:00:00Z'), + }) + + test.each([ + [ + ['module', '--json', 'list'], + ['module', 'list', '--json'], + ], + [ + ['module', '--json', 'search', 'block'], + ['module', 'search', 'block', '--json'], + ], + [ + ['module', '--json', 'info', 'blocks'], + ['module', 'info', 'blocks', '--json'], + ], + [ + ['module', '--json', '--refresh', 'list', '--all'], + ['module', 'list', '--all', '--json', '--refresh'], + ], + [ + ['module', '--type', 'contrib', '--json', 'list'], + ['module', 'list', '--type', 'contrib', '--json'], + ], + [ + ['module', '--type=contrib', '--json', 'list'], + ['module', 'list', '--type', 'contrib', '--json'], + ], + [ + ['module', '--category', 'site-and-layout', '--json', 'list'], + ['module', 'list', '--category', 'site-and-layout', '--json'], + ], + [ + ['module', '--json', '--type', 'contrib', 'search', 'e'], + ['module', 'search', 'e', '--json', '--type', 'contrib'], + ], + [ + ['--json', 'module', 'list'], + ['module', 'list', '--json'], + ], + [ + ['--json', '--type', 'contrib', 'module', '--all', 'list'], + ['module', 'list', '--json', '--type', 'contrib', '--all'], + ], + [ + ['--category=site-and-layout', 'module', '--json', 'list'], + ['module', 'list', '--category', 'site-and-layout', '--json'], + ], + [ + ['--json', 'module', 'info', 'blocks'], + ['module', 'info', 'blocks', '--json'], + ], + [ + ['--json', 'info'], + ['info', '--json'], + ], + ])('drx %j is drx %j', async (before, after) => { + const [first, second] = [await unattended(before), await unattended(after)] + expect(first.code, first.stderr).toBe(0) + expect(JSON.parse(first.stdout)).toEqual(JSON.parse(second.stdout)) + expect(first.stdout).toBe(second.stdout) + }) + + test('drx module --module-registry list reads that registry', async () => { + const other = await serve({ + '/other.json': JSON.stringify({ + schemaVersion: 1, + modules: [moduleRegistry().modules[1]], + }), + }) + try { + const url = `${other.url}/other.json` + for (const form of [ + ['module', '--module-registry', url, 'list'], + ['module', `--module-registry=${url}`, 'list'], + ['module', '--module-registry', url, '--json', 'list'], + ]) { + const before = await unattended(form) + const after = await unattended([ + 'module', + 'list', + '--module-registry', + url, + ...(form.includes('--json') ? ['--json'] : []), + ]) + expect(before.code, before.stderr).toBe(0) + expect(before.stdout).toBe(after.stdout) + expect(before.stdout).toContain('blocks') + expect(before.stdout).not.toContain('druxt-auth') + expect(before.stderr).toContain(url) + } + } finally { + await other.close() + } + }) + + test('a filter before the command leaves out what it does after it', async () => { + for (const form of [ + ['module', '--type', 'contrib', 'list'], + ['module', '--type=contrib', 'list'], + ['--type', 'contrib', 'module', 'list'], + ]) { + const [before, after] = [ + await unattended(form), + await unattended(['module', 'list', '--type', 'contrib']), + ] + expect(before.code, before.stderr).toBe(0) + expect(before.stdout).toBe(after.stdout) + expect(before.stdout).toContain('ckeditor') + expect(before.stdout).not.toContain('druxt-auth') + } + }) + + test('drx --module-registry module list reads that registry', async () => { + const other = await serve({ + '/other.json': JSON.stringify({ + schemaVersion: 1, + modules: [moduleRegistry().modules[1]], + }), + }) + try { + const url = `${other.url}/other.json` + const after = await unattended([ + 'module', + 'list', + '--module-registry', + url, + ]) + for (const form of [ + ['--module-registry', url, 'module', 'list'], + [`--module-registry=${url}`, 'module', 'list'], + ]) { + const before = await unattended(form) + expect(before.code, before.stderr).toBe(0) + expect(before.stdout).toBe(after.stdout) + expect(before.stdout).not.toContain('druxt-auth') + } + } finally { + await other.close() + } + }) + + test('drx --json info prints the JSON that drx info --json does', async () => { + const [before, after] = [ + await unattended(['--json', 'info']), + await unattended(['info', '--json']), + ] + expect(before.code, before.stderr).toBe(0) + expect(JSON.parse(before.stdout)).toEqual(JSON.parse(after.stdout)) + expect(before.stderr).toBe(after.stderr) + }) + + test('an option before init is the option after it', async () => { + const created = await run( + ['--json', '--yes', '--registry', starters.url, 'init', 'site'], + { cwd, env: { XDG_CONFIG_HOME: tmp('drx-config-') } } + ) + expect(created.code, created.stderr).toBe(0) + expect(JSON.parse(created.stdout)).toMatchObject({ ok: true }) + expect(existsSync(join(cwd, 'site', 'drx.config.json'))).toBe(true) + }) + + test('an option the command does not have is refused, wherever it is', async () => { + for (const form of [ + ['module', '--bogus', 'list'], + ['--bogus', 'module', 'list'], + ['--bogus', 'info'], + ['--type=contrib', 'info'], + ]) { + const result = await unattended(form) + const option = form.find((argument) => argument.startsWith('-')) ?? '' + expect(result.code).toBe(1) + expect(result.stderr).toContain(`Unknown option ${option.split('=')[0]}`) + } + }) + + test('--help with an option and its value before the command is that command', async () => { + const result = await unattended([ + 'module', + '--type', + 'contrib', + 'list', + '--help', + ]) + expect(result.code).toBe(0) + expect(result.stdout).toContain('USAGE drx module list') + }) + + test('a failure with --json before the command is still JSON', async () => { + const result = await unattended(['module', '--json', 'info', 'nothing']) + expect(result.code).toBe(1) + expect(JSON.parse(result.stdout)).toMatchObject({ + ok: false, + error: { code: 'unknown-module' }, + }) + }) +}) + +describe('drx init with no directory says why it did not ask', () => { + const TAIL = + ' Pass a directory, as in "drx init my-site", or --yes to use the default of the starter.' + test.each([ + [ + '--no-interactive', + ['--no-interactive'], + {}, + true, + 'No directory was given, and --no-interactive turns the questions off.', + ], + [ + 'DRX_NO_INTERACTIVE=1', + [], + { DRX_NO_INTERACTIVE: '1' }, + true, + 'No directory was given, and DRX_NO_INTERACTIVE turns the questions off.', + ], + [ + 'CI=true', + [], + { CI: 'true' }, + true, + 'No directory was given, and CI turns the questions off.', + ], + [ + '--json', + ['--json'], + {}, + true, + 'No directory was given, and nothing is asked with --json.', + ], + [ + 'no terminal', + [], + {}, + false, + 'No directory was given and there is no terminal to ask on.', + ], + [ + 'no terminal and DRX_NO_INTERACTIVE=1', + [], + { DRX_NO_INTERACTIVE: '1' }, + false, + 'No directory was given and there is no terminal to ask on.', + ], + ] as const)('with %s', async (_name, flag, env, terminal, message) => { + const result = await run( + ['init', ...flag], + { + cwd: tmp('drx-cwd-'), + env: { XDG_CONFIG_HOME: tmp('drx-config-'), ...env }, + defaultRegistry: starters.url, + }, + terminal ? { columns: 100 } : undefined + ) + expect(result.code).toBe(1) + expect(result.stderr).toContain(`Error: ${message}${TAIL}`) + }) +}) + +describe('--no-interactive', () => { + test('goes before or after the command, and with --yes', async () => { + for (const argv of [ + ['--no-interactive', 'init', '--yes'], + ['init', '--no-interactive', '--yes'], + ['init', '--yes', '--no-interactive'], + ]) { + const cwd = tmp('drx-cwd-') + const result = await run( + argv, + { cwd, defaultRegistry: starters.url }, + { columns: 100 } + ) + expect(result.code, argv.join(' ')).toBe(0) + expect(existsSync(join(cwd, 'my-druxt-site'))).toBe(true) + } + }) + + test.each(['0', 'false', ''])( + 'DRX_NO_INTERACTIVE=%j leaves a terminal interactive', + async (value) => { + const ask = vi.fn(async () => 'quit') + const result = await run( + [], + { + env: { XDG_CONFIG_HOME: tmp(), DRX_NO_INTERACTIVE: value }, + prompter: { select: ask } as unknown as Prompter, + }, + { columns: 100 } + ) + expect(result.code).toBe(0) + expect(ask).toHaveBeenCalledOnce() + } + ) +}) diff --git a/packages/cli/test/options-before.test.ts b/packages/cli/test/options-before.test.ts new file mode 100644 index 0000000..fc55b1c --- /dev/null +++ b/packages/cli/test/options-before.test.ts @@ -0,0 +1,104 @@ +import type { ArgsDef, CommandDef } from 'citty' +import { describe, expect, test } from 'vitest' +import { mainCommand, optionsAfterCommand } from '../src/cli.js' +import { defaultContext } from '../src/context.js' + +const main = mainCommand(defaultContext()) + +/** Every command of the tree with the names that lead to it. */ +function commands( + command: CommandDef, + path: string[] = [] +): { path: string[]; args: ArgsDef }[] { + const below = (command.subCommands ?? {}) as Record + return [ + ...(path.length > 0 + ? [{ path, args: (command.args ?? {}) as ArgsDef }] + : []), + ...Object.entries(below).flatMap(([name, next]) => + commands(next, [...path, name]) + ), + ] +} + +/** Each way an option of a command is written, as the arguments it takes. */ +function forms(args: ArgsDef): string[][] { + return Object.entries(args).flatMap(([name, definition]) => { + if (definition.type === 'positional') return [] + const alias = 'alias' in definition ? definition.alias : undefined + const names = [`--${name}`, ...[alias ?? []].flat().map((one) => `-${one}`)] + if (definition.type === 'boolean') { + return [...names.map((flag) => [flag]), [`--no-${name}`]] + } + return [ + ...names.map((flag) => [flag, 'a-value']), + [`--${name}=a-value`], + // A value that is the name of a command is still a value. + ...names.map((flag) => [flag, 'list']), + ...names.map((flag) => [flag, 'info']), + ] + }) +} + +const CASES = commands(main).flatMap(({ path, args }) => + forms(args).map((option) => ({ path, option })) +) + +describe('an option before a command is the option after it', () => { + test('the tree has commands and options to check', () => { + expect(CASES.length).toBeGreaterThan(30) + expect(CASES.some(({ path }) => path.length === 2)).toBe(true) + }) + + test.each(CASES)('drx $path with $option', ({ path, option }) => { + const after = [...path, ...option, 'something'] + expect(optionsAfterCommand(main, after)).toEqual(after) + // Before every name of the path, and between any two of them. + for (let at = 0; at < path.length; at++) { + const before = [...path.slice(0, at), ...option, ...path.slice(at)] + expect(optionsAfterCommand(main, [...before, 'something'])).toEqual(after) + } + }) + + test('options keep their order, and what follows -- is left alone', () => { + expect( + optionsAfterCommand(main, [ + '--json', + 'module', + '--type', + 'contrib', + 'list', + '--all', + '--', + '--refresh', + ]) + ).toEqual([ + 'module', + 'list', + '--json', + '--type', + 'contrib', + '--all', + '--', + '--refresh', + ]) + }) + + test('the options of drx itself stay before the command', () => { + expect(optionsAfterCommand(main, ['--interactive', 'info'])).toEqual([ + '--interactive', + 'info', + ]) + }) + + test('arguments that name no command are left as they are', () => { + for (const argv of [ + ['launch'], + ['--json'], + ['--type', 'x', 'launch'], + [], + ]) { + expect(optionsAfterCommand(main, argv)).toEqual(argv) + } + }) +}) diff --git a/packages/cli/test/output.test.ts b/packages/cli/test/output.test.ts new file mode 100644 index 0000000..acf88b2 --- /dev/null +++ b/packages/cli/test/output.test.ts @@ -0,0 +1,120 @@ +import { describe, expect, test } from 'vitest' +import type { CliContext } from '../src/context.js' +import { createOutput } from '../src/output.js' +import { cliVersion } from '../src/package-root.js' + +function context(options: { tty: boolean; env?: Record }) { + let stdout = '' + let stderr = '' + const made = { + env: options.env ?? {}, + stdout: { write: (chunk: string) => (stdout += chunk), isTTY: options.tty }, + stderr: { + write: (chunk: string) => (stderr += chunk), + isTTY: options.tty, + columns: 80, + }, + } as unknown as CliContext + return { made, read: () => ({ stdout, stderr }) } +} + +describe('output without a terminal', () => { + test('writes plain lines, with no marks, header or done lines', () => { + const { made, read } = context({ tty: false }) + const output = createOutput(made, false) + output.header() + output.note('Reading.') + output.done('Read.') + output.did('Removed a file.') + output.warn('Careful.') + expect(read().stderr).toBe('Reading.\nRemoved a file.\nWarning: Careful.\n') + expect(output.decorated).toBe(false) + }) +}) + +describe('output in a terminal', () => { + test('marks each line, and says Warning in words as well', () => { + const { made, read } = context({ tty: true, env: { NO_COLOR: '1' } }) + const output = createOutput(made, false) + output.header() + output.header() + output.note('Reading.') + output.done('Read.') + output.warn('Careful.') + expect(read().stderr).toBe( + [ + `◆ druxt ${cliVersion()}`, + '◆ Reading.', + '✔ Read.', + '▲ Warning: Careful.', + '', + ].join('\n') + ) + }) + + test('uses ASCII marks where Unicode cannot be drawn', () => { + const { made, read } = context({ + tty: true, + env: { NO_COLOR: '1', TERM: 'linux' }, + }) + const output = createOutput(made, false) + output.note('Reading.') + output.done('Read.') + output.did('Removed a file.') + expect(read().stderr).toBe('* Reading.\n+ Read.\n+ Removed a file.\n') + }) + + test('is plain with --json, and the result is JSON alone', () => { + const { made, read } = context({ tty: true }) + const output = createOutput(made, true) + output.header() + output.note('Reading.') + output.done('Read.') + output.result({ ok: true }, 'text') + expect(read().stderr).toBe('Reading.\n') + expect(JSON.parse(read().stdout)).toEqual({ ok: true }) + expect(output.out.color).toBe('none') + }) + + test('colours stderr and stdout by what each is attached to', () => { + const { made } = context({ tty: true, env: { COLORTERM: 'truecolor' } }) + const output = createOutput(made, false) + expect(output.err.color).toBe('truecolor') + expect(output.out.color).toBe('truecolor') + }) +}) + +describe('the banner', () => { + test('is drawn on stderr in a terminal wide enough, once', () => { + const { made, read } = context({ tty: true, env: { NO_COLOR: '1' } }) + const output = createOutput(made, false) + expect(output.banner({})).toBe(true) + expect(read().stderr).toContain('██████╗') + expect(read().stdout).toBe('') + // The small header would say the same thing twice. + output.header() + expect(read().stderr).not.toContain('druxt ') + }) + + // The menu draws the wordmark, then runs a command, which makes an Output of its own. + test('keeps the small header off a stream that already has the wordmark', () => { + const { made, read } = context({ tty: true, env: { NO_COLOR: '1' } }) + expect(createOutput(made, false).banner({})).toBe(true) + createOutput(made, false).header() + expect(read().stderr).not.toContain(`druxt ${cliVersion()}`) + }) + + test('is not drawn when the flag or the configuration says no', () => { + const { made, read } = context({ tty: true }) + const output = createOutput(made, false) + expect(output.banner({ flag: false })).toBe(false) + expect(output.banner({ configured: false })).toBe(false) + expect(read().stderr).toBe('') + }) + + test('is not drawn without a terminal', () => { + const { made, read } = context({ tty: false }) + expect(createOutput(made, false).banner({})).toBe(false) + expect(read().stderr).toBe('') + }) +}) diff --git a/packages/cli/test/presentation.test.ts b/packages/cli/test/presentation.test.ts new file mode 100644 index 0000000..b1b4d0d --- /dev/null +++ b/packages/cli/test/presentation.test.ts @@ -0,0 +1,205 @@ +import { stripVTControlCharacters } from 'node:util' +import { describe, expect, test } from 'vitest' +import { + bannerAllowed, + createPresentation, + detectColor, + supportsUnicode, + WORDMARK, + WORDMARK_WIDTH, +} from '../src/presentation.js' + +const tty = { isTTY: true, json: false } + +describe('detectColor', () => { + test.each([ + [{ COLORTERM: 'truecolor' }, 'truecolor'], + [{ COLORTERM: '24bit' }, 'truecolor'], + [{ TERM: 'xterm-256color' }, '256'], + [{ TERM: 'xterm' }, '16'], + [{}, '16'], + ])('in a terminal with %j is %s', (env, level) => { + expect(detectColor({ env, ...tty })).toBe(level) + }) + + test.each([ + ['NO_COLOR', { NO_COLOR: '1', COLORTERM: 'truecolor' }], + ['a dumb terminal', { TERM: 'dumb' }], + ['CI', { CI: 'true', COLORTERM: 'truecolor' }], + ['FORCE_COLOR=0', { FORCE_COLOR: '0', COLORTERM: 'truecolor' }], + ])('is off under %s', (_name, env) => { + expect(detectColor({ env, ...tty })).toBe('none') + }) + + test('is off without a terminal, and with --json', () => { + const env = { COLORTERM: 'truecolor' } + expect(detectColor({ env, isTTY: false, json: false })).toBe('none') + expect(detectColor({ env, isTTY: true, json: true })).toBe('none') + }) + + test('NO_COLOR wins over FORCE_COLOR, and an empty NO_COLOR is not set', () => { + expect( + detectColor({ env: { NO_COLOR: '1', FORCE_COLOR: '3' }, ...tty }) + ).toBe('none') + expect(detectColor({ env: { NO_COLOR: '' }, ...tty })).toBe('16') + }) + + test.each([ + ['1', '16'], + ['2', '256'], + ['3', 'truecolor'], + ['true', '16'], + ])( + 'FORCE_COLOR=%s turns it on with no terminal and under CI, as %s', + (value, level) => { + expect( + detectColor({ + env: { FORCE_COLOR: value, CI: 'true' }, + isTTY: false, + json: false, + }) + ).toBe(level) + } + ) + + test('--json is plain even when colour is forced', () => { + expect( + detectColor({ env: { FORCE_COLOR: '3' }, isTTY: true, json: true }) + ).toBe('none') + }) +}) + +describe('supportsUnicode', () => { + test('is true for a usual terminal and false for the Linux console', () => { + expect(supportsUnicode({ TERM: 'xterm-256color' }, 'linux')).toBe(true) + expect(supportsUnicode({ TERM: 'linux' }, 'linux')).toBe(false) + }) + + test('on Windows needs a terminal known to draw it', () => { + expect(supportsUnicode({}, 'win32')).toBe(false) + expect(supportsUnicode({ WT_SESSION: '1' }, 'win32')).toBe(true) + expect(supportsUnicode({ TERM_PROGRAM: 'vscode' }, 'win32')).toBe(true) + }) +}) + +describe('the wordmark', () => { + test('is six lines, each as wide as the widest', () => { + const lines = WORDMARK.split('\n') + expect(lines).toHaveLength(6) + expect(new Set(lines.map((line) => line.length))).toEqual( + new Set([WORDMARK_WIDTH]) + ) + expect(WORDMARK_WIDTH).toBe(58) + }) + + test('with colour off is the art and nothing else', () => { + const plain = createPresentation({ color: 'none', unicode: true }) + expect(plain.wordmark()).toBe(WORDMARK) + }) + + test('with colour on is the same art under the codes', () => { + for (const color of ['16', '256', 'truecolor'] as const) { + const drawn = createPresentation({ color, unicode: true }).wordmark() + expect(drawn).not.toBe(WORDMARK) + expect(stripVTControlCharacters(drawn)).toBe(WORDMARK) + } + }) + + test('runs from the backend blue on the left to the frontend green on the right', () => { + const drawn = createPresentation({ color: 'truecolor', unicode: true }) + .wordmark() + .split('\n')[0] as string + expect(drawn.startsWith('\u001B[38;2;52;152;219m')).toBe(true) + expect(drawn).toContain('\u001B[38;2;65;184;131m') + expect(drawn.endsWith('\u001B[39m')).toBe(true) + }) + + test('in 16 colours is blue on the left half and green on the right', () => { + const line = createPresentation({ color: '16', unicode: true }) + .wordmark() + .split('\n')[0] as string + expect(line.startsWith('\u001B[34m')).toBe(true) + expect(line).toContain('\u001B[32m') + }) + + test('falls back to the name in a terminal that cannot draw the blocks', () => { + expect( + createPresentation({ color: 'none', unicode: false }).wordmark() + ).toBe('DRUXT.JS') + }) +}) + +describe('marks', () => { + test('are four different shapes, with or without Unicode', () => { + for (const unicode of [true, false]) { + const p = createPresentation({ color: 'none', unicode }) + const marks = (['done', 'working', 'warning', 'failed'] as const).map( + (kind) => p.mark(kind) + ) + expect(new Set(marks).size).toBe(4) + if (!unicode) expect(marks.join('')).toMatch(/^[\x20-\x7E]+$/) + } + }) + + test('are coloured when colour is on, and the shape stays', () => { + const plain = createPresentation({ color: 'none', unicode: true }) + const colour = createPresentation({ color: '16', unicode: true }) + expect(colour.mark('failed')).not.toBe(plain.mark('failed')) + expect(stripVTControlCharacters(colour.mark('failed'))).toBe( + plain.mark('failed') + ) + }) +}) + +describe('role colouring', () => { + test('makes a backend blue and a frontend green, in each depth', () => { + const p16 = createPresentation({ color: '16', unicode: true }) + expect(p16.role('backend', 'B')).toBe('\u001B[34mB\u001B[39m') + expect(p16.role('frontend', 'F')).toBe('\u001B[32mF\u001B[39m') + + const p256 = createPresentation({ color: '256', unicode: true }) + expect(stripVTControlCharacters(p256.role('backend', 'B'))).toBe('B') + expect(p256.role('backend', 'B').startsWith('\u001B[38;5;')).toBe(true) + + const full = createPresentation({ color: 'truecolor', unicode: true }) + expect(full.role('backend', 'B')).toBe('\u001B[38;2;52;152;219mB\u001B[39m') + expect(full.role('frontend', 'F')).toBe( + '\u001B[38;2;65;184;131mF\u001B[39m' + ) + }) + + test('leaves the text alone with colour off', () => { + const plain = createPresentation({ color: 'none', unicode: true }) + expect(plain.role('backend', 'B')).toBe('B') + expect(plain.bold('x')).toBe('x') + expect(plain.dim('x')).toBe('x') + }) +}) + +describe('bannerAllowed', () => { + const yes = { + env: {}, + isTTY: true, + columns: 80, + json: false, + flag: undefined, + configured: undefined, + } + + test('is true in a terminal wide enough', () => { + expect(bannerAllowed(yes)).toBe(true) + expect(bannerAllowed({ ...yes, columns: 58 })).toBe(true) + }) + + test.each([ + ['--json', { json: true }], + ['no terminal', { isTTY: false }], + ['CI', { env: { CI: '1' } }], + ['a narrow terminal', { columns: 57 }], + ['a terminal of unknown width', { columns: undefined }], + ['--no-banner', { flag: false }], + ['"banner": false in the user configuration', { configured: false }], + ])('is false with %s', (_name, change) => { + expect(bannerAllowed({ ...yes, ...change })).toBe(false) + }) +}) diff --git a/packages/cli/test/prompts.test.ts b/packages/cli/test/prompts.test.ts index 6fd4435..9def340 100644 --- a/packages/cli/test/prompts.test.ts +++ b/packages/cli/test/prompts.test.ts @@ -62,6 +62,36 @@ describe('terminalPrompter', () => { ).toBe('split') }) + test('search narrows the list by what is typed', async () => { + const { prompter, press } = terminal() + press(`men${ENTER}`) + expect( + await prompter.search({ + message: 'Which module?', + choices: [ + { value: 'blocks', label: 'blocks' }, + { value: 'menu', label: 'menu', hint: 'druxt-menu' }, + ], + }) + ).toBe('menu') + }) + + test('select shows a choice that cannot be taken, and skips it', async () => { + const { prompter, press, drawn } = terminal() + press(`${DOWN}${ENTER}`) + expect( + await prompter.select({ + message: 'Which layout?', + choices: [ + { value: 'monorepo', label: 'monorepo' }, + { value: 'split', label: 'split', hint: 'not yet', disabled: true }, + { value: 'other', label: 'other' }, + ], + }) + ).toBe('other') + expect(drawn()).toContain('split') + }) + test('confirm returns the initial answer on enter', async () => { const { prompter, press } = terminal() press(ENTER) diff --git a/packages/cli/test/registry/entry.test.ts b/packages/cli/test/registry/entry.test.ts index 94cc6e3..84e270d 100644 --- a/packages/cli/test/registry/entry.test.ts +++ b/packages/cli/test/registry/entry.test.ts @@ -146,6 +146,7 @@ describe('validateEntry', () => { ], ['druxt.default', 'yes', 'druxt.default must be true or false'], ['druxt.steps', 'npm run dev', 'druxt.steps must be an array of strings'], + ['druxt.description', 7, 'druxt.description must be a string'], ['druxt.install', 'npm install', 'druxt.install must be an object'], [ 'druxt.install', diff --git a/packages/cli/test/repeat.test.ts b/packages/cli/test/repeat.test.ts new file mode 100644 index 0000000..f730ef0 --- /dev/null +++ b/packages/cli/test/repeat.test.ts @@ -0,0 +1,52 @@ +import { execFileSync } from 'node:child_process' +import { describe, expect, test } from 'vitest' +import { repeatCommand, shellQuote } from '../src/repeat.js' + +describe('shellQuote', () => { + test.each([ + ['my-site', 'my-site'], + ['--engine', '--engine'], + ['https://example.com/a?b=1', "'https://example.com/a?b=1'"], + ['./sites/a_b.c', './sites/a_b.c'], + ['my site', "'my site'"], + ["it's", `'it'\\''s'`], + ['a "quoted" name', `'a "quoted" name'`], + ['$HOME', `'$HOME'`], + ['', "''"], + ['a;b', "'a;b'"], + ])('%j becomes %s', (value, quoted) => { + expect(shellQuote(value)).toBe(quoted) + }) +}) + +describe('repeatCommand', () => { + test('joins the arguments after drx', () => { + expect(repeatCommand(['module', 'info', 'blocks'])).toBe( + 'drx module info blocks' + ) + }) + + // The real check of the quoting: a shell has to hand back the arguments + // exactly as they went in. + test.skipIf(process.platform === 'win32')( + 'survives a shell, with a space and both kinds of quote in a directory', + () => { + const argv = [ + 'init', + `my "site" isn't here`, + '--engine', + 'none', + '--base-url', + 'https://example.com/?a=1&b=$c', + '--yes', + ] + const line = repeatCommand(argv) + const echoed = execFileSync( + 'sh', + ['-c', `drx() { printf '%s\\n' "$@"; }; ${line}`], + { encoding: 'utf8' } + ) + expect(echoed.trimEnd().split('\n')).toEqual(argv) + } + ) +}) diff --git a/packages/cli/test/user-config.test.ts b/packages/cli/test/user-config.test.ts index 2ae3999..416ff7f 100644 --- a/packages/cli/test/user-config.test.ts +++ b/packages/cli/test/user-config.test.ts @@ -105,6 +105,7 @@ describe('loadUserConfig', () => { '{"moduleRegistries":{"a":"ftp://x"}}', 'moduleRegistries.a must be an http or https URL', ], + ['{"banner":"no"}', 'banner must be true or false'], ['{"sources":[]}', 'sources must be an object'], ['{"sources":{"a":"npm"}}', 'sources.a must be an object'], [ @@ -132,6 +133,17 @@ describe('loadUserConfig', () => { }) }) +describe('the banner setting', () => { + test('is read when it is set, and absent otherwise', async () => { + const path = join(home, 'config.json') + write(path, { banner: false }) + expect((await loadUserConfig({ DRX_CONFIG: path })).banner).toBe(false) + expect( + (await loadUserConfig({ XDG_CONFIG_HOME: home })).banner + ).toBeUndefined() + }) +}) + describe('resolveRegistryUrl', () => { const config = { path: '/home/me/.config/drx/config.json', diff --git a/starters/index.json b/starters/index.json index 26e1176..4f061ef 100644 --- a/starters/index.json +++ b/starters/index.json @@ -1,4 +1,4 @@ { - "revision": 2, + "revision": 3, "starters": ["quickstart"] } diff --git a/starters/quickstart.json b/starters/quickstart.json index 813decf..d1e84ab 100644 --- a/starters/quickstart.json +++ b/starters/quickstart.json @@ -5,10 +5,19 @@ "url": "https://github.com/druxt/quickstart", "druxt": { "line": "0.x", + "description": "Drupal 11, Nuxt 2 and Druxt 1 in one repository", "layout": "monorepo", "parts": [ - { "role": "frontend", "kind": "nuxt", "path": "nuxt" }, - { "role": "backend", "kind": "drupal", "path": "drupal" } + { + "role": "frontend", + "kind": "nuxt", + "path": "nuxt" + }, + { + "role": "backend", + "kind": "drupal", + "path": "drupal" + } ], "requires": { "node": "16.18.1", @@ -25,12 +34,14 @@ "engines": [ { "name": "php", - "label": "PHP 8.3 or newer with the pdo_sqlite extension, and Composer", + "label": "Local PHP with SQLite", + "needs": "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." + "This engine does not run on Windows itself. Use WSL2 there, or another engine.", + "npm run dev starts the backend again when it is not running." ], "files": [] }, @@ -42,15 +53,28 @@ "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" }, + { + "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"] + "files": ["drupal/.ddev"], + "project": { + "name": "quickstart-druxtsite", + "files": ["drupal/.ddev/config.yaml"] + } }, { "name": "lando", @@ -60,22 +84,41 @@ "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" }, + { + "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"] + "files": ["drupal/.lando.yml", "drupal/.ddev/commands"], + "project": { + "name": "druxt-quickstart", + "files": ["drupal/.lando.yml"] + }, + "needs": "Docker, and a Lando that has the drupal11 recipe" } ], "install": { "runs": ["npm run setup"], + "done": { + "file": ".env", + "contains": ["BASE_URL=", "OAUTH_CLIENT_ID="] + } + }, + "existingBackend": { "notes": [ - "npm install ran the setup. If it said it could not, run npm run setup once what it named is in place.", - "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." + "Set OAUTH_CLIENT_ID in .env to the client ID of an OAuth consumer on that Drupal before npm run dev. The site does not start without one." ] } }