diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 9d12b9d..2e6df4d 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -78,7 +78,7 @@ Every colour comes from the theme in `ui.js`: `color()` for plain output, `style Each file in `lib/` starts with two comment lines: what the file is for, and which files use it. Update them only if your change makes them wrong, for example a new file that imports it. Explain how something works in a comment next to the code instead, where it is easier to keep right. -Modules receive their side effects (file system, prompts, process spawning) as parameters with real defaults, so tests can replace them with fakes. Tests live in `test/`, one file per module. +Modules receive their side effects (file system, prompts, process spawning) as parameters with real defaults, so tests can replace them with fakes. Tests live in `test/`, one file per module. `test/benchmark.test.js` is the exception: it checks the time budget of the "Bigger workspaces" milestone, a 200-project workspace searched two levels deep in under 500 ms, on real folders in a temporary directory. ## Workflow diff --git a/README.md b/README.md index 6fe079e..8c4276f 100644 --- a/README.md +++ b/README.md @@ -27,7 +27,7 @@ Dev Workspace CLI detects each project's package manager (npm, pnpm, Yarn or Bun ## Features -- **One menu for every project:** lists the projects in your workspace folder and the scripts defined in each `package.json`. +- **One menu for every project:** lists the projects in your workspace folder and the scripts defined in each `package.json`, including the packages of npm, Yarn and pnpm monorepos. - **The right package manager:** runs each project's scripts with npm, pnpm, Yarn or Bun, detected from the project itself. - **Fast to navigate:** type a few letters to find a project or script, recently used projects come first, and `dws web dev` runs a script in one command. Menus also work with the mouse, with buttons for every action. - **Stays out of the way:** scripts run in the project folder with full terminal output. Pressing Ctrl+C stops the script and brings you back to the menu. @@ -105,7 +105,7 @@ This installs two equivalent commands, `dev-workspace` and the shorter `dws`. Ru Escape goes back one screen: from a project to the project list, from the workspace list or path prompt to the project list, and from the project list it exits. While you are searching, it only clears the search. The help line under each menu shows what it does (`esc back` or `esc exit`). -Every menu opens with a small box that shows where you are: the name of the workspace folder, followed by the project you are in (`◆ dev › web-app`), the workspace folder, and in a project, its package manager on the right. The box also holds the buttons of the screen, on the right of the workspace line: **⚙ Workspace** and **✕ Exit** in the project list, **← Back** and **… Run with args** in a project. The buttons sit just above the list: press ↑ on the first entry to reach the first button, ↑ again for the next one, and ↓ to come back (Tab and Shift+Tab work too, and ← and → move between buttons). The focused button is shown in reverse, or between brackets without colours, and Enter presses it. Each script's command is shown next to its name, in a column of its own, and tags such as `last run` sit at the right edge. When a list is longer than the window, `▲ 3 more` and `▼ 12 more` show how many entries are hidden above and below. The layout fills a new cmd or Windows Terminal window (120 columns) and stays within that width on wider ones; in a smaller window, such as the 80 columns macOS and Linux terminals open at, it uses the window's width. Long workspace paths are shortened in the middle (`C:Users…projectsweb`), keeping the folders that tell them apart, and script commands are cut with `…` to fit, and emoji or CJK characters in folder names never break the layout. +Every menu opens with a small box that shows where you are: the name of the workspace (see [Workspaces](#workspaces)), followed by the project you are in (`◆ dev › web-app`), the workspace folder, and in a project, its package manager on the right. The box also holds the buttons of the screen, on the right of the workspace line: **⚙ Workspace** and **✕ Exit** in the project list, **← Back** and **… Run with args** in a project. The buttons sit just above the list: press ↑ on the first entry to reach the first button, ↑ again for the next one, and ↓ to come back (Tab and Shift+Tab work too, and ← and → move between buttons). The focused button is shown in reverse, or between brackets without colours, and Enter presses it. Each script's command is shown next to its name, in a column of its own, and tags such as `last run` sit at the right edge. When a list is longer than the window, `▲ 3 more` and `▼ 12 more` show how many entries are hidden above and below. The layout fills a new cmd or Windows Terminal window (120 columns) and stays within that width on wider ones; in a smaller window, such as the 80 columns macOS and Linux terminals open at, it uses the window's width. Long workspace paths are shortened in the middle (`C:Users…projectsweb`), keeping the folders that tell them apart, and script commands are cut with `…` to fit, and emoji or CJK characters in folder names never break the layout. The menus are drawn on the terminal's alternate screen, as `less` and `vim` do, so resizing the window redraws the whole screen cleanly and the menus never fill your scrollback. A script's output appears on the normal screen and stays there after you return to the menus. @@ -152,9 +152,13 @@ Then **↻ Run again** and **← Back to scripts** sit side by side. Run again i To pass arguments to a script, press → on it, or click its **… run with args** button, then type the arguments, for example `--port 4000`. The **… Run with args** button in the header box does the same after asking which script to run. Use quotes for an argument that contains spaces: `--title "my app"`. The arguments are passed to the script as they are, without a shell. Press Esc at the arguments prompt to go back to the scripts without running anything. +Some scripts are helpers that only work with the rest of a command after them, such as `"packages": "yarn workspaces foreach --all"`, which other scripts call as `yarn packages run test`. Run on their own, they fail. The CLI recognises the common forms from the command, and tags them `needs arguments`: `yarn workspaces foreach` and `yarn workspace ` with nothing after them, and `pnpm`, `bun` and `npm` with only options such as `-r`, `--filter` or `--workspaces`, `npm exec`, `npx`, `turbo run`, `lerna run` and `lerna exec`. Running one, with Enter, a click or **▶ run**, asks for the arguments first, shows the command they complete (`packages runs: yarn workspaces foreach --all `), and an empty answer is refused. + ### Projects -Every subfolder of the workspace is listed as a project, including links to folders (symbolic links, and junctions on Windows), except folders that are never projects: names starting with a dot (such as `.git` or `.vscode`) and `node_modules`. Only the immediate subfolders are listed; projects nested deeper are not discovered. +Every subfolder of the workspace is listed as a project, including links to folders (symbolic links, and junctions on Windows), except folders that are never projects: names starting with a dot (such as `.git` or `.vscode`) and `node_modules`. + +By default, only the immediate subfolders are listed. If your workspace groups projects in folders, such as `clients/acme/web`, let the CLI look deeper with `dws --set-depth 2` (or `3`, the maximum): it then also searches the folders that have no `package.json`, down to that many levels. The search stops at every folder with a `package.json`, so a project's own subfolders are never listed, and never enters `node_modules` or dot-folders. Projects found this way are named by their path (`clients/acme/web`); a folder that holds no project at all stays one dimmed entry. `dws --set-depth 1` goes back to the default. Projects are sorted by name, ignoring case. Folders without a `package.json` have no scripts to run, so they appear dimmed at the end of the list, tagged `no package.json`, and cannot be selected. A `package.json` that starts with a UTF-8 byte order mark, as Windows PowerShell 5.1 and some editors write it, is read normally, as npm does. @@ -162,6 +166,21 @@ Next to each project, the list shows how many scripts it has and its Git branch In the script list, each script's command is shown next to its name, shortened to fit the terminal. Lifecycle hooks are listed with their main script instead of separately: with `prebuild`, `build` and `postbuild` scripts, the list shows only `build`, with the command `node build.js (+ prebuild, postbuild)`; when the command is shortened, the hooks are always kept. Running `build` runs its hooks too, as the package manager normally does. A hook without its main script, such as `postinstall` on its own, is listed like any other script. In Yarn 2+ projects, which never run these hooks, every hook is listed as a separate script so you can still run it. +#### Monorepos + +A project that declares workspaces is shown as a monorepo: the `workspaces` field of its `package.json` (npm, Yarn and Bun) or a `pnpm-workspace.yaml` (pnpm). It has a `▸` before its name and its package count in its details (`3 packages · 2 scripts · main`). Opening it (Enter, a click, or →) shows what it holds under it: **root** first, which opens the scripts of the monorepo's own `package.json`, then its packages. Opening it again, or ← from any of its entries, hides them. A monorepo found by a search opens the same way, and the search is cleared. In **Recent**, a monorepo expands too. + +```text + ❯ ▾ shop 3 packages · 2 scripts · main pnpm + ├ root 2 scripts + ├ web 1 script · feat/landing + ├ api 2 scripts @shop/api + └ ui 1 script @shop/ui + web 2 scripts · main npm +``` + +The tree lines show which entries belong to the monorepo. Each package is listed by its folder name (`api` for `packages/api`), or by its whole path when two packages share a folder name (`apps/web` and `packages/web`), with its `name` from `package.json` on the right when it differs from the folder name. A package that is a Git repository of its own (it has its own `.git`, such as a submodule) shows its branch too. Opening a package shows its scripts, and they run in the package's folder with the monorepo's package manager, so `pnpm run dev` starts in `shop/packages/api`. The packages are the folders the workspace patterns match (`packages/*`, `apps/**`, and patterns starting with `!` to leave folders out) that have a `package.json`; a `**` is followed down to five folders, whatever the search depth (see [Projects](#projects)), which only applies to the workspace folder. They are read once per session. Searching looks through every package, shown or not: typing `ui` finds `shop › ui`. Packages appear in the recent projects too, under their full name (`shop/packages/api`). + ## Package managers Each project's scripts run with the package manager that project uses. It is chosen in this order: @@ -194,8 +213,8 @@ dws web dev # run its "dev" script, then exit dws web dev -- --port 4000 # pass everything after -- to the script ``` -- The project is found by its exact name first, then ignoring case, then by the start of its name, as long as only one project starts that way: `dws des build` runs `build` in `design-system`. If several projects match, the CLI lists them. -- Any script in `package.json` can be run by name, including `pre` and `post` hooks. +- The project is found by its exact name first, then ignoring case, then by the last part of a nested project's name (`dws web` finds `clients/acme/web`, see [Projects](#projects)), then by the start of its name, as long as only one project starts that way: `dws des build` runs `build` in `design-system`. If several projects match, the CLI lists them. Nested names can be typed with `/`, or `` on Windows. A monorepo's packages are found the same way, by their full name or its last part: `dws shop/packages/api test`, or `dws api test` when no other project or package is called `api`. +- Any script in `package.json` can be run by name, including `pre` and `post` hooks. A script tagged `needs arguments` in the menu (see [Running scripts](#running-scripts)) is not started without arguments after `--`: the CLI exits with code 1 and says how to add them. - With a script, nothing is asked and the screen is not cleared, so direct mode also works in other scripts. The CLI exits with the script's exit code, or 128 plus the signal number if a signal stopped it, as shells do (130 after Ctrl+C). It exits with code 1 if it cannot start the script, for example when no workspace is saved yet. - Without a script, the CLI needs a terminal to read keys from. When its input is redirected (`dws < file`, or in a CI job), it exits with code 1 and a message saying how to run a script directly, instead of waiting for keys that never come. @@ -205,20 +224,23 @@ dws web dev -- --port 4000 # pass everything after -- to the script dev-workspace [options] [project [script] [-- arguments]] ``` -| Option | Description | -| ------------------------ | ------------------------------------------------------------ | -| `-w, --workspace ` | Use `` as the workspace and save it | -| `--no-mouse` | Use only the keyboard in menus, for this run | -| `--set-mouse ` | Save whether menus use the mouse | -| `--set-color ` | Save the accent colour (see [Colours](#colours)) | -| `--config-path` | Print the location of the configuration file | -| `--clear-history` | Forget the recent projects and last scripts | -| `--add-alias ` | Create another command that starts the CLI | -| `--remove-alias ` | Delete an alias created with `--add-alias` | -| `--list-aliases` | List the commands that start the CLI | -| `--reset` | Delete the configuration, history and custom aliases | -| `-v, --version` | Print the version | -| `-h, --help` | Show the help (coloured as described in [Colours](#colours)) | +| Option | Description | +| ------------------------------ | ----------------------------------------------------------------------------- | +| `-w, --workspace ` | Use a saved workspace, or `` (saved too, see [Workspaces](#workspaces)) | +| `--list-workspaces` | List the saved workspaces | +| `--remove-workspace ` | Forget a saved workspace (its folder is left as it is) | +| `--no-mouse` | Use only the keyboard in menus, for this run | +| `--set-mouse ` | Save whether menus use the mouse | +| `--set-color ` | Save the accent colour (see [Colours](#colours)) | +| `--set-depth <1-3>` | Save how many folder levels to search (see [Projects](#projects)) | +| `--config-path` | Print the location of the configuration file | +| `--clear-history` | Forget the recent projects and last scripts | +| `--add-alias ` | Create another command that starts the CLI | +| `--remove-alias ` | Delete an alias created with `--add-alias` | +| `--list-aliases` | List the commands that start the CLI | +| `--reset` | Delete the configuration, history and custom aliases | +| `-v, --version` | Print the version | +| `-h, --help` | Show the help (coloured as described in [Colours](#colours)) | ## Aliases @@ -251,12 +273,24 @@ The workspace path is saved in the standard configuration folder of your operati - The `DEV_WORKSPACE_CONFIG` environment variable points the CLI at a different file. - If you edit the file by hand, an editor that saves it with a UTF-8 byte order mark does no harm. - The accent colour chosen on the first launch is saved as `"color"`: `{ "workspace": "…", "color": "teal" }`. `dws --set-color ` changes it. A file saved by a version without this setting keeps cyan and is never asked again. +- `dws --set-depth 2` saves `"depth": 2`, the number of folder levels searched for projects (1 to 3, 1 when it is missing). - `dws --set-mouse off` saves `"mouse": false` in the file, so menus use only the keyboard: `{ "workspace": "…", "mouse": false }`. `dws --set-mouse on` saves `true`. Changing the workspace keeps these settings, and they can be saved before any workspace is chosen. -- To switch workspaces, press the **⚙ Workspace** button in the project list or run `dws --workspace `. The button shows the same folders as the first launch, with the current one tagged `current`, and **… Enter another path**. In that list, and at the path prompt, Esc keeps the current workspace and goes back to the projects. If the saved workspace no longer exists, the CLI asks for a new one. +- Saved workspaces are kept as `"workspaces"`, by name, and `"workspace"` holds the path of the current one: `{ "workspace": "…/work", "workspaces": { "dev": "…/dev", "work": "…/work" } }`. A file saved by a version without names keeps working: its workspace is listed under its folder name. See [Workspaces](#workspaces). - Versions before 0.3.0 stored the file in `~/.dev-workspace-cli/config.json`. If that file exists, it is moved to the new location automatically. The history of recent projects and last scripts, and which mouse notes were shown, is kept apart from the settings, in `state.json` in the same folder as `config.json`. With `DEV_WORKSPACE_CONFIG`, it is named after your file instead (`dws.json` keeps it in `dws.state.json`), so it never overwrites a `state.json` of your own. It is only a convenience: if it is missing or damaged, the CLI starts with an empty history. `dws --clear-history` deletes it. +### Workspaces + +You can keep several workspaces, for example `work` and `personal`, and switch between them. Every workspace you use is saved under a name: the first one, and any folder passed with `--workspace `, under its folder name (`dev`, or `dev-2` when that name is taken). + +- Press the **⚙ Workspace** button in the project list to switch. It lists the saved workspaces by name, with the current one tagged `current` and those whose folder is gone dimmed as `not found`, then the suggested folders of the first launch that are not saved yet, and **… Enter another path**. Choosing a saved workspace switches to it at once; for a new folder, the CLI asks for a name, filled in with the folder name, so Enter keeps it. Names cannot contain `/` or `\`, or start with `.` or `~`, so they never read as a path. +- `dws --workspace work` switches to the saved workspace `work` (the name is matched exactly, then ignoring case), also in direct mode: `dws -w work web dev`. Anything that is not a saved name is read as a path. To use a folder that has the same name as a saved workspace, give it as a path, such as `./work`. +- `dws --list-workspaces` prints the saved workspaces and marks the current one; `dws --remove-workspace ` forgets one, but never the current one, and leaves its folder as it is. +- In the workspace list, the name prompt and the path prompt, Esc keeps the current workspace and goes back to the projects. If the current workspace no longer exists, the CLI asks for another one, and the list offers the other saved workspaces. + +The header box starts with the workspace's name (`◆ work › web-app`). + ## Uninstalling The configuration, history and custom aliases are kept outside the package, so they remain after an uninstall. To remove everything: diff --git a/ROADMAP.md b/ROADMAP.md index 133f7d8..fc9eb7c 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -26,7 +26,7 @@ These apply to every milestone: | Fast navigation | Released in 0.6.0 | Fuzzy search, recent items, direct mode, script arguments | | A polished interface | Released in 0.9.0 | Mouse support, framed header, buttons, themes, project details, first run | | Terminal compatibility | Planned | Mouse and screens checked in macOS Terminal, iTerm2 and Linux terminals | -| Bigger workspaces | Planned | Monorepos, nested projects, multiple named workspaces | +| Bigger workspaces | Released in 0.11.0 | Monorepos, nested projects, multiple named workspaces | | Configuration and scripts | Planned | Versioned config schema, `config` command, JSON output, project commands | | Hardening and release candidate | Planned | Linting, type checks, end-to-end tests, interface freeze, feedback period | | Stable | Planned: 1.0.0 | Semver guarantees for flags, config and exit codes | @@ -179,14 +179,16 @@ Every screen checked in the terminals people use, on their own schedule: they ne **Done when:** screenshots of the main screens look correct in Windows Terminal, PowerShell, macOS Terminal, iTerm2 and a Linux terminal, at 80 and 120 columns, with and without `NO_COLOR`, and resizing the window while a menu is open never leaves broken lines or duplicate headers in any of them. -## Bigger workspaces +## Bigger workspaces _(released in 0.11.0)_ -- [ ] **Monorepos:** detect npm, Yarn and pnpm workspaces. A monorepo appears as one project with expandable packages; scripts run in the selected package. -- [ ] **Nested discovery:** optional search depth (default 1, maximum 3) for workspaces organised in folders such as `clients/acme/web`. It must stop at any folder with a `package.json` and never enter `node_modules`. -- [ ] **Multiple named workspaces:** save several workspaces (for example `work` and `personal`), switch between them from the menu, and choose one with `--workspace `. +- [x] **Monorepos:** detect npm, Yarn and pnpm workspaces. A monorepo appears as one project with expandable packages; scripts run in the selected package. Opening it shows a **root** entry for its own scripts and its packages, search looks through all of them, and each package runs with its monorepo's package manager [#36](https://github.com/modulane/dev-workspace-cli/issues/36). +- [x] **Nested discovery:** optional search depth (default 1, maximum 3) for workspaces organised in folders such as `clients/acme/web`, saved with `--set-depth`. It must stop at any folder with a `package.json` and never enter `node_modules`. Projects found deeper are named by their path, and direct mode also finds them by their last part (`dws web`) [#37](https://github.com/modulane/dev-workspace-cli/issues/37). +- [x] **Multiple named workspaces:** save several workspaces (for example `work` and `personal`), switch between them from the menu, and choose one with `--workspace `. Each workspace is saved under a name (its folder name, or one typed when it is added from the menu), and `--list-workspaces` and `--remove-workspace` manage them [#38](https://github.com/modulane/dev-workspace-cli/issues/38). **Done when:** a 200-project workspace with depth 2 lists in under 500 ms on a typical SSD, measured in a benchmark test. +Met: `test/benchmark.test.js` lists 20 folders of 10 projects each, two levels deep, and fails above 500 ms. It runs with the other tests in CI on every operating system. + ## Configuration and scripts - [ ] **Versioned config schema:** add a `"version"` field and migrate older files automatically, with a backup (`config.json.bak`) before any migration. diff --git a/lib/args.js b/lib/args.js index cb0afa0..2516773 100644 --- a/lib/args.js +++ b/lib/args.js @@ -1,5 +1,5 @@ // Reading the command-line options, and the `--help` text. -// Used by cli.js and prompts.js. +// Used by cli.js, prompts.js and script-arguments.js. import { parseArgs } from 'node:util' @@ -24,13 +24,20 @@ export function formatHelp(color = value => String(value)) { ${color('dws web dev -- --port 4000', 'accent')} ${color('Options:', 'bold')} - ${color('-w, --workspace', 'accent')} ${color('', 'dim')} Use as the workspace and save it + ${color('-w, --workspace', 'accent')} ${color('', 'dim')} + Use a saved workspace, or (saved too) + ${color('--list-workspaces', 'accent')} List the saved workspaces + ${color('--remove-workspace', 'accent')} ${color('', 'dim')} + Forget a saved workspace ${color('--no-mouse', 'accent')} Use only the keyboard in menus, this time ${color('--set-mouse', 'accent')} ${color('', 'dim')} Save whether menus use the mouse ${color('--set-color', 'accent')} ${color('', 'dim')} Save the accent colour: cyan, blue, purple, magenta, pink, orange, teal, sky, lavender, coral, gold, bold + ${color('--set-depth', 'accent')} ${color('<1-3>', 'dim')} Save how many folder levels to search for + projects (1, the default, lists only the + workspace's own subfolders) ${color('--config-path', 'accent')} Print the configuration file location ${color('--clear-history', 'accent')} Forget recently used projects and scripts ${color('--add-alias', 'accent')} ${color('', 'dim')} Create another command that starts the CLI @@ -64,9 +71,12 @@ export function parseCliArgs(args) { args: own, options: { workspace: { type: 'string', short: 'w' }, + 'list-workspaces': { type: 'boolean' }, + 'remove-workspace': { type: 'string' }, 'no-mouse': { type: 'boolean' }, 'set-mouse': { type: 'string' }, 'set-color': { type: 'string' }, + 'set-depth': { type: 'string' }, 'config-path': { type: 'boolean' }, 'clear-history': { type: 'boolean' }, 'add-alias': { type: 'string' }, @@ -112,6 +122,15 @@ export function parseCliArgs(args) { ) } + if ( + values['set-depth'] !== undefined && + !['1', '2', '3'].includes(values['set-depth']) + ) { + throw new Error( + `Use --set-depth with 1, 2 or 3, not "${values['set-depth']}".${SEE_HELP}`, + ) + } + if (separator !== -1 && script === undefined) { throw new Error( `Arguments after -- need a project and a script, for example: dws web dev -- --port 4000${SEE_HELP}`, diff --git a/lib/cli.js b/lib/cli.js index 0ad8605..ae43621 100644 --- a/lib/cli.js +++ b/lib/cli.js @@ -18,11 +18,15 @@ import { getConfigPaths, migrateLegacyConfig, readColorSetting, + readDepthSetting, readMouseSetting, + readSavedWorkspaces, readWorkspaceConfig, resetWorkspaceConfig, saveColorSetting, + saveDepthSetting, saveMouseSetting, + saveSavedWorkspaces, saveWorkspaceConfig, } from './config.js' @@ -46,6 +50,8 @@ import { } from './terminal.js' import { + MAX_DEPTH, + getPackages, getProjects, getScripts, isDirectory, @@ -64,6 +70,7 @@ import { RUN_WITH_ARGUMENTS, askForArguments, askForWorkspace, + askForWorkspaceName, chooseAccent, chooseProject, chooseScript, @@ -77,7 +84,7 @@ import { import { drawLines } from './list.js' import { screen } from './screen.js' -import { ACCENTS, color, headerLines, setAccent } from './ui.js' +import { ACCENTS, color, folderName, headerLines, setAccent } from './ui.js' const { version } = createRequire(import.meta.url)('../package.json') @@ -88,11 +95,11 @@ function describePackageManager({ name, source }) { return `${name} · ${source}` } -// A project's script count in the list: "12 scripts". -function describeScripts(count) { - if (count === 0) return 'no scripts' +// A count in the list: "12 scripts", "1 package", "no scripts". +function describeCount(count, noun) { + if (count === 0) return `no ${noun}s` - return `${count} script${count === 1 ? '' : 's'}` + return `${count} ${noun}${count === 1 ? '' : 's'}` } // The branches a project usually starts on, coloured apart from the others. @@ -157,22 +164,83 @@ function exitCodeOf({ code, signal }) { return code ?? 1 } -// Find a project by exact name, then ignoring case, then by a prefix that -// matches only one project. -export function findProject(projects, name, root) { +// Whether two paths name the same folder: Windows paths ignore case. +function samePath(a, b, platform = process.platform) { + const normalize = value => + platform === 'win32' + ? path.resolve(value).toLowerCase() + : path.resolve(value) + + return normalize(a) === normalize(b) +} + +// The name a workspace is saved under, or undefined. +function nameOf(saved, directory) { + return Object.keys(saved).find(name => samePath(saved[name], directory)) +} + +// The saved name matching `typed` exactly, else ignoring case. +function findName(saved, typed) { + const names = Object.keys(saved) + + return ( + names.find(name => name === typed) ?? + names.find(name => name.toLowerCase() === typed.toLowerCase()) + ) +} + +// `base`, or `base-2`, `base-3`… when another workspace has the name. +function uniqueName(base, saved) { + let name = base + + for (let number = 2; findName(saved, name) !== undefined; number++) { + name = `${base}-${number}` + } + + return name +} + +// Why a typed workspace name cannot be used, or true. A name must never +// read as a path, as --workspace accepts both. +export function checkWorkspaceName(typed, saved) { + const name = typed.trim() + const taken = findName(saved, name) + + if (!name) return 'Please enter a name.' + if (/[\\/]/.test(name) || /^[.~]/.test(name)) { + return 'A name cannot contain / or \\, or start with . or ~.' + } + if (taken !== undefined) return `"${taken}" already names ${saved[taken]}.` + + return true +} + +// Find a project by exact name, then ignoring case, then by the last part +// of a nested project's name (`web` for `clients/acme/web`), then by a +// prefix that matches only one project. A \ typed on Windows reads as /. +// A package that matches along with its monorepo is left out, so `sho` +// still finds `shop` and not also `shop/packages/api`. +export function findProject(projects, typed, root) { + const name = typed.replaceAll('\\', '/') const lower = name.toLowerCase() const rules = [ project => project.name === name, project => project.name.toLowerCase() === lower, + project => project.name.toLowerCase().split('/').at(-1) === lower, project => project.name.toLowerCase().startsWith(lower), ] for (const rule of rules) { - const matches = projects.filter(rule) + const found = projects.filter(rule) + const matches = found.filter( + project => + !project.monorepo || + !found.some(other => other.directory === project.monorepo.directory), + ) if (matches.length === 1) return matches[0] - if (matches.length > 1 && rule === rules[2]) { + if (matches.length > 1 && rule !== rules[0] && rule !== rules[1]) { const names = matches.map(project => project.name).join(', ') throw new Error( @@ -195,11 +263,15 @@ const defaultDependencies = { getConfigPaths, migrateLegacyConfig, readColorSetting, + readDepthSetting, readMouseSetting, + readSavedWorkspaces, readWorkspaceConfig, resetWorkspaceConfig, saveColorSetting, + saveDepthSetting, saveMouseSetting, + saveSavedWorkspaces, saveWorkspaceConfig, }, history: { @@ -213,6 +285,7 @@ const defaultDependencies = { isTerminal, }, workspace: { + getPackages, getProjects, detectPackageManager, getScripts, @@ -227,6 +300,7 @@ const defaultDependencies = { prompts: { askForArguments, askForWorkspace, + askForWorkspaceName, chooseAccent, chooseProject, chooseScript, @@ -283,15 +357,24 @@ export function createCli(overrides = {}) { const stateFile = getStatePath(configFile, { custom: configPaths.custom }) let root = '' + // The current workspace's saved name, shown in the header. + let workspaceName = null + // How many folder levels the project list searches, read once per run. + let depth = 1 let history = emptyState() - // Project details by directory, as promises, for this session. + // Project details and monorepo packages by directory, as promises, for + // this session. const details = new Map() + const packageLists = new Map() // The header box for a menu, drawn by the list at its current width, with // the list's toolbar. function header(crumbs = [], tag) { return (width, buttons = {}) => - ui.headerLines({ workspace: root, crumbs, tag, ...buttons }, width) + ui.headerLines( + { workspace: root, name: workspaceName, crumbs, tag, ...buttons }, + width, + ) } // Update the history and save it. History is a convenience, so a failed @@ -347,22 +430,71 @@ export function createCli(overrides = {}) { return true } - async function saveWorkspace(value) { - root = (await findWorkspace(value)).directory + // The saved workspaces, { name: path }. The current workspace of a file + // saved before workspaces had names is included under its folder name. + async function savedWorkspaces() { + const saved = await config.readSavedWorkspaces(configFile) + const current = + root || (await config.readWorkspaceConfig(configFile).catch(() => null)) + + if (current && nameOf(saved, current) === undefined) { + saved[uniqueName(folderName(current), saved)] = current + } + + return saved + } + + // Make a folder the current workspace, saved under its saved name, the + // `name` given, or its folder name. + async function saveWorkspace(value, { name } = {}) { + const saved = await savedWorkspaces() + const directory = (await findWorkspace(value)).directory + const known = nameOf(saved, directory) + + workspaceName = known ?? name ?? uniqueName(folderName(directory), saved) + saved[workspaceName] = directory + root = directory await config.saveWorkspaceConfig(root, configFile) + await config.saveSavedWorkspaces(saved, configFile) + + const named = + workspaceName === folderName(root) ? '' : ` as "${workspaceName}"` output.log() - output.log(ui.color(` Workspace saved: ${root}`, 'green')) + output.log(ui.color(` Workspace saved: ${root}${named}`, 'green')) output.log() return root } + // Switch to a folder from the workspace list or the path prompt. From the + // project list (`cancellable`), a folder not saved yet is named first, and + // Escape there keeps the current workspace. + async function addWorkspace(value, { cancellable }) { + const saved = await savedWorkspaces() + const { directory } = await findWorkspace(value) + + if (!cancellable || nameOf(saved, directory) !== undefined) { + return saveWorkspace(directory) + } + + output.log(ui.color(` Press Esc to keep ${root}.`, 'dim')) + + const name = await prompts.askForWorkspaceName( + uniqueName(folderName(directory), saved), + typed => checkWorkspaceName(typed, saved), + ) + + if (name === null) return root + + return saveWorkspace(directory, { name }) + } + // A suggested workspace folder's detail: "8 projects", counting the // folders with a package.json. async function folderDetails(folder) { - const count = (await workspace.getProjects(folder)).filter( + const count = (await workspace.getProjects(folder, { depth })).filter( project => project.hasPackageJson, ).length @@ -375,10 +507,21 @@ export function createCli(overrides = {}) { // workspace folders that exist are offered first, then a typed path. From // the project list (`cancellable`), Escape keeps the current workspace. async function configureWorkspace({ cancellable = false } = {}) { - const folders = await workspace.suggestWorkspaces() + const saved = await savedWorkspaces() + const known = await Promise.all( + Object.entries(saved).map(async ([name, directory]) => ({ + name, + directory, + missing: !(await workspace.isDirectory(directory)), + })), + ) + const folders = (await workspace.suggestWorkspaces()).filter( + folder => nameOf(saved, folder) === undefined, + ) - if (folders.length > 0) { + if (known.length + folders.length > 0) { const choice = await prompts.chooseWorkspace(folders, { + saved: known, cancellable, details: folderDetails, ...(cancellable @@ -396,7 +539,7 @@ export function createCli(overrides = {}) { ui.leaveScreen() if (choice === null) return root - if (choice !== ENTER_PATH) return saveWorkspace(choice) + if (choice !== ENTER_PATH) return addWorkspace(choice, { cancellable }) } output.log() @@ -415,10 +558,25 @@ export function createCli(overrides = {}) { if (directory === null) return root - return saveWorkspace(directory) + return addWorkspace(directory, { cancellable }) } + // --workspace: a saved workspace's name, or else a path, saved under its + // folder name. async function useWorkspaceOption(directory) { + const saved = await savedWorkspaces() + const name = findName(saved, directory) + + if (name !== undefined) { + if (!(await workspace.isDirectory(saved[name]))) { + throw new Error( + `The workspace "${name}" is unavailable: ${saved[name]}. Remove it with --remove-workspace ${name}.`, + ) + } + + return saveWorkspace(saved[name]) + } + const result = await validateWorkspace(directory) if (result !== true) { @@ -468,6 +626,7 @@ export function createCli(overrides = {}) { if (savedPath && (await workspace.isDirectory(path.resolve(savedPath)))) { root = path.resolve(savedPath) + workspaceName = nameOf(await savedWorkspaces(), root) ?? null return root } @@ -521,10 +680,16 @@ export function createCli(overrides = {}) { // The list's details for a project: its script count (as its script menu // counts them) and Git branch, with its package manager as the tag. - async function readDetails({ directory }) { + // A monorepo's details start with its package count; a package shows its + // package name as the tag when it differs from its folder name, and a + // branch only when it is a Git repository of its own (its folder has a + // .git). A monorepo's `root` entry (`root: true`) shows only the script + // count of its own package.json. + async function readDetails(project, root) { + const { directory, monorepo } = project const [packageManager, branch] = await Promise.all([ - workspace.detectPackageManager(directory), - workspace.readGitBranch(directory), + workspace.detectPackageManager(toolDirectory(project)), + root ? null : workspace.readGitBranch(directory), ]) let detail @@ -533,25 +698,90 @@ export function createCli(overrides = {}) { groupHooks: packageManager.runsHooks, }) - detail = describeScripts(scripts.length) + detail = describeCount(scripts.length, 'script') } catch { detail = 'invalid package.json' } - return { detail, ...branchSegments(branch), hint: packageManager.name } + if (root) return { detail } + + if (project.workspaces) { + const count = (await packagesOf(project)).length + + detail = `${describeCount(count, 'package')} · ${detail}` + } + + return { + detail, + ...branchSegments(branch), + hint: monorepo ? packageTag(project) : packageManager.name, + } + } + + function packageTag({ path: folder, packageName }) { + return packageName === folder.split('/').at(-1) ? undefined : packageName } - function projectDetails(project) { - if (!details.has(project.directory)) { - details.set(project.directory, readDetails(project)) + // Where the package manager is detected: a package uses its monorepo's. + function toolDirectory(project) { + return project.monorepo?.directory ?? project.directory + } + + // A monorepo's packages, read once per session, as projects named after + // the monorepo and their path in it (`shop/packages/api`), with + // `monorepo` pointing back to it. A monorepo whose packages cannot be + // read simply has none. + function packagesOf(monorepo) { + if (!packageLists.has(monorepo.directory)) { + packageLists.set( + monorepo.directory, + workspace.getPackages(monorepo.directory, monorepo.workspaces).then( + found => + found.map(({ path: folder, directory, packageName }) => ({ + name: `${monorepo.name}/${folder}`, + path: folder, + directory, + hasPackageJson: true, + monorepo, + ...(packageName && { packageName }), + })), + () => [], + ), + ) } - return details.get(project.directory) + return packageLists.get(monorepo.directory) + } + + // The packages of every monorepo among `projects`, by monorepo directory. + async function readPackages(projects) { + const monorepos = projects.filter(project => project.workspaces) + const lists = await Promise.all(monorepos.map(packagesOf)) + + return new Map( + monorepos.map((monorepo, index) => [monorepo.directory, lists[index]]), + ) + } + + // The projects and every monorepo's packages, for finding one by name. + async function readAllProjects() { + const projects = await readProjects() + const packages = await readPackages(projects) + + return [...projects, ...[...packages.values()].flat()] + } + + function projectDetails(project, { root = false } = {}) { + const key = root ? `root:${project.directory}` : project.directory + + if (!details.has(key)) details.set(key, readDetails(project, root)) + + return details.get(key) } async function readProjects() { try { - return await workspace.getProjects(root) + return await workspace.getProjects(root, { depth }) } catch (error) { throw new Error(`Could not read workspace: ${error.message}`, { cause: error, @@ -571,6 +801,7 @@ export function createCli(overrides = {}) { for (const line of ui.drawHeader({ workspace: root, + name: workspaceName, crumbs: [project.name, script.name], tag: describePackageManager(packageManager), })) { @@ -644,21 +875,43 @@ export function createCli(overrides = {}) { if (!withArguments) return { script, args: [] } + // A script that needs arguments shows what they complete. + if (script.needsArguments) { + output.log( + ui.color( + ` ${script.name} runs: ${script.command} `, + 'dim', + ), + ) + } + output.log(ui.color(' Press Esc to go back to the scripts.', 'dim')) - const args = await prompts.askForArguments(script.name) + const args = await prompts.askForArguments(script.name, { + required: Boolean(script.needsArguments), + }) if (args !== null) return { script, args } } } async function projectMenu(project) { + // Read again for the list once back: the project, and when it is a + // monorepo or one of its packages, the monorepo's packages and count. + const monorepo = project.monorepo ?? (project.workspaces && project) + details.delete(project.directory) + details.delete(`root:${project.directory}`) + + if (monorepo) { + packageLists.delete(monorepo.directory) + details.delete(monorepo.directory) + } // Detected first: hooks are grouped under their main script only when the // package manager runs them. const packageManager = await workspace.detectPackageManager( - project.directory, + toolDirectory(project), ) let scripts @@ -718,9 +971,9 @@ export function createCli(overrides = {}) { script: scriptName, scriptArgs, }) { - const project = findProject(await readProjects(), name, root) + const project = findProject(await readAllProjects(), name, root) const packageManager = await workspace.detectPackageManager( - project.directory, + toolDirectory(project), ) let scripts @@ -745,6 +998,14 @@ export function createCli(overrides = {}) { ) } + const script = scripts.find(found => found.name === scriptName) + + if (script.needsArguments && !scriptArgs?.length) { + throw new Error( + `"${scriptName}" cannot run without arguments (it runs: ${script.command}). Add them after --, for example: dws ${project.name} ${scriptName} -- `, + ) + } + const options = runOptions(packageManager, scriptArgs ?? []) output.error( @@ -783,6 +1044,7 @@ export function createCli(overrides = {}) { } history = await historyStore.readState(stateFile) + depth = await config.readDepthSetting(configFile, MAX_DEPTH) if (direct) { if (options.workspace === undefined) { @@ -811,18 +1073,25 @@ export function createCli(overrides = {}) { let opening = options.project === undefined ? null - : findProject(await readProjects(), options.project, root) + : findProject(await readAllProjects(), options.project, root) + // The last project or package opened, selected again in the list. + let lastOpened = null while (true) { if (opening) { + lastOpened = opening.directory await projectMenu(opening) opening = null } const projects = await readProjects() + const packages = await readPackages(projects) + const everything = [...projects, ...[...packages.values()].flat()] const choice = await prompts.chooseProject(projects, { - recent: recentProjects(history, projects), + recent: recentProjects(history, everything), details: projectDetails, + packages: project => packages.get(project.directory), + default: everything.find(project => project.directory === lastOpened), header: header(), body: projects.length === 0 @@ -913,6 +1182,71 @@ export function createCli(overrides = {}) { output.log(` The accent colour is now ${ui.color(name, 'accent')}.`) } + async function setDepth(value) { + const levels = Number(value) + + await config.saveDepthSetting(levels, configFile) + + output.log( + ui.color( + levels === 1 + ? ' The project list shows the workspace folders only.' + : ` The project list searches ${levels} folder levels for projects.`, + 'green', + ), + ) + } + + async function printWorkspaces() { + const current = await config + .readWorkspaceConfig(configFile) + .catch(() => null) + const saved = await savedWorkspaces() + const names = Object.keys(saved) + + if (names.length === 0) { + output.log(' No saved workspaces yet. Run dev-workspace to choose one.') + return + } + + const width = Math.max(...names.map(name => name.length)) + + for (const name of names) { + const mark = current && samePath(saved[name], current) ? ' (current)' : '' + + output.log(` ${name.padEnd(width)} ${saved[name]}${mark}`) + } + } + + async function removeWorkspace(typed) { + const saved = await savedWorkspaces() + const name = findName(saved, typed) + const current = await config + .readWorkspaceConfig(configFile) + .catch(() => null) + + if (name === undefined) { + throw new Error( + `No saved workspace named "${typed}". See them with --list-workspaces.`, + ) + } + + if (current && samePath(saved[name], current)) { + throw new Error( + `"${name}" is the current workspace. Switch to another one first, with --workspace .`, + ) + } + + const directory = saved[name] + + delete saved[name] + await config.saveSavedWorkspaces(saved, configFile) + + output.log( + ` Removed the workspace "${name}". Its folder is left as it is: ${directory}`, + ) + } + async function deleteAlias(name) { await aliases.removeAlias(name) @@ -930,6 +1264,10 @@ export function createCli(overrides = {}) { if (options.version) return output.log(version) if (options['config-path']) return output.log(configFile) if (options['list-aliases']) return printAliases() + if (options['list-workspaces']) return printWorkspaces() + if (options['remove-workspace'] !== undefined) { + return removeWorkspace(options['remove-workspace']) + } if (options['add-alias'] !== undefined) { return createAlias(options['add-alias']) } @@ -942,6 +1280,9 @@ export function createCli(overrides = {}) { if (options['set-color'] !== undefined) { return setColor(options['set-color']) } + if (options['set-depth'] !== undefined) { + return setDepth(options['set-depth']) + } if (options.reset) return reset() if (options['clear-history']) return clearHistory() diff --git a/lib/config.js b/lib/config.js index 5b9ce65..818a37e 100644 --- a/lib/config.js +++ b/lib/config.js @@ -195,6 +195,41 @@ async function saveSetting(name, value, configFile) { ) } +// The saved workspaces, { name: path }, leaving out entries that are not a +// name and a path. Never fails, as readMouseSetting(). +export async function readSavedWorkspaces(configFile) { + const saved = (await readSettings(configFile)).workspaces + + if (!saved || typeof saved !== 'object' || Array.isArray(saved)) return {} + + return Object.fromEntries( + Object.entries(saved).filter( + ([name, directory]) => + name.trim() && typeof directory === 'string' && directory.trim(), + ), + ) +} + +export function saveSavedWorkspaces(workspaces, configFile) { + return saveSetting('workspaces', workspaces, configFile) +} + +// The saved search depth, a whole number from 1 to `max`; 1 when none is +// saved or the value is not one. Never fails, as readMouseSetting(). +export async function readDepthSetting(configFile, max = 3) { + try { + const depth = parseJson(await readFile(configFile, 'utf8'))?.depth + + return Number.isInteger(depth) && depth >= 1 && depth <= max ? depth : 1 + } catch { + return 1 + } +} + +export function saveDepthSetting(depth, configFile) { + return saveSetting('depth', depth, configFile) +} + export function saveMouseSetting(enabled, configFile) { return saveSetting('mouse', enabled, configFile) } diff --git a/lib/list.js b/lib/list.js index 9632595..e13aebf 100644 --- a/lib/list.js +++ b/lib/list.js @@ -321,6 +321,20 @@ export function createList({ let redraw = null const showItems = items.length > 0 + // Expandable items: each child's parent, and the parents shown open, + // starting with the one holding the default value. + const parents = new Map() + + for (const item of items) { + for (const child of item.children ?? []) parents.set(child, item) + } + + const tree = parents.size > 0 + const open = new Set( + items.filter(item => + item.children?.some(child => child.value === defaultValue), + ), + ) const rightButton = rowButtons.findIndex(button => button.right) // The buttons ↑ and Tab reach, in order, after the list. const focusable = [ @@ -331,18 +345,52 @@ export function createList({ let focus = items.some(isSelectable) || focusable.length === 0 ? 'list' : focusable[0] - // Labels line up in a column, as wide as the widest one (icon included), - // up to MAX_LABEL_WIDTH. + // Labels line up in a column, as wide as the widest one (icon and lead + // included, with a child's widest lead: its parent while searching), up + // to MAX_LABEL_WIDTH. const labelWidth = Math.min( MAX_LABEL_WIDTH, Math.max( 0, ...items .filter(item => !item.separator) - .map(item => textWidth(labelText(item))), + .flatMap(item => [ + textWidth(labelText(item)) + (tree ? 2 : 0), + ...(item.children ?? []).map( + child => + textWidth(labelText(child)) + + Math.max(4, textWidth(item.label) + 3), + ), + ]), ), ) + // What is drawn between an item's marker and its label. In a list with + // expandable items: ▸ (closed) or ▾ (open) before a parent, two spaces + // before any other item, and a tree branch before a child (├, or └ for + // the last one), so it reads as part of its parent. While searching, + // nothing, except a child's parent: `shop › `. + function leadOf(item) { + const parent = parents.get(item) + + if (parent && query) return `${parent.label} › ` + if (parent) return parent.children.at(-1) === item ? ' └ ' : ' ├ ' + if (!tree || query) return '' + if (!item.children?.length) return ' ' + + return open.has(item) ? '▾ ' : '▸ ' + } + + // Open or close a parent, keeping the cursor on it. + function toggle(item) { + if (open.has(item)) open.delete(item) + else open.add(item) + + rows = filter() + cursor = rows.findIndex(row => row.item === item) + scrollToCursor() + } + function lineWidth() { return widthFor(output.columns) } @@ -374,14 +422,33 @@ export function createList({ return note ? wrapText(note, width - 2) : [] } + // Without a search, the items, with the children of the open parents + // under them. A search looks through every child too, and shows each + // value once (a recent project can also be a child). function filter() { - if (!query) return items.map(item => ({ item, positions: [] })) + if (!query) { + return items.flatMap(item => [ + { item, positions: [] }, + ...(open.has(item) + ? item.children.map(child => ({ item: child, positions: [] })) + : []), + ]) + } + + const seen = new Set() return fuzzyFilter( - items.filter(item => !item.separator), + items.flatMap(item => + item.separator ? [] : [item, ...(item.children ?? [])], + ), query, item => item.label, - ) + ).filter(({ item }) => { + if (seen.has(item.value)) return false + + seen.add(item.value) + return true + }) } function firstSelectable() { @@ -424,12 +491,15 @@ export function createList({ top = Math.max(0, Math.min(top, rows.length - size)) } + // A value shown both as a parent and as one of its children (a + // monorepo and its root entry) selects the child. function update(selectValue) { rows = filter() - const kept = rows.findIndex( - row => isSelectable(row.item) && row.item.value === selectValue, - ) + const matches = row => + isSelectable(row.item) && row.item.value === selectValue + const child = rows.findIndex(row => matches(row) && parents.has(row.item)) + const kept = child === -1 ? rows.findIndex(matches) : child cursor = kept === -1 ? firstSelectable() : kept scrollToCursor() @@ -484,11 +554,28 @@ export function createList({ )?.id } - // What the list resolves with, and the label its summary shows. + // What the list resolves with, and the label its summary shows. A parent + // is never chosen: it opens or closes, and while searching, the search + // is cleared and it opens. function chooseItem(index) { const { item } = rows[index] + const parent = parents.get(item) + + if (item.children?.length) { + if (!query) return toggle(item) - return { value: item.value, label: item.label } + query = '' + open.add(item) + rows = filter() + cursor = rows.findIndex(row => row.item === item) + scrollToCursor() + return + } + + return { + value: item.value, + label: parent ? `${parent.label} › ${item.label}` : item.label, + } } function pressRowButton(buttonIndex, rowIndex) { @@ -512,6 +599,9 @@ export function createList({ return buttons[first] case 'row': return pressRowButton(Number(first), Number(second)) + case 'toggle': + focus = 'list' + return toggle(rows[first].item) case 'up': return move(-1, visibleRows() - 1) case 'down': @@ -561,8 +651,24 @@ export function createList({ } // ←/→ between buttons; → on an item presses its `right` row button. + // Outside a search, → opens a closed parent, and ← closes an open one, + // or, on a child, closes its parent and moves there. function sideways(direction) { if (focus === 'list') { + const item = cursor === -1 ? null : rows[cursor].item + + if (item && !query) { + const parent = parents.get(item) + + if (direction === 1 && item.children?.length && !open.has(item)) { + return toggle(item) + } + + if (direction === -1 && (open.has(item) || parent)) { + return toggle(parent ?? item) + } + } + if (direction === 1 && rightButton !== -1 && cursor !== -1) { return pressRowButton(rightButton, cursor) } @@ -616,9 +722,10 @@ export function createList({ Promise.resolve() .then(() => item.load()) .then( - ({ detail, hint } = {}) => { + ({ detail, detailEnd, hint } = {}) => { loaded.set(item, { ...(detail && { detail }), + ...(detailEnd && { detailEnd }), ...(hint && { hint }), }) redraw?.() @@ -645,6 +752,14 @@ export function createList({ : [] const matched = new Set(positions) const segments = [[' '], marker] + const lead = leadOf(row.item) + + // A parent's ▸ or ▾ is a button that opens or closes it. + if (lead.trim() && row.item.children) { + segments.push([lead, ...base, { target: `toggle:${index}` }]) + } else if (lead) { + segments.push([lead, 'dim']) + } if (item.icon) segments.push([`${item.icon} `, ...base]) @@ -674,7 +789,7 @@ export function createList({ 0, ) const trailerRoom = trailerWidth ? trailerWidth + 2 : 0 - let used = 4 + textWidth(labelText(item)) + let used = 4 + textWidth(lead + labelText(item)) if (item.detail) { const column = Math.max(used + 2, 4 + labelWidth + 2) @@ -714,13 +829,22 @@ export function createList({ const help = [] if (showItems) { - help.push('↑↓ move', `enter ${focus === 'list' ? enter : 'press'}`) + // On a parent, Enter opens or closes it; ← closes a child's parent. + const item = focus === 'list' ? rows[cursor]?.item : null + const opens = item?.children?.length + ? open.has(item) && !query + ? 'collapse' + : 'expand' + : enter + + help.push('↑↓ move', `enter ${focus === 'list' ? opens : 'press'}`) // Opening with the wheel is not something people expect, so say it. - if (mouse) help.push(`middle-click ${enter}`) + if (mouse) help.push(`middle-click ${opens}`) if (rightButton !== -1) { help.push(`→ ${helpName(rowButtons[rightButton].label)}`) } + if (item && !query && parents.has(item)) help.push('← collapse') if (focusable.length) help.push('tab buttons') } else if (focusable.length) { help.push('enter press') diff --git a/lib/prompts.js b/lib/prompts.js index f552a54..e5f61e4 100644 --- a/lib/prompts.js +++ b/lib/prompts.js @@ -57,6 +57,9 @@ function scriptItem(script, lastScript) { ...(script.hooks?.length && { detailEnd: ` (+ ${script.hooks.join(', ')})`, }), + // "last run" matters more; a script that needs arguments asks for them + // anyway. + ...(script.needsArguments && { hint: 'needs arguments' }), ...(script.name === lastScript && { hint: 'last run', hintStyle: 'accent', @@ -64,6 +67,18 @@ function scriptItem(script, lastScript) { } } +// A package's label under its monorepo: its folder (`api` for +// `packages/api`), or its whole path when another package has the same +// folder name. +function packageLabel(child, siblings) { + const folder = child.path.split('/').at(-1) + const shared = siblings.some( + other => other !== child && other.path.split('/').at(-1) === folder, + ) + + return shared ? child.path : folder +} + // The header and body for the list, left out while unset. function frame({ header, body } = {}) { return { ...(header && { header }), ...(body?.length && { body }) } @@ -143,22 +158,56 @@ export function createPrompts({ }) }, + // Escape resolves with null; the name the user typed otherwise. + async askForWorkspaceName(suggested, validate) { + const name = await inputOrEscape({ + message: 'Name for this workspace', + default: suggested, + validate, + theme, + }) + + return name === null ? null : name.trim() + }, + async chooseWorkspace( folders, - { current, details, cancellable = false, ...options } = {}, + { saved = [], current, details, cancellable = false, ...options } = {}, ) { + const savedItems = saved.map(({ name, directory, missing }) => ({ + label: name, + value: directory, + detail: directory, + ...(missing + ? { disabled: 'not found' } + : directory === current && { hint: 'current' }), + })) const items = folders.map(folder => ({ label: folder, value: folder, ...(details && { load: () => details(folder) }), ...(folder === current && { hint: 'current' }), })) + // Group titles only when there is something to tell apart. + const groups = + savedItems.length && items.length + ? [ + { separator: 'Saved' }, + ...savedItems, + { separator: 'Suggested' }, + ...items, + ] + : [...savedItems, ...items] + const offered = [...saved.map(({ directory }) => directory), ...folders] return menu({ message: 'Select your workspace folder', - items: [...items, { label: '… Enter another path', value: ENTER_PATH }], + items: [ + ...groups, + { label: '… Enter another path', value: ENTER_PATH }, + ], ...(cancellable && { escape: { value: null, label: 'back' } }), - ...(folders.includes(current) && { default: current }), + ...(offered.includes(current) && { default: current }), searchable: false, clickOpens: true, fullscreen: true, @@ -186,13 +235,42 @@ export function createPrompts({ }) }, - async chooseProject(projects, { recent = [], details, ...options } = {}) { + async chooseProject( + projects, + { recent = [], details, packages, default: selected, ...options } = {}, + ) { const item = project => projectItem(project, details) + // A monorepo expands into `root`, which opens the scripts of its own + // package.json, then its packages, each labelled with its folder + // (packageLabel), in "Recent" as in "All projects"; a recent package + // has its full name. + const tree = project => { + const children = packages?.(project) ?? [] + + if (children.length === 0) return item(project) + + const root = { + label: 'root', + value: project, + ...(details && { load: () => details(project, { root: true }) }), + } + + return { + ...item(project), + children: [ + root, + ...children.map(child => ({ + ...item(child), + label: packageLabel(child, children), + })), + ], + } + } const others = projects.filter(project => !recent.includes(project)) - const items = others.map(item) + const items = others.map(tree) if (recent.length > 0) { - items.unshift({ separator: 'Recent' }, ...recent.map(item), { + items.unshift({ separator: 'Recent' }, ...recent.map(tree), { separator: 'All projects', }) } @@ -206,6 +284,7 @@ export function createPrompts({ ], escape: { value: null, label: 'exit' }, enter: 'open', + ...(selected && { default: selected }), clickOpens: true, fullscreen: true, ...frame(options), @@ -237,7 +316,10 @@ export function createPrompts({ rowButtons: [ { label: '▶ run', - value: script => ({ script, withArguments: false }), + value: script => ({ + script, + withArguments: Boolean(script.needsArguments), + }), }, { label: '… run with args', @@ -253,17 +335,25 @@ export function createPrompts({ // Enter, or a click on the selected script. if (scripts.includes(choice)) { - return { script: choice, withArguments: forArguments } + return { + script: choice, + withArguments: forArguments || Boolean(choice.needsArguments), + } } return choice }, // Escape goes back: null instead of the arguments. - async askForArguments(scriptName) { + // With `required`, an empty answer is refused. + async askForArguments(scriptName, { required = false } = {}) { const text = await inputOrEscape({ message: `Arguments for ${scriptName}`, validate: value => { + if (required && !value.trim()) { + return `${scriptName} cannot run without arguments.` + } + try { splitArguments(value) return true @@ -303,6 +393,7 @@ export function createPrompts({ export const { askForArguments, askForWorkspace, + askForWorkspaceName, chooseAccent, confirmWorkspaceChange, chooseProject, diff --git a/lib/script-arguments.js b/lib/script-arguments.js new file mode 100644 index 0000000..b362635 --- /dev/null +++ b/lib/script-arguments.js @@ -0,0 +1,99 @@ +// Recognising scripts that cannot run without arguments. +// Used by workspace.js. + +import { splitArguments } from './args.js' + +// The options that take a value, by tool. +const VALUE_OPTIONS = { + yarn: ['--from', '--include', '--exclude', '-j', '--jobs'], + pnpm: ['--filter', '-F', '--filter-prod', '--dir', '-C', '--test-pattern'], + npm: ['--workspace', '-w', '--prefix'], + npx: ['--package', '-p'], + bun: ['--filter', '-F', '--cwd'], + turbo: ['--filter', '-F', '--concurrency'], + lerna: ['--scope', '--ignore', '--concurrency'], +} + +// The words that are not options, in order. +function operands(words, valueOptions = []) { + const found = [] + + for (let index = 0; index < words.length; index++) { + const word = words[index] + + if (!word.startsWith('-')) found.push(word) + else if (valueOptions.includes(word)) index++ + } + + return found +} + +// Whether `command` fails unless arguments are added after it: a helper +// that other scripts call with the rest of the command, such as +// `"packages": "yarn workspaces foreach --all"` called as +// `yarn packages run test`. It is decided from the command alone, so the +// menu can ask for the arguments first and direct mode can refuse to start +// it without any; getScripts() in workspace.js marks such scripts with +// `needsArguments: true`. +// +// Only the last command of a chain (after &&, ||, ; or |) is looked at, +// since the arguments are added at the end. It needs arguments when, once +// its options are left out (with the value of any VALUE_OPTIONS), nothing +// is left after: +// +// yarn workspaces foreach yarn workspace +// pnpm with only options (-r, --filter , …) +// npm with only workspace options (-ws, --workspace ), npm exec, +// npm x, npx +// bun with only --filter +// turbo run, lerna run, lerna exec +// +// Anything else counts as runnable on its own, so a script is never +// blocked by mistake. +export function needsArguments(command) { + let words + + try { + words = splitArguments(command.split(/&&|\|\||[;|]/).at(-1)) + } catch { + return false + } + + const [tool, ...rest] = words + const options = rest.filter(word => word.startsWith('-')) + const left = operands(rest, VALUE_OPTIONS[tool]) + + // `pnpm --version` or `npm --help` runs on its own. + if (options.some(option => /^(-v|--version|-h|--help)$/.test(option))) { + return false + } + + switch (tool) { + case 'yarn': + return ( + (left[0] === 'workspaces' && + left[1] === 'foreach' && + left.length === 2) || + (left[0] === 'workspace' && left.length === 2) + ) + case 'pnpm': + case 'bun': + return options.length > 0 && left.length === 0 + case 'npm': + return ( + (left.length === 0 && + options.some(option => + ['-ws', '--workspaces', '--workspace', '-w'].includes(option), + )) || + (left.length === 1 && ['exec', 'x'].includes(left[0])) + ) + case 'npx': + return left.length === 0 + case 'turbo': + return left.length === 1 && left[0] === 'run' + case 'lerna': + return left.length === 1 && ['run', 'exec'].includes(left[0]) + default: + return false + } +} diff --git a/lib/ui.js b/lib/ui.js index e8de48c..7ea358f 100644 --- a/lib/ui.js +++ b/lib/ui.js @@ -141,7 +141,7 @@ export function createUi({ useColors = USE_COLORS } = {}) { // The header box, as lines of segments at most `width` columns wide, starting // with the same two-column margin as the rest of the list. export function headerLines( - { workspace, crumbs = [], tag, toolbar = [] }, + { workspace, name: workspaceName, crumbs = [], tag, toolbar = [] }, width, ) { // The box, corners included; its title row holds "╭─ ", the title, a space, @@ -149,7 +149,10 @@ export function headerLines( const box = Math.max(10, width - 2) const room = box - 6 // A long folder name is cut to leave room for the breadcrumb. - const folder = truncateText(folderName(workspace), Math.max(1, room - 2)) + const folder = truncateText( + workspaceName || folderName(workspace), + Math.max(1, room - 2), + ) const name = `◆ ${folder}` const trail = crumbs.map(crumb => ` › ${crumb}`).join('') const tagPart = tag ? ` ${tag} ─` : '' diff --git a/lib/workspace.js b/lib/workspace.js index 7f87a0c..3f340b3 100644 --- a/lib/workspace.js +++ b/lib/workspace.js @@ -6,6 +6,7 @@ import os from 'node:os' import path from 'node:path' import { parseJson } from './json.js' +import { needsArguments } from './script-arguments.js' // Check whether a path points to an accessible directory. export async function isDirectory(directory) { @@ -209,35 +210,296 @@ async function isFolder(root, entry) { return entry.isSymbolicLink() && isDirectory(path.join(root, entry.name)) } -// List immediate child directories in the workspace, and links to them: -// projects with a package.json first, then the others, each group sorted by -// name. -export async function getProjects(root) { - const entries = await readdir(root, { withFileTypes: true }) +// The package folders of a pnpm-workspace.yaml: the `packages` list, in +// block (`- 'apps/*'`) or flow (`['apps/*']`) style. Only that key is read, +// so a small reader does instead of a YAML parser. +export function parsePnpmWorkspace(content) { + const lines = ( + content.charCodeAt(0) === 0xfeff ? content.slice(1) : content + ).split(/\r?\n/) + const start = lines.findIndex(line => /^packages\s*:/.test(line)) - const projects = await Promise.all( + if (start === -1) return [] + + const unquote = value => { + const text = value.trim() + // A comment can follow the value, quoted or not. + const quoted = /^(['"])(.*?)\1(?:\s+#.*)?$/.exec(text) + + return quoted ? quoted[2] : text.replace(/\s+#.*$/, '').trim() + } + const rest = lines[start].replace(/^packages\s*:/, '').trim() + + if (rest.startsWith('[')) { + // A flow list can run over several lines, up to its ]; comments are + // left out line by line. + let flow = rest + + for ( + let index = start + 1; + !flow.includes(']') && index < lines.length; + index++ + ) { + flow += ` ${lines[index].replace(/(^|\s)#.*$/, '')}` + } + + return flow + .replace(/^\[/, '') + .replace(/\].*$/, '') + .split(',') + .map(unquote) + .filter(Boolean) + } + + const patterns = [] + + for (const line of lines.slice(start + 1)) { + if (!line.trim() || line.trim().startsWith('#')) continue + + // Items may be indented or not (`- apps/*` right under `packages:`). + const item = /^\s*-\s+(.+)$/.exec(line) + + // The list ends at the next key. + if (!item) break + + patterns.push(unquote(item[1])) + } + + return patterns.filter(Boolean) +} + +// The package folder patterns of a monorepo, or null for any other project: +// the `workspaces` field of package.json (npm, Yarn and Bun: a list, or an +// object with a `packages` list), else the `packages` of pnpm-workspace.yaml. +export async function readWorkspacePatterns(directory) { + let field + + try { + field = parseJson( + await readFile(path.join(directory, 'package.json'), 'utf8'), + )?.workspaces + } catch { + // An unreadable package.json is reported when its scripts are read. + } + + const list = Array.isArray(field) ? field : field?.packages + let patterns = Array.isArray(list) + ? list.filter(pattern => typeof pattern === 'string') + : [] + + if (patterns.length === 0) { + try { + patterns = parsePnpmWorkspace( + await readFile(path.join(directory, 'pnpm-workspace.yaml'), 'utf8'), + ) + } catch { + // No pnpm workspace either. + } + } + + return patterns.length > 0 ? patterns : null +} + +// A workspace pattern as a regular expression for a folder path with /: +// `*` matches within one folder name, `**` any number of folders. +function patternToRegExp(pattern) { + let source = '' + + for (let index = 0; index < pattern.length; index++) { + const character = pattern[index] + + if (character === '/' && pattern.slice(index) === '/**' && index > 0) { + // A trailing `/**` also matches the folder itself, as in pnpm, so + // `!**/test/**` leaves out `test` too. + source += '(?:/.*)?' + break + } else if (character === '*' && pattern[index + 1] === '*') { + // `**/` may also match no folder at all. + const slash = pattern[index + 2] === '/' + + source += slash ? '(?:.*/)?' : '.*' + index += slash ? 2 : 1 + } else if (character === '*') source += '[^/]*' + else if (character === '?') source += '[^/]' + else source += character.replace(/[.+^${}()|[\]\\]/g, '\\$&') + } + + return new RegExp(`^${source}$`) +} + +// How many folders deep a `**` pattern is followed. +const MAX_PACKAGE_DEPTH = 5 + +// Clean a pattern up: `./apps/*/` and `apps/*/package.json` mean `apps/*`. +function cleanPattern(pattern) { + return pattern + .trim() + .replaceAll('\\', '/') + .replace(/^\.\//, '') + .replace(/\/package\.json$/, '') + .replace(/\/+$/, '') +} + +// The folders under `base` (a path with /, relative to `root`) down to +// `levels` more folders, never entering node_modules or dot-folders. +async function foldersUnder(root, base, levels) { + if (levels === 0) return [] + + let entries + + try { + entries = await readdir(path.join(root, base), { withFileTypes: true }) + } catch { + return [] + } + + const found = await Promise.all( entries .filter(entry => !isNeverProject(entry.name)) .map(async entry => { - if (!(await isFolder(root, entry))) return null + if (!(await isFolder(path.join(root, base), entry))) return [] + + const relative = base ? `${base}/${entry.name}` : entry.name + + return [relative, ...(await foldersUnder(root, relative, levels - 1))] + }), + ) - const directory = path.join(root, entry.name) + return found.flat() +} + +// The packages of a monorepo: the folders its workspace patterns match +// (patterns starting with ! leave folders out) that have a package.json, +// each named by its path in the monorepo (`packages/api`), with the `name` +// from its package.json as `packageName`, sorted by path. +export async function getPackages(directory, patterns) { + const cleaned = patterns.map(cleanPattern) + const include = cleaned.filter(pattern => !pattern.startsWith('!')) + const exclude = cleaned + .filter(pattern => pattern.startsWith('!')) + .map(pattern => patternToRegExp(cleanPattern(pattern.slice(1)))) + const paths = new Set() + + await Promise.all( + include.map(async pattern => { + const parts = pattern.split('/') + const wild = parts.findIndex(part => /[*?]/.test(part)) + + if (wild === -1) { + if (pattern && pattern !== '.') paths.add(pattern) + return + } + + const base = parts.slice(0, wild).join('/') + const levels = parts.includes('**') + ? MAX_PACKAGE_DEPTH + : parts.length - wild + const matcher = patternToRegExp(pattern) + + for (const folder of await foldersUnder(directory, base, levels)) { + if (matcher.test(folder)) paths.add(folder) + } + }), + ) + + const packages = await Promise.all( + [...paths] + .filter(folder => !exclude.some(matcher => matcher.test(folder))) + .map(async folder => { + const packageDirectory = path.join(directory, ...folder.split('/')) + + if (!(await hasPackageJson(packageDirectory))) return null + + let packageName + + try { + packageName = parseJson( + await readFile(path.join(packageDirectory, 'package.json'), 'utf8'), + )?.name + } catch { + // The name is only shown; its scripts report a broken file. + } return { - name: entry.name, - directory, - hasPackageJson: await hasPackageJson(directory), + path: folder, + directory: packageDirectory, + ...(typeof packageName === 'string' && { packageName }), } }), ) - return projects - .filter(project => project !== null) - .sort( - (a, b) => - Number(b.hasPackageJson) - Number(a.hasPackageJson) || - compareNames(a.name, b.name), - ) + return packages.filter(Boolean).sort((a, b) => compareNames(a.path, b.path)) +} + +// How deep getProjects() looks for projects: 1 lists the immediate +// subfolders only. +export const DEFAULT_DEPTH = 1 +export const MAX_DEPTH = 3 + +// The projects in `folder`, `level` folders below the workspace. A folder +// with a package.json is a project, and the search stops there. Any other +// folder is searched in turn while `level` is under `depth`; it is replaced +// by what it holds when that includes a project, and listed itself, as a +// folder without a package.json, otherwise. +async function findProjects(folder, prefix, level, depth) { + const entries = await readdir(folder, { withFileTypes: true }) + + const found = await Promise.all( + entries + .filter(entry => !isNeverProject(entry.name)) + .map(async entry => { + if (!(await isFolder(folder, entry))) return [] + + const directory = path.join(folder, entry.name) + // Always with /, so a name reads the same on every system. + const name = prefix + entry.name + + if (await hasPackageJson(directory)) { + const workspaces = await readWorkspacePatterns(directory) + + return [ + { + name, + directory, + hasPackageJson: true, + ...(workspaces && { workspaces }), + }, + ] + } + + if (level < depth) { + // A subfolder that cannot be read simply holds no projects. + const inside = await findProjects( + directory, + `${name}/`, + level + 1, + depth, + ).catch(() => []) + + if (inside.some(project => project.hasPackageJson)) return inside + } + + return [{ name, directory, hasPackageJson: false }] + }), + ) + + return found.flat() +} + +// List the projects in the workspace: its subfolders, and links to them, +// down to `depth` levels (DEFAULT_DEPTH to MAX_DEPTH), as findProjects() +// describes. Projects found deeper are named by their path in the workspace +// (`clients/acme/web`). Projects with a package.json come first, then the +// others, each group sorted by name. +export async function getProjects(root, { depth = DEFAULT_DEPTH } = {}) { + const levels = Math.min(MAX_DEPTH, Math.max(1, Math.trunc(depth) || 1)) + const projects = await findProjects(root, '', 1, levels) + + return projects.sort( + (a, b) => + Number(b.hasPackageJson) - Number(a.hasPackageJson) || + compareNames(a.name, b.name), + ) } // Read npm scripts from a project's package.json. With `groupHooks: false`, @@ -284,7 +546,11 @@ export async function getScripts(directory, { groupHooks = true } = {}) { const list = Object.entries(scripts) .filter(([, command]) => typeof command === 'string') - .map(([name, command]) => ({ name, command })) + .map(([name, command]) => + needsArguments(command) + ? { name, command, needsArguments: true } + : { name, command }, + ) return groupHooks ? groupLifecycleScripts(list) : list } diff --git a/test/args.test.js b/test/args.test.js index ae1540d..76b6944 100644 --- a/test/args.test.js +++ b/test/args.test.js @@ -55,9 +55,12 @@ test('parseCliArgs explains how to get help for invalid input', () => { test('formatHelp documents every option', () => { for (const flag of [ '--workspace', + '--list-workspaces', + '--remove-workspace', '--no-mouse', '--set-mouse', '--set-color', + '--set-depth', '--config-path', '--clear-history', '--add-alias', @@ -91,13 +94,20 @@ test('formatHelp defaults to plain text', () => { dws web dev -- --port 4000 Options: - -w, --workspace Use as the workspace and save it + -w, --workspace + Use a saved workspace, or (saved too) + --list-workspaces List the saved workspaces + --remove-workspace + Forget a saved workspace --no-mouse Use only the keyboard in menus, this time --set-mouse Save whether menus use the mouse --set-color Save the accent colour: cyan, blue, purple, magenta, pink, orange, teal, sky, lavender, coral, gold, bold + --set-depth <1-3> Save how many folder levels to search for + projects (1, the default, lists only the + workspace's own subfolders) --config-path Print the configuration file location --clear-history Forget recently used projects and scripts --add-alias Create another command that starts the CLI @@ -135,9 +145,9 @@ test('formatHelp applies colors to headings, commands, options and environment', assert.ok(colored.includes('[accent]dws web[/accent]')) assert.ok(colored.includes('[bold]Options:[/bold]')) assert.ok( - colored.includes('[accent]-w, --workspace[/accent] [dim][/dim]'), + colored.includes('[accent]-w, --workspace[/accent] [dim][/dim]'), ) - assert.ok(colored.includes('Use as the workspace')) + assert.ok(colored.includes('Use a saved workspace, or ')) assert.ok(colored.includes('[bold]Environment:[/bold]')) assert.ok(colored.includes('[accent]DEV_WORKSPACE_CONFIG[/accent]')) }) @@ -206,6 +216,26 @@ test('parseCliArgs accepts only the accent colours for --set-color', () => { ) }) +test('parseCliArgs accepts only 1, 2 and 3 for --set-depth', () => { + for (const depth of ['1', '2', '3']) { + assert.deepEqual( + { ...parseCliArgs(['--set-depth', depth]) }, + { + 'set-depth': depth, + }, + ) + } + + for (const depth of ['0', '4', 'two', '1.5']) { + assert.throws( + () => parseCliArgs(['--set-depth', depth]), + new RegExp( + `Use --set-depth with 1, 2 or 3, not "${depth}"\\.\\n.*--help`, + ), + ) + } +}) + test('formatHelp names every accent colour', () => { const help = formatHelp().replace(/\s+/g, ' ') diff --git a/test/benchmark.test.js b/test/benchmark.test.js new file mode 100644 index 0000000..9a4bcd5 --- /dev/null +++ b/test/benchmark.test.js @@ -0,0 +1,48 @@ +// The "Bigger workspaces" milestone's goal: a 200-project workspace searched +// two levels deep lists in under 500 ms. + +import test from 'node:test' +import assert from 'node:assert/strict' +import { mkdtemp, mkdir, rm, writeFile } from 'node:fs/promises' +import os from 'node:os' +import path from 'node:path' + +import { getProjects } from '../lib/workspace.js' + +const BUDGET = 500 + +test('a 200-project workspace with depth 2 lists in under 500 ms', async () => { + const root = await mkdtemp(path.join(os.tmpdir(), 'dev-workspace-bench-')) + + try { + // 20 groups of 10 projects, as in clients//, each with + // the files a real project has next to its package.json. + for (let group = 0; group < 20; group++) { + for (let index = 0; index < 10; index++) { + const project = path.join(root, `group-${group}`, `project-${index}`) + + await mkdir(path.join(project, 'node_modules', 'dependency'), { + recursive: true, + }) + await mkdir(path.join(project, 'src')) + await mkdir(path.join(project, '.git')) + await writeFile( + path.join(project, 'package.json'), + JSON.stringify({ name: `project-${index}`, scripts: { dev: 'x' } }), + ) + } + } + + const started = performance.now() + const projects = await getProjects(root, { depth: 2 }) + const elapsed = performance.now() - started + + assert.equal(projects.length, 200) + assert.ok( + elapsed < BUDGET, + `listed in ${elapsed.toFixed(0)} ms, budget ${BUDGET} ms`, + ) + } finally { + await rm(root, { recursive: true, force: true }) + } +}) diff --git a/test/cli.test.js b/test/cli.test.js index 4112e4e..4534ba1 100644 --- a/test/cli.test.js +++ b/test/cli.test.js @@ -3,7 +3,12 @@ import path from 'node:path' import test from 'node:test' import assert from 'node:assert/strict' -import { createCli, findProject, formatDuration } from '../lib/cli.js' +import { + checkWorkspaceName, + createCli, + findProject, + formatDuration, +} from '../lib/cli.js' import { CHANGE_WORKSPACE, ENTER_PATH, @@ -20,6 +25,7 @@ const WORKSPACE = path.resolve('fake/workspace') function createDependencies(overrides = {}) { const calls = { savedWorkspaces: [], + namedWorkspaces: [], discoveredWorkspaces: [], savedStates: [], mouse: [], @@ -49,6 +55,11 @@ function createDependencies(overrides = {}) { }), migrateLegacyConfig: async () => null, readColorSetting: async () => 'cyan', + readDepthSetting: async () => 1, + readSavedWorkspaces: async () => ({}), + saveSavedWorkspaces: async (workspaces, file) => { + calls.namedWorkspaces.push({ workspaces, file }) + }, readMouseSetting: async () => true, readWorkspaceConfig: async () => WORKSPACE, resetWorkspaceConfig: async () => [], @@ -100,6 +111,9 @@ function createDependencies(overrides = {}) { prompts: { askForArguments: async () => [], askForWorkspace: async () => WORKSPACE, + askForWorkspaceName: async suggested => suggested, + // The saved workspace is always offered: type a path by default. + chooseWorkspace: async () => ENTER_PATH, chooseProject: async (projects, options) => { calls.menus.push(options) return null @@ -354,7 +368,12 @@ test('CLI runs a selected script and reports success', async () => { const lines = loggedText(calls).split('\n') assert.deepEqual(calls.runHeaders, [ - { workspace: WORKSPACE, crumbs: ['example', 'dev'], tag: 'npm · default' }, + { + workspace: WORKSPACE, + name: 'workspace', + crumbs: ['example', 'dev'], + tag: 'npm · default', + }, ]) assert.deepEqual(lines.slice(0, 6), [ '', @@ -771,21 +790,17 @@ test('CLI offers a workspace change when the project list is empty', async () => test('CLI saves the workspace passed with --workspace', async () => { const otherWorkspace = path.resolve('fake/other') - let configRead = false - const { dependencies, calls } = createDependencies({ - config: { - readWorkspaceConfig: async () => { - configRead = true - return WORKSPACE - }, - }, - }) + const { dependencies, calls } = createDependencies() await createCli(dependencies).start(['--workspace', 'fake/other']) - assert.equal(configRead, false) assert.equal(calls.savedWorkspaces[0].workspace, otherWorkspace) + // The previous workspace stays saved, under its folder name. + assert.deepEqual(calls.namedWorkspaces.at(-1).workspaces, { + workspace: WORKSPACE, + other: otherWorkspace, + }) assert.equal(calls.discoveredWorkspaces[0].root, otherWorkspace) }) @@ -1323,6 +1338,49 @@ test('findProject matches exactly, then ignoring case, then by unique prefix', ( assert.throws(() => find('mobile'), /No project named "mobile" in /) }) +test('findProject finds nested projects by path or by their last part', () => { + const projects = [ + 'web', + 'clients/acme/api', + 'clients/acme/site', + 'x/site', + ].map(name => ({ name, directory: path.join(WORKSPACE, name) })) + const find = name => findProject(projects, name, WORKSPACE).name + + assert.equal(find('clients/acme/api'), 'clients/acme/api') + assert.equal(find('clients\\acme\\api'), 'clients/acme/api') + assert.equal(find('API'), 'clients/acme/api') + assert.equal(find('web'), 'web') + assert.equal(find('clients/acme/s'), 'clients/acme/site') + assert.throws( + () => find('site'), + /"site" matches several projects: clients\/acme\/site, x\/site\./, + ) +}) + +test('findProject finds a monorepo by prefix, not its packages too', () => { + const shop = { name: 'shop', directory: path.join(WORKSPACE, 'shop') } + const projects = [ + shop, + { name: 'blog', directory: path.join(WORKSPACE, 'blog') }, + ...['packages/api', 'packages/web'].map(folder => ({ + name: `shop/${folder}`, + directory: path.join(shop.directory, folder), + // A copy, as the session's package lists hold the monorepo read first. + monorepo: { ...shop }, + })), + ] + const find = name => findProject(projects, name, WORKSPACE).name + + assert.equal(find('sho'), 'shop') + assert.equal(find('shop/packages/a'), 'shop/packages/api') + assert.equal(find('api'), 'shop/packages/api') + assert.throws( + () => find('shop/packages'), + /"shop\/packages" matches several projects: shop\/packages\/api, shop\/packages\/web\./, + ) +}) + test('CLI runs a script directly and returns its exit code', async () => { const { dependencies, calls, runs } = directDependencies() @@ -2092,3 +2150,499 @@ test('CLI goes back to the scripts on Escape at the arguments prompt', async () assert.deepEqual(runs, []) assert.match(loggedText(calls), /Press Esc to go back to the scripts\./) }) + +test('CLI --set-depth saves the depth and exits', async () => { + const saved = [] + const { dependencies, calls } = createDependencies({ + config: { + saveDepthSetting: async (depth, file) => saved.push({ depth, file }), + }, + }) + + await createCli(dependencies).start(['--set-depth', '2']) + + assert.deepEqual(saved, [ + { depth: 2, file: '/fake/home/.dev-workspace-cli/config.json' }, + ]) + assert.match(calls.logs.at(-1)[0], /searches 2 folder levels/) + assert.equal(calls.discoveredWorkspaces.length, 0) + + await createCli(dependencies).start(['--set-depth', '1']) + + assert.match(calls.logs.at(-1)[0], /workspace folders only/) +}) + +test('CLI lists projects down to the saved depth', async () => { + const asked = [] + const { dependencies } = createDependencies({ + config: { readDepthSetting: async () => 3 }, + workspace: { + getProjects: async (root, options) => { + asked.push({ root, ...options }) + return [] + }, + }, + }) + + await createCli(dependencies).run() + + assert.deepEqual(asked, [{ root: WORKSPACE, depth: 3 }]) +}) + +// A monorepo, shop, with one package, next to an ordinary project. +function monorepoDependencies(overrides = {}) { + const shop = { + name: 'shop', + directory: path.join(WORKSPACE, 'shop'), + hasPackageJson: true, + workspaces: ['packages/*'], + } + const web = { + name: 'web', + directory: path.join(WORKSPACE, 'web'), + hasPackageJson: true, + } + const apiDirectory = path.join(shop.directory, 'packages', 'api') + const asked = { packageManagers: [], packages: [], branches: [], runs: [] } + const result = createDependencies({ + ...overrides, + workspace: { + getProjects: async () => [shop, web], + getPackages: async (directory, patterns) => { + asked.packages.push([directory, patterns]) + return [ + { + path: 'packages/api', + directory: apiDirectory, + packageName: '@shop/api', + }, + ] + }, + getScripts: async directory => + directory === shop.directory + ? [{ name: 'build', command: 'turbo build' }] + : [ + { name: 'dev', command: 'vite' }, + { name: 'test', command: 'vitest' }, + ], + detectPackageManager: async directory => { + asked.packageManagers.push(directory) + return { name: 'pnpm', source: 'pnpm-lock.yaml', runsHooks: true } + }, + // Only the monorepo is a Git repository: its package has no .git. + readGitBranch: async directory => { + asked.branches.push(directory) + return directory === shop.directory ? 'main' : null + }, + ...overrides.workspace, + }, + commands: { + runCommand: async (...args) => { + asked.runs.push(args) + return { code: 0 } + }, + }, + }) + + return { ...result, shop, web, apiDirectory, asked } +} + +test('CLI opens a package of a monorepo and runs its script there', async () => { + const lists = [] + let scriptMenus = 0 + const { dependencies, shop, web, apiDirectory, asked } = monorepoDependencies( + { + prompts: { + chooseProject: async (projects, options) => { + lists.push(options) + + // The first time, open the package; then exit. + return lists.length === 1 ? options.packages(shop)[0] : null + }, + chooseScript: async scripts => { + scriptMenus++ + return scriptMenus === 1 ? { script: scripts[0] } : null + }, + waitAfterCommand: async () => false, + }, + }, + ) + + await createCli(dependencies).run() + + const [api] = lists[0].packages(shop) + + assert.equal(api.name, 'shop/packages/api') + assert.equal(api.monorepo, shop) + assert.equal(lists[0].packages(web), undefined) + // Read for the list, then again once back from one of its packages. + assert.deepEqual(asked.packages, [ + [shop.directory, ['packages/*']], + [shop.directory, ['packages/*']], + ]) + + // The package runs in its own folder, with its monorepo's tool. + assert.deepEqual(asked.runs, [ + ['dev', apiDirectory, { packageManager: 'pnpm' }], + ]) + assert.equal(asked.packageManagers.at(-1), shop.directory) + + // Back in the list, the package is recent and selected again. + assert.equal(lists[1].recent[0].directory, apiDirectory) + assert.equal(lists[1].default.directory, apiDirectory) +}) + +test('CLI keeps the packages of a monorepo after another project is opened', async () => { + let lists = 0 + const { dependencies, shop, web, asked } = monorepoDependencies({ + prompts: { + chooseProject: async () => (++lists === 1 ? web : null), + chooseScript: async () => null, + }, + }) + + await createCli(dependencies).run() + + assert.equal(lists, 2) + assert.deepEqual(asked.packages, [[shop.directory, ['packages/*']]]) +}) + +test('CLI shows a monorepo with its package count, and a package with its name', async () => { + let options + const { dependencies, shop } = monorepoDependencies({ + prompts: { + chooseProject: async (projects, given) => { + options = given + return null + }, + }, + }) + + await createCli(dependencies).run() + + const [api] = options.packages(shop) + + assert.deepEqual(await options.details(shop), { + detail: '1 package · 1 script', + detailEnd: [ + [' · ', 'dim'], + ['main', 'mainBranch'], + ], + hint: 'pnpm', + }) + // A package without a .git of its own shows no branch. + assert.deepEqual(await options.details(api), { + detail: '2 scripts', + hint: '@shop/api', + }) +}) + +test('CLI shows the branch of a package that is a Git repository of its own', async () => { + let options + const { dependencies, shop, apiDirectory } = monorepoDependencies({ + prompts: { + chooseProject: async (projects, given) => { + options = given + return null + }, + }, + workspace: { + readGitBranch: async directory => + directory === apiDirectory ? 'feat/login' : 'main', + }, + }) + + await createCli(dependencies).run() + + const [api] = options.packages(shop) + + assert.deepEqual(await options.details(api), { + detail: '2 scripts', + detailEnd: [ + [' · ', 'dim'], + ['feat/login', 'branch'], + ], + hint: '@shop/api', + }) +}) + +test('CLI runs a package script directly, by its full name or its last part', async () => { + for (const name of ['shop/packages/api', 'api']) { + const { dependencies, apiDirectory, asked } = monorepoDependencies() + + assert.equal(await createCli(dependencies).start([name, 'test']), 0) + assert.deepEqual(asked.runs, [ + ['test', apiDirectory, { packageManager: 'pnpm' }], + ]) + } +}) + +const WORK = path.resolve('fake/work') +const GONE = path.resolve('fake/gone') + +// A configuration with two saved workspaces, the current one first, and a +// third one whose folder is gone. +function namedDependencies(overrides = {}) { + return createDependencies({ + ...overrides, + config: { + readSavedWorkspaces: async () => ({ + dev: WORKSPACE, + work: WORK, + old: GONE, + }), + ...overrides.config, + }, + workspace: { + isDirectory: async directory => directory !== GONE, + ...overrides.workspace, + }, + }) +} + +test('CLI switches to a saved workspace by name with --workspace', async () => { + const { dependencies, calls } = namedDependencies() + + await createCli(dependencies).start(['--workspace', 'WORK']) + + assert.equal(calls.savedWorkspaces[0].workspace, WORK) + assert.equal(calls.discoveredWorkspaces[0].root, WORK) + // The header names the workspace. + assert.match( + calls.menus[0] + .header(80) + .map(line => line.map(([text]) => text).join('')) + .join('\n'), + /◆ work ─/, + ) + + await assert.rejects( + createCli(namedDependencies().dependencies).start(['-w', 'old']), + /The workspace "old" is unavailable: .*gone\. Remove it with --remove-workspace old\./, + ) +}) + +test('CLI offers the saved workspaces, then the other suggested folders', async () => { + const other = path.resolve('fake/other') + const choices = [CHANGE_WORKSPACE, null] + const shown = [] + const named = [] + + const { dependencies, calls } = namedDependencies({ + workspace: { + suggestWorkspaces: async () => [WORK, other], + }, + prompts: { + chooseProject: async () => choices.shift(), + chooseWorkspace: async (folders, options) => { + shown.push([folders, options]) + return other + }, + askForWorkspaceName: async (suggested, validate) => { + named.push({ suggested, taken: validate('Work'), empty: validate(' ') }) + return 'clients' + }, + }, + }) + + await createCli(dependencies).run() + + const [[folders, options]] = shown + + // A saved folder is not suggested again. + assert.deepEqual(folders, [other]) + assert.deepEqual(options.saved, [ + { name: 'dev', directory: WORKSPACE, missing: false }, + { name: 'work', directory: WORK, missing: false }, + { name: 'old', directory: GONE, missing: true }, + ]) + assert.deepEqual(named, [ + { + suggested: 'other', + taken: `"work" already names ${WORK}.`, + empty: 'Please enter a name.', + }, + ]) + assert.deepEqual(calls.namedWorkspaces.at(-1).workspaces, { + dev: WORKSPACE, + work: WORK, + old: GONE, + clients: other, + }) + assert.match(loggedText(calls), /Workspace saved: .*other as "clients"/) +}) + +test('CLI asks no name for a saved workspace, and Escape at the name goes back', async () => { + for (const [picked, name, saved] of [ + [WORK, undefined, WORK], + [path.resolve('fake/other'), null, undefined], + ]) { + const choices = [CHANGE_WORKSPACE, null] + let asked = false + + const { dependencies, calls } = namedDependencies({ + prompts: { + chooseProject: async () => choices.shift(), + chooseWorkspace: async () => picked, + askForWorkspaceName: async () => { + asked = true + return name + }, + }, + }) + + await createCli(dependencies).run() + + assert.equal(asked, name !== undefined) + assert.equal(calls.savedWorkspaces[0]?.workspace, saved) + } +}) + +test('CLI names a new workspace after its folder, made unique', async () => { + const otherDev = path.resolve('elsewhere/dev') + const { dependencies, calls } = namedDependencies() + + await createCli(dependencies).start(['--workspace', otherDev]) + + assert.equal(calls.namedWorkspaces.at(-1).workspaces['dev-2'], otherDev) +}) + +test('CLI lists and removes saved workspaces', async () => { + const { dependencies, calls } = namedDependencies() + + await createCli(dependencies).start(['--list-workspaces']) + + assert.deepEqual( + calls.logs.map(([line]) => line), + [` dev ${WORKSPACE} (current)`, ` work ${WORK}`, ` old ${GONE}`], + ) + + await createCli(dependencies).start(['--remove-workspace', 'old']) + + assert.deepEqual(calls.namedWorkspaces.at(-1).workspaces, { + dev: WORKSPACE, + work: WORK, + }) + assert.match(calls.logs.at(-1)[0], /Removed the workspace "old"/) + + await assert.rejects( + createCli(dependencies).start(['--remove-workspace', 'dev']), + /"dev" is the current workspace\. Switch to another one first/, + ) + await assert.rejects( + createCli(dependencies).start(['--remove-workspace', 'nope']), + /No saved workspace named "nope"\. See them with --list-workspaces\./, + ) +}) + +test('CLI lists a workspace saved before names existed under its folder name', async () => { + const { dependencies, calls } = createDependencies() + + await createCli(dependencies).start(['--list-workspaces']) + assert.deepEqual(calls.logs, [[` workspace ${WORKSPACE} (current)`]]) + + const none = createDependencies({ + config: { readWorkspaceConfig: async () => null }, + }) + + await createCli(none.dependencies).start(['--list-workspaces']) + assert.match(none.calls.logs[0][0], /No saved workspaces yet/) +}) + +test('checkWorkspaceName refuses names that read as paths or are taken', () => { + const saved = { work: WORK } + + assert.equal(checkWorkspaceName('personal', saved), true) + for (const name of ['a/b', String.raw`a\b`, '.hidden', '~home']) { + assert.match(checkWorkspaceName(name, saved), /cannot contain/) + } + assert.match(checkWorkspaceName('WORK', saved), /"work" already names/) +}) + +test('CLI asks for the arguments of a script that needs them, showing its command', async () => { + const project = projectFixtures()[0] + const packages = { + name: 'packages', + command: 'yarn workspaces foreach -A', + needsArguments: true, + } + const asked = [] + let scriptMenus = 0 + const runs = [] + + const { dependencies, calls } = createDependencies({ + workspace: { + getProjects: async () => [project], + getScripts: async () => [packages], + }, + commands: { + runCommand: async (...args) => { + runs.push(args) + return { code: 0 } + }, + }, + prompts: { + chooseProject: async () => (scriptMenus === 0 ? project : null), + chooseScript: async () => + scriptMenus++ === 0 ? { script: packages, withArguments: true } : null, + askForArguments: async (name, options) => { + asked.push([name, options]) + return ['run', 'test'] + }, + waitAfterCommand: async () => false, + }, + }) + + await createCli(dependencies).run() + + assert.deepEqual(asked, [['packages', { required: true }]]) + assert.match( + loggedText(calls), + /packages runs: yarn workspaces foreach -A /, + ) + assert.deepEqual(runs[0].slice(0, 2), ['packages', project.directory]) + assert.deepEqual(runs[0][2].args, ['run', 'test']) +}) + +test('CLI does not run a script that needs arguments directly without any', async () => { + const { dependencies, runs } = directDependencies({ + workspace: { + getScripts: async () => [ + { + name: 'packages', + command: 'yarn workspaces foreach -A', + needsArguments: true, + }, + ], + }, + }) + + await assert.rejects( + createCli(dependencies).start(['web', 'packages']), + /"packages" cannot run without arguments \(it runs: yarn workspaces foreach -A\)\. Add them after --, for example: dws web packages -- /, + ) + assert.deepEqual(runs, []) + + assert.equal( + await createCli(dependencies).start(['web', 'packages', '--', 'run', 'x']), + 0, + ) +}) + +test('CLI shows only the script count on a monorepo root entry', async () => { + let options + const { dependencies, shop } = monorepoDependencies({ + prompts: { + chooseProject: async (projects, given) => { + options = given + return null + }, + }, + }) + + await createCli(dependencies).run() + + assert.deepEqual(await options.details(shop, { root: true }), { + detail: '1 script', + }) +}) diff --git a/test/config.test.js b/test/config.test.js index 9b30792..d118e30 100644 --- a/test/config.test.js +++ b/test/config.test.js @@ -17,11 +17,15 @@ import { getConfigPaths, migrateLegacyConfig, readColorSetting, + readDepthSetting, readMouseSetting, + readSavedWorkspaces, readWorkspaceConfig, resetWorkspaceConfig, saveColorSetting, + saveDepthSetting, saveMouseSetting, + saveSavedWorkspaces, saveWorkspaceConfig, } from '../lib/config.js' @@ -385,3 +389,64 @@ test('saveColorSetting saves the colour and keeps the other settings', async () } }) }) + +test('saveDepthSetting saves the depth, and readDepthSetting checks it', async () => { + await withTempHome(async home => { + const { directory, file } = pathsIn(home) + + assert.equal(await readDepthSetting(file), 1) + + await saveWorkspaceConfig('/projects', file) + await saveDepthSetting(2, file) + + assert.deepEqual(JSON.parse(await readFile(file, 'utf8')), { + workspace: '/projects', + depth: 2, + }) + assert.equal(await readDepthSetting(file), 2) + + await mkdir(directory, { recursive: true }) + + for (const depth of [0, 4, 1.5, '2', null]) { + await writeFile(file, JSON.stringify({ depth }), 'utf8') + assert.equal(await readDepthSetting(file), 1, String(depth)) + } + + await writeFile(file, '{ not json', 'utf8') + assert.equal(await readDepthSetting(file), 1) + }) +}) + +test('saveSavedWorkspaces saves the names, and readSavedWorkspaces checks them', async () => { + await withTempHome(async home => { + const { directory, file } = pathsIn(home) + + assert.deepEqual(await readSavedWorkspaces(file), {}) + + await saveWorkspaceConfig('/work', file) + await saveSavedWorkspaces({ work: '/work', personal: '/me' }, file) + + assert.deepEqual(JSON.parse(await readFile(file, 'utf8')), { + workspace: '/work', + workspaces: { work: '/work', personal: '/me' }, + }) + assert.deepEqual(await readSavedWorkspaces(file), { + work: '/work', + personal: '/me', + }) + + await mkdir(directory, { recursive: true }) + + for (const workspaces of [['/work'], 'work', null]) { + await writeFile(file, JSON.stringify({ workspaces }), 'utf8') + assert.deepEqual(await readSavedWorkspaces(file), {}) + } + + await writeFile( + file, + JSON.stringify({ workspaces: { ok: '/ok', ' ': '/x', bad: 3, no: '' } }), + 'utf8', + ) + assert.deepEqual(await readSavedWorkspaces(file), { ok: '/ok' }) + }) +}) diff --git a/test/list.test.js b/test/list.test.js index e25e641..2000b57 100644 --- a/test/list.test.js +++ b/test/list.test.js @@ -504,6 +504,33 @@ test('items load their details once, when first drawn', async () => { assert.equal(await result, 9) }) +test('a loaded detail keeps its end, such as the Git branch', async () => { + const terminal = createTerminal() + const result = terminal.select({ + message: 'Pick', + items: [ + { + label: 'api', + value: 'api', + load: async () => ({ + detail: '2 scripts', + detailEnd: [[' · main', 'green']], + hint: 'npm', + }), + }, + ], + }) + + await new Promise(resolve => setImmediate(resolve)) + assert.equal( + terminal.screen()[2], + aligned(' ❯ api 2 scripts · main', 'npm'), + ) + + terminal.type(KEYS.enter) + assert.equal(await result, 'api') +}) + test('details that arrive after the list closes are not drawn', async () => { const terminal = createTerminal() let finish @@ -1633,3 +1660,124 @@ test('row buttons are divided by a line in the faint accent', async () => { terminal.type(KEYS.enter) await result }) + +// A monorepo with its root and two packages, next to an ordinary project. +function treeItems() { + const root = { label: 'root', value: 'shop' } + const api = { label: 'packages/api', value: 'shop/api' } + const ui = { label: 'packages/ui', value: 'shop/ui' } + + return [ + { label: 'shop', value: 'shop', children: [root, api, ui] }, + { label: 'web', value: 'web' }, + ] +} + +test('Enter on an item with children opens or closes it, and ← closes it', async () => { + const terminal = createTerminal() + const result = terminal.select({ + message: 'Pick', + items: treeItems(), + enter: 'open', + }) + + assert.deepEqual(terminal.screen().slice(2, 4), [' ❯ ▸ shop', ' web']) + assert.match(terminal.screen().at(-1), /enter expand/) + + terminal.type(KEYS.enter) + + assert.deepEqual(terminal.screen().slice(2, 7), [ + ' ❯ ▾ shop', + ' ├ root', + ' ├ packages/api', + ' └ packages/ui', + ' web', + ]) + assert.match(terminal.screen().at(-1), /enter collapse/) + + terminal.type(KEYS.enter) + assert.deepEqual(terminal.screen().slice(2, 4), [' ❯ ▸ shop', ' web']) + + // → opens it too; ← on a child closes its parent and selects it. + terminal.type(KEYS.right, KEYS.down, KEYS.down) + assert.equal(terminal.screen()[4], ' ❯ ├ packages/api') + assert.match(terminal.screen().at(-1), /enter open · ← collapse/) + + terminal.type(KEYS.left) + assert.deepEqual(terminal.screen().slice(2, 4), [' ❯ ▸ shop', ' web']) + + terminal.type(KEYS.right, KEYS.down, KEYS.down, KEYS.enter) + assert.equal(await result, 'shop/api') + // The summary names the child with its parent. + assert.match(terminal.written, /Pick {2}shop › packages\/api/) +}) + +test('a search looks through every child, each value once', async () => { + const terminal = createTerminal() + const result = terminal.select({ + message: 'Pick', + // A recent copy of a child is not shown twice. + items: [{ label: 'shop/api', value: 'shop/api' }, ...treeItems()], + }) + + terminal.type('u', 'i') + + assert.deepEqual(terminal.screen().slice(2, 3), [' ❯ shop › packages/ui']) + + terminal.type(KEYS.backspace, KEYS.backspace, 'a', 'p', 'i') + + const lines = terminal + .screen() + .slice(2) + .filter(line => line.includes('api')) + + assert.equal(lines.length, 1, lines.join('\n')) + + // ← and → do nothing to the tree while searching. + terminal.type(KEYS.left, KEYS.enter) + assert.equal(await result, 'shop/api') +}) + +test('Enter on a parent found by a search clears it and opens the parent', async () => { + const terminal = createTerminal() + const result = terminal.select({ message: 'Pick', items: treeItems() }) + + terminal.type('s', 'h', 'o', 'p') + assert.equal(terminal.screen()[2], ' ❯ shop') + + terminal.type(KEYS.enter) + assert.deepEqual(terminal.screen().slice(2, 4), [ + ' ❯ ▾ shop', + ' ├ root', + ]) + + terminal.type(KEYS.down, KEYS.enter) + assert.equal(await result, 'shop') +}) + +test('the default value opens its parent, and a click opens or closes it', async () => { + const terminal = createTerminal() + const result = terminal.select({ + message: 'Pick', + items: treeItems(), + // Both the parent's and its root child's value: the child is selected. + default: 'shop', + mouse: true, + fullscreen: true, + clickOpens: true, + }) + + // The list is drawn from row 1: the message, then shop on row 3. + assert.equal(terminal.screen()[3], ' ❯ ├ root') + + // A click on the ▸ or on the name closes and opens it. + terminal.click(3, 5) + assert.deepEqual(terminal.screen().slice(2, 4), [' ❯ ▸ shop', ' web']) + + terminal.click(3, 9) + assert.equal(terminal.screen()[4], ' ├ packages/api') + + // A child is chosen with one click. + terminal.click(5, 12) + assert.equal(await result, 'shop/api') +}) diff --git a/test/prompts.test.js b/test/prompts.test.js index 8fc1b98..fa93196 100644 --- a/test/prompts.test.js +++ b/test/prompts.test.js @@ -530,3 +530,196 @@ test('askForArguments returns null on Escape, to go back', async () => { assert.equal(await answer, null) assert.equal(keys.listenerCount('keypress'), 0) }) + +test('chooseProject expands a monorepo into its packages', async () => { + const shop = { name: 'shop', directory: '/projects/shop', workspaces: ['*'] } + const web = { name: 'web', directory: '/projects/web' } + const api = { + name: 'shop/packages/api', + path: 'packages/api', + directory: '/projects/shop/packages/api', + monorepo: shop, + } + const { calls, prompts } = createPromptMocks({ select: api }) + + const result = await prompts.chooseProject([shop, web], { + recent: [api], + packages: project => (project === shop ? [api] : undefined), + default: api, + }) + + assert.equal(result, api) + assert.deepEqual(calls.select[0].items, [ + { separator: 'Recent' }, + // In "Recent", a package has its full name and no packages of its own. + { label: 'shop/packages/api', value: api }, + { separator: 'All projects' }, + { + label: 'shop', + value: shop, + // root opens the monorepo's own scripts. + children: [ + { label: 'root', value: shop }, + { label: 'api', value: api }, + ], + }, + { label: 'web', value: web }, + ]) + assert.equal(calls.select[0].default, api) +}) + +test('chooseProject keeps the whole path of packages with the same folder name', async () => { + const shop = { name: 'shop', directory: '/projects/shop', workspaces: ['*'] } + const pkg = path => ({ + name: `shop/${path}`, + path, + directory: `/projects/shop/${path}`, + monorepo: shop, + }) + const packages = [pkg('apps/web'), pkg('packages/web'), pkg('packages/ui')] + const { calls, prompts } = createPromptMocks({ select: null }) + + await prompts.chooseProject([shop], { packages: () => packages }) + + assert.deepEqual( + calls.select[0].items[0].children.map(child => child.label), + ['root', 'apps/web', 'packages/web', 'ui'], + ) +}) + +test('chooseWorkspace lists the saved workspaces first, by name', async () => { + const { calls, prompts } = createPromptMocks({ select: '/work' }) + + await prompts.chooseWorkspace(['/home/dev'], { + saved: [ + { name: 'work', directory: '/work', missing: false }, + { name: 'old', directory: '/gone', missing: true }, + ], + current: '/work', + cancellable: true, + }) + + const { items } = calls.select[0] + + assert.deepEqual(items.slice(0, 4), [ + { separator: 'Saved' }, + { label: 'work', value: '/work', detail: '/work', hint: 'current' }, + { label: 'old', value: '/gone', detail: '/gone', disabled: 'not found' }, + { separator: 'Suggested' }, + ]) + assert.equal(items[4].value, '/home/dev') + assert.equal(calls.select[0].default, '/work') + + // Without suggestions, no group titles. + await prompts.chooseWorkspace([], { + saved: [{ name: 'work', directory: '/work', missing: false }], + }) + assert.deepEqual( + calls.select[1].items.map(item => item.label), + ['work', '… Enter another path'], + ) +}) + +test('askForWorkspaceName suggests a name, trims it, and Escape returns null', async () => { + const { calls, prompts } = createPromptMocks({ input: ' personal ' }) + const validate = () => true + + assert.equal(await prompts.askForWorkspaceName('dev', validate), 'personal') + assert.equal(calls.input[0].message, 'Name for this workspace') + assert.equal(calls.input[0].default, 'dev') + assert.equal(calls.input[0].validate, validate) + + const keys = new EventEmitter() + const escaping = createPrompts({ input: abortableInput(keys), keys }) + const answer = escaping.askForWorkspaceName('dev', validate) + + keys.emit('keypress', undefined, { name: 'escape' }) + assert.equal(await answer, null) +}) + +test('chooseProject keeps the packages of a recent monorepo', async () => { + const shop = { name: 'shop', directory: '/projects/shop', workspaces: ['*'] } + const web = { name: 'web', directory: '/projects/web' } + const api = { name: 'shop/api', path: 'api', directory: '/projects/shop/api' } + const { calls, prompts } = createPromptMocks({ select: null }) + + await prompts.chooseProject([shop, web], { + recent: [shop], + packages: project => (project === shop ? [api] : undefined), + }) + + assert.deepEqual(calls.select[0].items, [ + { separator: 'Recent' }, + { + label: 'shop', + value: shop, + children: [ + { label: 'root', value: shop }, + { label: 'api', value: api }, + ], + }, + { separator: 'All projects' }, + { label: 'web', value: web }, + ]) +}) + +test('chooseScript asks for the arguments of a script that needs them', async () => { + const packages = { + name: 'packages', + command: 'yarn workspaces foreach -A', + needsArguments: true, + } + const { calls, prompts } = createPromptMocks({ select: packages }) + + assert.deepEqual(await prompts.chooseScript([packages]), { + script: packages, + withArguments: true, + }) + + const { items, rowButtons } = calls.select[0] + + assert.equal(items[0].hint, 'needs arguments') + assert.deepEqual(rowButtons[0].value(packages), { + script: packages, + withArguments: true, + }) + + // "last run" is the tag that wins. + await prompts.chooseScript([packages], { lastScript: 'packages' }) + assert.equal(calls.select[1].items[0].hint, 'last run') +}) + +test('askForArguments refuses an empty answer when arguments are required', async () => { + const { calls, prompts } = createPromptMocks({ input: 'run test' }) + + assert.deepEqual( + await prompts.askForArguments('packages', { required: true }), + ['run', 'test'], + ) + assert.equal( + calls.input[0].validate(' '), + 'packages cannot run without arguments.', + ) + assert.equal(calls.input[0].validate('run test'), true) + + await prompts.askForArguments('dev') + assert.equal(calls.input[1].validate(''), true) +}) + +test('the root entry of a monorepo loads its own details', async () => { + const shop = { name: 'shop', directory: '/projects/shop' } + const api = { name: 'shop/api', path: 'api', directory: '/projects/shop/api' } + const asked = [] + const { calls, prompts } = createPromptMocks({ select: null }) + + await prompts.chooseProject([shop], { + packages: () => [api], + details: async (project, options) => { + asked.push([project, options]) + return {} + }, + }) + await calls.select[0].items[0].children[0].load() + + assert.deepEqual(asked, [[shop, { root: true }]]) +}) diff --git a/test/script-arguments.test.js b/test/script-arguments.test.js new file mode 100644 index 0000000..043440a --- /dev/null +++ b/test/script-arguments.test.js @@ -0,0 +1,49 @@ +import test from 'node:test' +import assert from 'node:assert/strict' + +import { needsArguments } from '../lib/script-arguments.js' + +test('needsArguments recognises helpers that only take the rest of a command', () => { + for (const command of [ + "yarn workspaces foreach --all --include '@modulane/*' --topological-dev --verbose", + 'yarn workspaces foreach -A -j 4', + 'yarn workspace @shop/api', + 'pnpm -r', + 'pnpm --filter "./packages/**"', + 'npm -ws', + 'npm --workspace packages/api', + 'npm exec', + 'npx', + 'bun --filter "*"', + 'turbo run --filter web', + 'lerna exec --scope api', + 'yarn build && yarn workspaces foreach -A', + ]) { + assert.equal(needsArguments(command), true, command) + } +}) + +test('needsArguments lets every other script run on its own', () => { + for (const command of [ + 'yarn packages run check', + 'yarn workspaces foreach -A run build', + 'yarn workspace @shop/api run dev', + 'yarn lint', + 'yarn', + 'pnpm -r build', + 'pnpm --filter web dev', + 'pnpm', + 'pnpm --version', + 'npm run build --workspaces', + 'npm exec eslint', + 'npx eslint .', + 'bun --filter "*" build', + 'turbo run build', + 'lerna run test', + 'eslint .', + 'yarn workspaces foreach -A | tee log.txt', + 'node -e "unclosed', + ]) { + assert.equal(needsArguments(command), false, command) + } +}) diff --git a/test/ui.test.js b/test/ui.test.js index ff1aa54..c95944b 100644 --- a/test/ui.test.js +++ b/test/ui.test.js @@ -117,6 +117,13 @@ test('headerLines draws the workspace folder and path in a box', () => { ]) }) +test('headerLines starts the breadcrumb with a saved workspace name', () => { + assert.equal( + header({ workspace: '/projects', name: 'personal' }, 40)[0], + ' ╭─ ◆ personal ───────────────────────╮', + ) +}) + test('headerLines shows the breadcrumb and the tag in the top border', () => { const [top] = header( { workspace: '/projects', crumbs: ['web-app'], tag: 'npm · default' }, diff --git a/test/workspace.test.js b/test/workspace.test.js index 1ce3de6..76a8544 100644 --- a/test/workspace.test.js +++ b/test/workspace.test.js @@ -6,10 +6,13 @@ import path from 'node:path' import { isDirectory, + getPackages, getProjects, getScripts, normalizePathInput, + parsePnpmWorkspace, readGitBranch, + readWorkspacePatterns, resolveDirectoryInput, suggestWorkspaces, } from '../lib/workspace.js' @@ -496,3 +499,273 @@ test('suggestWorkspaces skips a drive that does not answer in time', async () => assert.deepEqual(result, ['C:\\dev']) }) + +// Create each folder, with a package.json for the paths that end in /. +async function createTree(root, paths) { + for (const entry of paths) { + const folder = path.join(root, ...entry.split('/').filter(Boolean)) + + await mkdir(folder, { recursive: true }) + + if (entry.endsWith('/')) { + await writeFile(path.join(folder, 'package.json'), '{}', 'utf8') + } + } +} + +test('getProjects searches nested folders down to the depth', async () => { + await withTempDirectory(async directory => { + await createTree(directory, [ + 'web/', + 'web/packages/ui/', + 'apps/site/', + 'apps/notes', + 'clients/acme/web/', + 'clients/acme/api/', + 'clients/beta/site/', + 'clients/empty', + 'clients/node_modules/lib/', + 'clients/.cache/tool/', + 'docs/images', + 'deep/a/b/c/', + ]) + + const names = async depth => + (await getProjects(directory, { depth })).map(project => [ + project.name, + project.hasPackageJson, + ]) + + // Depth 1, the default, lists the workspace's own folders only. + assert.deepEqual(await names(undefined), [ + ['web', true], + ['apps', false], + ['clients', false], + ['deep', false], + ['docs', false], + ]) + + // A folder is replaced by what it holds only when that includes a + // project; a folder with a package.json is never searched. + assert.deepEqual(await names(2), [ + ['apps/site', true], + ['web', true], + ['apps/notes', false], + ['clients', false], + ['deep', false], + ['docs', false], + ]) + + // node_modules and dot-folders are never entered, and deep/a/b/c is + // below the deepest level. + assert.deepEqual(await names(3), [ + ['apps/site', true], + ['clients/acme/api', true], + ['clients/acme/web', true], + ['clients/beta/site', true], + ['web', true], + ['apps/notes', false], + ['clients/empty', false], + ['deep', false], + ['docs', false], + ]) + + // The depth is kept between 1 and 3. + assert.deepEqual(await names(9), await names(3)) + assert.deepEqual(await names(0), await names(1)) + + const projects = await getProjects(directory, { depth: 3 }) + + assert.equal( + projects.find(project => project.name === 'clients/acme/api').directory, + path.join(directory, 'clients', 'acme', 'api'), + ) + }) +}) + +test('parsePnpmWorkspace reads the packages list in either style', () => { + assert.deepEqual( + parsePnpmWorkspace( + [ + '# the workspace', + 'packages:', + " - 'packages/*'", + ' - "apps/**"', + '', + ' # tools too', + ' - tools/cli # the CLI', + " - '!**/test/**'", + " - 'docs' # it's the site", + 'catalog:', + ' - not-a-package', + ].join('\r\n'), + ), + ['packages/*', 'apps/**', 'tools/cli', '!**/test/**', 'docs'], + ) + assert.deepEqual(parsePnpmWorkspace('packages: [\'a/*\', "b"]\n'), [ + 'a/*', + 'b', + ]) + assert.deepEqual( + parsePnpmWorkspace( + 'packages: [\n \'apps/*\', # the apps\n "libs/*",\n]\ncatalog:\n a: b\n', + ), + ['apps/*', 'libs/*'], + ) + assert.deepEqual( + parsePnpmWorkspace('packages:\n- apps/*\n- libs/*\ncatalog:\n- no\n'), + ['apps/*', 'libs/*'], + ) + assert.deepEqual(parsePnpmWorkspace('catalog:\n react: ^19\n'), []) +}) + +test('readWorkspacePatterns finds the npm, Yarn and pnpm workspaces', async () => { + await withTempDirectory(async directory => { + const project = async (name, files) => { + const folder = path.join(directory, name) + + await mkdir(folder) + + for (const [file, content] of Object.entries(files)) { + await writeFile(path.join(folder, file), content, 'utf8') + } + + return readWorkspacePatterns(folder) + } + + assert.deepEqual( + await project('npm', { + 'package.json': JSON.stringify({ workspaces: ['packages/*', 3] }), + }), + ['packages/*'], + ) + assert.deepEqual( + await project('yarn', { + 'package.json': JSON.stringify({ + workspaces: { packages: ['apps/*'], nohoist: ['**/react'] }, + }), + }), + ['apps/*'], + ) + assert.deepEqual( + await project('pnpm', { + 'package.json': '{}', + 'pnpm-workspace.yaml': 'packages:\n - libs/*\n', + }), + ['libs/*'], + ) + assert.equal( + await project('plain', { 'package.json': '{ "name": "plain" }' }), + null, + ) + assert.equal(await project('broken', { 'package.json': '{' }), null) + }) +}) + +test('getProjects marks monorepos with their workspace patterns', async () => { + await withTempDirectory(async directory => { + await createTree(directory, ['shop/', 'web/']) + await writeFile( + path.join(directory, 'shop', 'package.json'), + JSON.stringify({ workspaces: ['packages/*'] }), + ) + + assert.deepEqual(await getProjects(directory), [ + { + name: 'shop', + directory: path.join(directory, 'shop'), + hasPackageJson: true, + workspaces: ['packages/*'], + }, + { + name: 'web', + directory: path.join(directory, 'web'), + hasPackageJson: true, + }, + ]) + }) +}) + +test('getPackages expands the workspace patterns into packages', async () => { + await withTempDirectory(async directory => { + await createTree(directory, [ + 'packages/api/', + 'packages/ui/', + 'packages/notes', + 'packages/node_modules/dependency/', + 'apps/web/', + 'apps/mobile/ios/', + 'apps/mobile/ios/test/', + 'tools/cli/', + ]) + await writeFile( + path.join(directory, 'packages', 'api', 'package.json'), + JSON.stringify({ name: '@shop/api' }), + ) + + const packages = await getPackages(directory, [ + './packages/*/', + 'apps/**', + 'tools/cli', + 'missing/*', + '.', + '!**/test', + ]) + + assert.deepEqual( + packages.map(({ path: folder, packageName }) => [folder, packageName]), + [ + ['apps/mobile/ios', undefined], + ['apps/web', undefined], + ['packages/api', '@shop/api'], + ['packages/ui', undefined], + ['tools/cli', undefined], + ], + ) + assert.equal(packages[2].directory, path.join(directory, 'packages', 'api')) + }) +}) + +test('getPackages leaves out a folder and what it holds with a trailing /**', async () => { + await withTempDirectory(async directory => { + await createTree(directory, [ + 'packages/api/', + 'packages/test/', + 'packages/test/fixture/', + 'packages/testing/', + ]) + + const packages = await getPackages(directory, [ + 'packages/**', + '!**/test/**', + ]) + + assert.deepEqual( + packages.map(({ path: folder }) => folder), + ['packages/api', 'packages/testing'], + ) + }) +}) + +test('getScripts marks scripts that cannot run without arguments', async () => { + await withTempDirectory(async directory => { + await writeFile( + path.join(directory, 'package.json'), + JSON.stringify({ + scripts: { + test: 'yarn packages run test', + packages: 'yarn workspaces foreach --all --verbose', + }, + }), + ) + + assert.deepEqual(await getScripts(directory), [ + { name: 'test', command: 'yarn packages run test' }, + { + name: 'packages', + command: 'yarn workspaces foreach --all --verbose', + needsArguments: true, + }, + ]) + }) +})