From 1153124f928737214e3ebce760f6fe9294158c1f Mon Sep 17 00:00:00 2001 From: versnic <37933264+versnic@users.noreply.github.com> Date: Tue, 10 Nov 2026 23:36:44 +0100 Subject: [PATCH 01/17] fix: show the git branch loaded for each project --- lib/list.js | 8 +++++--- test/list.test.js | 27 +++++++++++++++++++++++++++ 2 files changed, 32 insertions(+), 3 deletions(-) diff --git a/lib/list.js b/lib/list.js index 06f76f2..166eddf 100644 --- a/lib/list.js +++ b/lib/list.js @@ -18,8 +18,9 @@ // so the screen can show the effect of a choice, such as an accent colour, // before it is made. Disabled items are shown dimmed and skipped by the cursor; // separators are hidden while searching. `load` fills in an item lazily: it -// is called once, the first time the item is drawn, and the { detail, hint } -// its promise resolves with are shown from then on (a rejection is ignored), +// is called once, the first time the item is drawn, and the { detail, +// detailEnd, hint } its promise resolves with are shown from then on (a +// rejection is ignored), // so a long list only reads what scrolls into view. Actions are buttons, never items, so // searching never picks one: // @@ -693,9 +694,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?.() diff --git a/test/list.test.js b/test/list.test.js index 6228d18..daa6f52 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 From 80ca49c23b81e820c2e76afa5d6190b8a6f9b0eb Mon Sep 17 00:00:00 2001 From: versnic <37933264+versnic@users.noreply.github.com> Date: Tue, 10 Nov 2026 23:41:08 +0100 Subject: [PATCH 02/17] feat: search nested folders for projects --- README.md | 36 ++++++++++-------- ROADMAP.md | 2 +- lib/args.js | 16 +++++++- lib/cli.js | 54 +++++++++++++++++++++------ lib/config.js | 32 ++++++++++++---- lib/workspace.js | 83 ++++++++++++++++++++++++++++++------------ test/args.test.js | 24 ++++++++++++ test/benchmark.test.js | 48 ++++++++++++++++++++++++ test/cli.test.js | 59 ++++++++++++++++++++++++++++++ test/config.test.js | 29 +++++++++++++++ test/workspace.test.js | 83 ++++++++++++++++++++++++++++++++++++++++++ 11 files changed, 405 insertions(+), 61 deletions(-) create mode 100644 test/benchmark.test.js diff --git a/README.md b/README.md index ce722ea..3721f83 100644 --- a/README.md +++ b/README.md @@ -154,7 +154,9 @@ To pass arguments to a script, press → on it, or click its **… run with args ### 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. @@ -194,7 +196,7 @@ 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. +- 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. - Any script in `package.json` can be run by name, including `pre` and `post` hooks. - 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 +207,21 @@ 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 `` 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)) | +| `--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,6 +254,7 @@ 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. - 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. diff --git a/ROADMAP.md b/ROADMAP.md index 492f68f..a846175 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -182,7 +182,7 @@ Every screen checked in the terminals people use, on their own schedule: they ne ## Bigger workspaces - [ ] **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`. +- [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). - [ ] **Multiple named workspaces:** save several workspaces (for example `work` and `personal`), switch between them from the menu, and choose one with `--workspace `. **Done when:** a 200-project workspace with depth 2 lists in under 500 ms on a typical SSD, measured in a benchmark test. diff --git a/lib/args.js b/lib/args.js index 8894ffd..576ae1f 100644 --- a/lib/args.js +++ b/lib/args.js @@ -10,7 +10,8 @@ // here. It colours headings, commands and placeholders through the given // function (ui.color), commands in the accent, so NO_COLOR, FORCE_COLOR, // non-TTY output and the chosen accent are respected; with no function it -// returns plain text. --set-color accepts the names in ui.ACCENTS. +// returns plain text. --set-color accepts the names in ui.ACCENTS, and +// --set-depth 1, 2 or 3, kept as text (cli.js turns it into a number). // // splitArguments() splits arguments typed at the "Run with arguments…" prompt // into a list, honouring single and double quotes. No shell is involved, so @@ -47,6 +48,9 @@ export function formatHelp(color = value => String(value)) { ${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 @@ -83,6 +87,7 @@ export function parseCliArgs(args) { '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' }, @@ -128,6 +133,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 ec95a00..4c29842 100644 --- a/lib/cli.js +++ b/lib/cli.js @@ -2,12 +2,13 @@ // // start() first applies the saved accent colour (ui.setAccent), then // handles one-shot options (help, formatted with ui.color, version, aliases, -// the mouse and colour settings, reset, clearing the history) and otherwise -// runs the main loop: load or configure the workspace, list its projects -// (recently used ones first, each with its script count, Git branch and -// package manager: projectDetails(); the branch is coloured, main, master -// and trunk in one colour and any other branch in another), list a project's scripts with its -// detected package manager, run the chosen script with that tool, optionally +// the mouse, colour and depth settings, reset, clearing the history) and +// otherwise runs the main loop: load or configure the workspace, list its +// projects (found down to the saved search depth: --set-depth, read once +// per run; recently used ones first, each with its script count, Git branch +// and package manager: projectDetails(); the branch is coloured, main, +// master and trunk in one colour and any other branch in another), list a +// project's scripts with its detected package manager, run the chosen script with that tool, optionally // with arguments, then offer to run it again. Every menu shows the header // box from ui.js, with the project as a breadcrumb and its package manager // as the tag; empty and error states are shown in the box's screen, as the @@ -83,10 +84,12 @@ import { getConfigPaths, migrateLegacyConfig, readColorSetting, + readDepthSetting, readMouseSetting, readWorkspaceConfig, resetWorkspaceConfig, saveColorSetting, + saveDepthSetting, saveMouseSetting, saveWorkspaceConfig, } from './config.js' @@ -111,6 +114,7 @@ import { } from './terminal.js' import { + MAX_DEPTH, getProjects, getScripts, isDirectory, @@ -222,13 +226,16 @@ 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) { +// 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 /. +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), ] @@ -237,7 +244,7 @@ export function findProject(projects, name, root) { 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( @@ -260,10 +267,12 @@ const defaultDependencies = { getConfigPaths, migrateLegacyConfig, readColorSetting, + readDepthSetting, readMouseSetting, readWorkspaceConfig, resetWorkspaceConfig, saveColorSetting, + saveDepthSetting, saveMouseSetting, saveWorkspaceConfig, }, @@ -348,6 +357,8 @@ export function createCli(overrides = {}) { const stateFile = getStatePath(configFile, { custom: configPaths.custom }) let root = '' + // 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. const details = new Map() @@ -427,7 +438,7 @@ export function createCli(overrides = {}) { // 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 @@ -616,7 +627,7 @@ export function createCli(overrides = {}) { 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, @@ -848,6 +859,7 @@ export function createCli(overrides = {}) { } history = await historyStore.readState(stateFile) + depth = await config.readDepthSetting(configFile, MAX_DEPTH) if (direct) { if (options.workspace === undefined) { @@ -978,6 +990,21 @@ 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 deleteAlias(name) { await aliases.removeAlias(name) @@ -1007,6 +1034,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 6a39ea7..032e61e 100644 --- a/lib/config.js +++ b/lib/config.js @@ -9,13 +9,15 @@ // automatically by migrateLegacyConfig(). // // The file holds the workspace, the accent colour chosen on the first run, -// and, optionally, whether menus use the mouse: -// `{ "workspace": "", "color": "cyan", "mouse": false }`. -// readMouseSetting() is false only for `"mouse": false`, and -// readColorSetting() returns the colour's name or null; neither ever fails: -// a problem with the file is reported by readWorkspaceConfig(). -// saveMouseSetting() and saveColorSetting() store them, also for --set-mouse -// and --set-color. Saving any setting keeps the other ones; a file without a +// and, optionally, whether menus use the mouse and how deep projects are +// searched for: `{ "workspace": "", "color": "cyan", "mouse": false, +// "depth": 2 }`. readMouseSetting() is false only for `"mouse": false`, +// readColorSetting() returns the colour's name or null, and +// readDepthSetting() a depth from 1 to 3 (1 by default); none of them ever +// fails: a problem with the file is reported by readWorkspaceConfig(). +// saveMouseSetting(), saveColorSetting() and saveDepthSetting() store them, +// also for --set-mouse, --set-color and --set-depth. Saving any setting +// keeps the other ones; a file without a // workspace counts as no workspace configured yet. A file // saved with a UTF-8 byte order mark, as some editors do, is read normally. // Used by cli.js. @@ -209,6 +211,22 @@ async function saveSetting(name, value, 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/workspace.js b/lib/workspace.js index 4ec8453..331d1d0 100644 --- a/lib/workspace.js +++ b/lib/workspace.js @@ -1,10 +1,14 @@ // Reading the workspace from disk. // -// getProjects() lists the workspace's immediate subfolders, and links to -// folders (symbolic links, and junctions on Windows), as projects, leaving -// out folders that are never projects (dot-folders such as .git, and -// node_modules). Each project records whether it has a package.json; those -// without one are sorted after the others so the menu can show them dimmed. +// getProjects() lists the workspace's subfolders, and links to folders +// (symbolic links, and junctions on Windows), as projects, leaving out +// folders that are never projects (dot-folders such as .git, and +// node_modules). With `{ depth }` (DEFAULT_DEPTH 1 to MAX_DEPTH 3), it also +// looks inside folders without a package.json, for workspaces organised as +// `clients/acme/web`: it stops at every folder with a package.json, and +// names the projects it finds deeper by their path, with /. Each project +// records whether it has a package.json; those without one are sorted after +// the others so the menu can show them dimmed. // getScripts() reads the scripts from a project's package.json, with clear // errors for unreadable or invalid files (a leading byte order mark is // ignored, as npm does), and attaches pre/post hooks to their main script @@ -240,35 +244,66 @@ 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 }) +// How deep getProjects() looks for projects: 1 lists the immediate +// subfolders only. +export const DEFAULT_DEPTH = 1 +export const MAX_DEPTH = 3 - const projects = await Promise.all( +// 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(root, entry))) return null + if (!(await isFolder(folder, entry))) return [] - const directory = path.join(root, entry.name) + const directory = path.join(folder, entry.name) + // Always with /, so a name reads the same on every system. + const name = prefix + entry.name - return { - name: entry.name, - directory, - hasPackageJson: await hasPackageJson(directory), + if (await hasPackageJson(directory)) { + return [{ name, directory, hasPackageJson: true }] } + + 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 projects - .filter(project => project !== null) - .sort( - (a, b) => - Number(b.hasPackageJson) - Number(a.hasPackageJson) || - compareNames(a.name, b.name), - ) + 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`, diff --git a/test/args.test.js b/test/args.test.js index ae1540d..8ad836d 100644 --- a/test/args.test.js +++ b/test/args.test.js @@ -58,6 +58,7 @@ test('formatHelp documents every option', () => { '--no-mouse', '--set-mouse', '--set-color', + '--set-depth', '--config-path', '--clear-history', '--add-alias', @@ -98,6 +99,9 @@ test('formatHelp defaults to plain text', () => { --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 @@ -206,6 +210,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..0e50af9 100644 --- a/test/cli.test.js +++ b/test/cli.test.js @@ -49,6 +49,7 @@ function createDependencies(overrides = {}) { }), migrateLegacyConfig: async () => null, readColorSetting: async () => 'cyan', + readDepthSetting: async () => 1, readMouseSetting: async () => true, readWorkspaceConfig: async () => WORKSPACE, resetWorkspaceConfig: async () => [], @@ -1323,6 +1324,26 @@ 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('CLI runs a script directly and returns its exit code', async () => { const { dependencies, calls, runs } = directDependencies() @@ -2092,3 +2113,41 @@ 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 }]) +}) diff --git a/test/config.test.js b/test/config.test.js index 9b30792..e584a22 100644 --- a/test/config.test.js +++ b/test/config.test.js @@ -17,10 +17,12 @@ import { getConfigPaths, migrateLegacyConfig, readColorSetting, + readDepthSetting, readMouseSetting, readWorkspaceConfig, resetWorkspaceConfig, saveColorSetting, + saveDepthSetting, saveMouseSetting, saveWorkspaceConfig, } from '../lib/config.js' @@ -385,3 +387,30 @@ 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) + }) +}) diff --git a/test/workspace.test.js b/test/workspace.test.js index 1ce3de6..fcc2393 100644 --- a/test/workspace.test.js +++ b/test/workspace.test.js @@ -496,3 +496,86 @@ 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'), + ) + }) +}) From c65e76e0b0eca5ad62c25fbbc348b6484b51ae8a Mon Sep 17 00:00:00 2001 From: versnic <37933264+versnic@users.noreply.github.com> Date: Tue, 10 Nov 2026 23:49:29 +0100 Subject: [PATCH 03/17] feat: list the packages of monorepos --- README.md | 18 +++- ROADMAP.md | 2 +- lib/cli.js | 116 ++++++++++++++++++--- lib/list.js | 130 ++++++++++++++++++++++-- lib/prompts.js | 27 ++++- lib/workspace.js | 223 ++++++++++++++++++++++++++++++++++++++++- test/cli.test.js | 141 ++++++++++++++++++++++++++ test/list.test.js | 93 +++++++++++++++++ test/prompts.test.js | 33 ++++++ test/workspace.test.js | 135 +++++++++++++++++++++++++ 10 files changed, 887 insertions(+), 31 deletions(-) diff --git a/README.md b/README.md index 3721f83..61fee43 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. @@ -164,6 +164,20 @@ 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`). Press → on it, or click the `▸`, to show its packages under it, and ← to hide them again; Enter or a click on its name opens the scripts of the monorepo itself, as for any project. + +```text + ❯ ▾ shop 3 packages · 2 scripts · main pnpm + apps/web 1 script + packages/api 2 scripts @shop/api + packages/ui 1 script @shop/ui + web 2 scripts · main npm +``` + +Each package is listed by its folder in the monorepo, with its `name` from `package.json` on the right when it differs from the folder name. 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`; they are read once per session. Searching looks through every package, shown or not: typing `ui` finds `shop › packages/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: @@ -196,7 +210,7 @@ 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 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. +- 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. - 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. diff --git a/ROADMAP.md b/ROADMAP.md index a846175..039ded5 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -181,7 +181,7 @@ Every screen checked in the terminals people use, on their own schedule: they ne ## Bigger workspaces -- [ ] **Monorepos:** detect npm, Yarn and pnpm workspaces. A monorepo appears as one project with expandable packages; scripts run in the selected package. +- [x] **Monorepos:** detect npm, Yarn and pnpm workspaces. A monorepo appears as one project with expandable packages; scripts run in the selected package. → or a click on its `▸` shows the 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). - [ ] **Multiple named workspaces:** save several workspaces (for example `work` and `personal`), switch between them from the menu, and choose one with `--workspace `. diff --git a/lib/cli.js b/lib/cli.js index 4c29842..0519311 100644 --- a/lib/cli.js +++ b/lib/cli.js @@ -46,6 +46,14 @@ // The project is found by exact name, then ignoring case, then by unique // prefix (findProject). // +// Monorepos (projects with `workspaces`, see workspace.js) expand in the +// project list into their packages, read once per session (packagesOf()). +// A package is a project named `/`, with `monorepo` set: it +// opens and runs like any project, in its own folder, with the package +// manager detected in its monorepo (toolDirectory()). Packages are in the +// history and in direct mode as projects are; the list selects the last +// project or package opened again when it comes back. +// // Project details are read only for the projects the list shows, and // cached for the session, so a large workspace still opens at once; opening // a project reads its details again the next time the list shows it, as a @@ -115,6 +123,7 @@ import { import { MAX_DEPTH, + getPackages, getProjects, getScripts, isDirectory, @@ -157,11 +166,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. @@ -287,6 +296,7 @@ const defaultDependencies = { isTerminal, }, workspace: { + getPackages, getProjects, detectPackageManager, getScripts, @@ -360,8 +370,10 @@ export function createCli(overrides = {}) { // 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. @@ -597,10 +609,14 @@ 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 no + // branch: its monorepo shows both. + async function readDetails(project) { + const { directory, monorepo } = project const [packageManager, branch] = await Promise.all([ - workspace.detectPackageManager(directory), - workspace.readGitBranch(directory), + workspace.detectPackageManager(toolDirectory(project)), + monorepo ? null : workspace.readGitBranch(directory), ]) let detail @@ -609,12 +625,75 @@ 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 (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 + } + + // 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 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) { @@ -734,7 +813,7 @@ export function createCli(overrides = {}) { // 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 @@ -794,9 +873,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 @@ -888,18 +967,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 diff --git a/lib/list.js b/lib/list.js index 166eddf..a84e375 100644 --- a/lib/list.js +++ b/lib/list.js @@ -10,7 +10,14 @@ // Ctrl+C rejects with an ExitPromptError, as Inquirer's prompts do. // // Items are { label, value, icon, detail, detailEnd, hint, hintStyle, -// disabled, load, style } or { separator }. `style` (a style name from +// disabled, load, style, children } or { separator }. An item with +// `children` (items too, one level deep) can be expanded: a ▸ before its +// label (▾ while open) shows it, → or a click on the ▸ opens it, and ← +// closes it again, also from one of its children, which then selects the +// parent. Its children are drawn indented under it while it is open; the +// parent holding the `default` value starts open. A search looks through +// every child, open or not, showing each with its parent (`shop › api`), +// and each value only once. `style` (a style name from // ui.js) colours the label while the item is not selected; the selected one // is in the accent. `hintStyle` draws the `hint` tag in a style other than // dim, such as the accent for "last run". @@ -399,6 +406,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 = [ @@ -409,18 +430,50 @@ 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 an indent before a child. While searching, + // nothing, except a child's parent: `shop › `. + function leadOf(item) { + const parent = parents.get(item) + + if (parent) return query ? `${parent.label} › ` : ' ' + 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) } @@ -452,14 +505,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() { @@ -565,8 +637,12 @@ export function createList({ // What the list resolves with, and the label its summary shows. function chooseItem(index) { const { item } = rows[index] + const parent = parents.get(item) - return { value: item.value, label: item.label } + return { + value: item.value, + label: parent ? `${parent.label} › ${item.label}` : item.label, + } } function pressRowButton(buttonIndex, rowIndex) { @@ -590,6 +666,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': @@ -639,8 +718,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) } @@ -724,6 +819,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]) @@ -753,7 +856,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) @@ -800,6 +903,15 @@ export function createList({ if (rightButton !== -1) { help.push(`→ ${helpName(rowButtons[rightButton].label)}`) } + + // What the arrows do on the selected parent or child. + const item = focus === 'list' && !query ? rows[cursor]?.item : null + + if (item && (open.has(item) || parents.has(item))) { + help.push('← collapse') + } else if (item?.children?.length) { + help.push('→ expand') + } 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 78684e8..38812f6 100644 --- a/lib/prompts.js +++ b/lib/prompts.js @@ -14,6 +14,10 @@ // click opens a project. With `details` (a function of a project returning a // promise of { detail, hint }), the list loads each project's details as it // comes into view: cli.js passes `12 scripts · main` and the package manager. +// With `packages` (a function of a project returning its packages, as +// projects with a `path` in the monorepo), a monorepo can be expanded in the +// list to show its packages under it (see list.js); a package opens like a +// project. The cursor starts on the `default` project or package, if given. // It returns the project, CHANGE_WORKSPACE for the `⚙ Workspace` button, or // null for `✕ Exit` and Escape. chooseScript() puts // the cursor on the project's last script, tagged "last run" in the accent @@ -238,10 +242,28 @@ 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 in the list expands into its packages, each labelled with + // its path in the monorepo; in "Recent", items have their full name. + const tree = project => { + const children = packages?.(project) ?? [] + + return children.length === 0 + ? item(project) + : { + ...item(project), + children: children.map(child => ({ + ...item(child), + label: child.path, + })), + } + } 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), { @@ -258,6 +280,7 @@ export function createPrompts({ ], escape: { value: null, label: 'exit' }, enter: 'open', + ...(selected && { default: selected }), clickOpens: true, fullscreen: true, ...frame(options), diff --git a/lib/workspace.js b/lib/workspace.js index 331d1d0..967d7a0 100644 --- a/lib/workspace.js +++ b/lib/workspace.js @@ -8,7 +8,14 @@ // `clients/acme/web`: it stops at every folder with a package.json, and // names the projects it finds deeper by their path, with /. Each project // records whether it has a package.json; those without one are sorted after -// the others so the menu can show them dimmed. +// the others so the menu can show them dimmed. A monorepo also has +// `workspaces`: its package folder patterns, from readWorkspacePatterns() +// (the `workspaces` field of package.json for npm, Yarn and Bun, else +// pnpm-workspace.yaml, read by parsePnpmWorkspace()). getPackages() expands +// those patterns (`*`, `**`, and `!` to leave folders out) into the +// monorepo's packages, folders with a package.json named by their path in +// the monorepo (`packages/api`), with the package's own `name` as +// `packageName`. // getScripts() reads the scripts from a project's package.json, with clear // errors for unreadable or invalid files (a leading byte order mark is // ignored, as npm does), and attaches pre/post hooks to their main script @@ -244,6 +251,209 @@ async function isFolder(root, entry) { return entry.isSymbolicLink() && isDirectory(path.join(root, entry.name)) } +// 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)) + + if (start === -1) return [] + + const unquote = value => { + const text = value.trim() + const quoted = /^(['"])(.*)\1$/.exec(text) + + // A comment can follow a value that has no quotes. + return quoted ? quoted[2] : text.replace(/\s+#.*$/, '').trim() + } + const rest = lines[start].replace(/^packages\s*:/, '').trim() + + if (rest.startsWith('[')) { + return rest + .replace(/^\[/, '') + .replace(/\].*$/, '') + .split(',') + .map(unquote) + .filter(Boolean) + } + + const patterns = [] + + for (const line of lines.slice(start + 1)) { + if (!line.trim() || line.trim().startsWith('#')) continue + + 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[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(path.join(root, base), entry))) return [] + + const relative = base ? `${base}/${entry.name}` : entry.name + + return [relative, ...(await foldersUnder(root, relative, levels - 1))] + }), + ) + + 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 { + path: folder, + directory: packageDirectory, + ...(typeof packageName === 'string' && { packageName }), + } + }), + ) + + 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 @@ -268,7 +478,16 @@ async function findProjects(folder, prefix, level, depth) { const name = prefix + entry.name if (await hasPackageJson(directory)) { - return [{ name, directory, hasPackageJson: true }] + const workspaces = await readWorkspacePatterns(directory) + + return [ + { + name, + directory, + hasPackageJson: true, + ...(workspaces && { workspaces }), + }, + ] } if (level < depth) { diff --git a/test/cli.test.js b/test/cli.test.js index 0e50af9..7f404eb 100644 --- a/test/cli.test.js +++ b/test/cli.test.js @@ -2151,3 +2151,144 @@ test('CLI lists projects down to the saved depth', async () => { 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 } + }, + readGitBranch: async directory => { + asked.branches.push(directory) + return 'main' + }, + ...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 once for the session. + assert.deepEqual(asked.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 shows a monorepo with its package count, and a package with its name', async () => { + let options + const { dependencies, shop, asked } = 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', + }) + assert.deepEqual(await options.details(api), { + detail: '2 scripts', + hint: '@shop/api', + }) + // A package has its monorepo's branch, so it is not read again. + assert.deepEqual(asked.branches, [shop.directory]) +}) + +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' }], + ]) + } +}) diff --git a/test/list.test.js b/test/list.test.js index daa6f52..537bca8 100644 --- a/test/list.test.js +++ b/test/list.test.js @@ -1657,3 +1657,96 @@ test('row buttons are divided by a line in the faint accent', async () => { terminal.type(KEYS.enter) await result }) + +// A monorepo with two packages, next to an ordinary project. +function treeItems() { + const api = { label: 'packages/api', value: 'shop/api' } + const ui = { label: 'packages/ui', value: 'shop/ui' } + + return [ + { label: 'shop', value: 'shop', children: [api, ui] }, + { label: 'web', value: 'web' }, + ] +} + +test('an item with children opens with → and closes with ←', async () => { + const terminal = createTerminal() + const result = terminal.select({ message: 'Pick', items: treeItems() }) + + assert.deepEqual(terminal.screen().slice(2, 4), [' ❯ ▸ shop', ' web']) + assert.match(terminal.screen().at(-1), /→ expand/) + + terminal.type(KEYS.right) + + assert.deepEqual(terminal.screen().slice(2, 6), [ + ' ❯ ▾ shop', + ' packages/api', + ' packages/ui', + ' web', + ]) + assert.match(terminal.screen().at(-1), /← collapse/) + + // ← on a child closes its parent and selects it. + terminal.type(KEYS.down, KEYS.down) + assert.equal(terminal.screen()[4], ' ❯ packages/ui') + + terminal.type(KEYS.left) + assert.deepEqual(terminal.screen().slice(2, 4), [' ❯ ▸ shop', ' web']) + + terminal.type(KEYS.right, 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 items = treeItems() + const result = terminal.select({ + message: 'Pick', + // A recent copy of a child is not shown twice. + items: [{ label: 'shop/api', value: 'shop/api' }, ...items], + }) + + 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('the parent of the default value starts open, and its ▸ is a button', async () => { + const terminal = createTerminal() + const result = terminal.select({ + message: 'Pick', + items: treeItems(), + default: 'shop/ui', + mouse: true, + fullscreen: true, + clickOpens: true, + }) + + // The list is drawn from row 1: the message, then shop on row 3. + assert.equal(terminal.screen()[4], ' ❯ packages/ui') + + terminal.click(3, 5) + assert.deepEqual(terminal.screen().slice(2, 4), [' ❯ ▸ shop', ' web']) + + terminal.click(3, 5) + assert.equal(terminal.screen()[3], ' packages/api') + + // A click on the name opens the parent itself. + terminal.click(3, 9) + assert.equal(await result, 'shop') +}) diff --git a/test/prompts.test.js b/test/prompts.test.js index 8fc1b98..af80b29 100644 --- a/test/prompts.test.js +++ b/test/prompts.test.js @@ -530,3 +530,36 @@ 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, + children: [{ label: 'packages/api', value: api }], + }, + { label: 'web', value: web }, + ]) + assert.equal(calls.select[0].default, api) +}) diff --git a/test/workspace.test.js b/test/workspace.test.js index fcc2393..a57af58 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' @@ -579,3 +582,135 @@ test('getProjects searches nested folders down to the depth', async () => { ) }) }) + +test('parsePnpmWorkspace reads the packages list in either style', () => { + assert.deepEqual( + parsePnpmWorkspace( + [ + '# the workspace', + 'packages:', + " - 'packages/*'", + ' - "apps/**"', + '', + ' # tools too', + ' - tools/cli # the CLI', + " - '!**/test/**'", + 'catalog:', + ' - not-a-package', + ].join('\r\n'), + ), + ['packages/*', 'apps/**', 'tools/cli', '!**/test/**'], + ) + assert.deepEqual(parsePnpmWorkspace('packages: [\'a/*\', "b"]\n'), [ + 'a/*', + 'b', + ]) + 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')) + }) +}) From 7588dec72305a7c7f7a1061e001c3799fc14d748 Mon Sep 17 00:00:00 2001 From: versnic <37933264+versnic@users.noreply.github.com> Date: Wed, 11 Nov 2026 00:05:55 +0100 Subject: [PATCH 04/17] feat: save several named workspaces --- CONTRIBUTING.md | 2 +- README.md | 47 +++++---- ROADMAP.md | 2 +- lib/args.js | 8 +- lib/cli.js | 227 ++++++++++++++++++++++++++++++++++++++++--- lib/config.js | 31 +++++- lib/prompts.js | 54 ++++++++-- lib/ui.js | 10 +- test/args.test.js | 12 ++- test/cli.test.js | 220 ++++++++++++++++++++++++++++++++++++++--- test/config.test.js | 36 +++++++ test/prompts.test.js | 50 ++++++++++ test/ui.test.js | 7 ++ 13 files changed, 645 insertions(+), 61 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 1badcc1..0accc8a 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 a comment describing what it contains and how it is used. Keep that comment accurate when you change the file. -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 61fee43..092af7b 100644 --- a/README.md +++ b/README.md @@ -105,7 +105,7 @@ This installs two equivalent commands, `dev-workspace` and the shorter `dws`. 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 stays within 100 columns on wide terminals. 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 stays within 100 columns on wide terminals. 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. @@ -221,21 +221,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)) | -| `--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)) | +| 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 @@ -270,11 +272,22 @@ The workspace path is saved in the standard configuration folder of your operati - 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 039ded5..47ea2b4 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -183,7 +183,7 @@ Every screen checked in the terminals people use, on their own schedule: they ne - [x] **Monorepos:** detect npm, Yarn and pnpm workspaces. A monorepo appears as one project with expandable packages; scripts run in the selected package. → or a click on its `▸` shows the 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). -- [ ] **Multiple named workspaces:** save several workspaces (for example `work` and `personal`), switch between them from the menu, and choose one with `--workspace `. +- [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. diff --git a/lib/args.js b/lib/args.js index 576ae1f..3e4c0f7 100644 --- a/lib/args.js +++ b/lib/args.js @@ -41,7 +41,11 @@ 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 @@ -84,6 +88,8 @@ 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' }, diff --git a/lib/cli.js b/lib/cli.js index 0519311..39d9e7a 100644 --- a/lib/cli.js +++ b/lib/cli.js @@ -12,9 +12,10 @@ // with arguments, then offer to run it again. Every menu shows the header // box from ui.js, with the project as a breadcrumb and its package manager // as the tag; empty and error states are shown in the box's screen, as the -// list's body. The workspace is chosen from a list of the common workspace -// folders that exist (suggestWorkspaces()), with "Enter another path" for -// any other folder; without any of them, the path prompt opens directly. +// list's body. The workspace is chosen from a list of the saved workspaces +// and the common workspace folders not saved yet (suggestWorkspaces()), +// with "Enter another path" for any other folder; without any of them, the +// path prompt opens directly. // On the first run, the accent colour is asked next (chooseColor()), with // each choice previewed as the cursor reaches it, and saved with the // workspace; --set-color changes it later. @@ -24,6 +25,15 @@ // resolveDirectoryInput(), so ~, quotes and escaped spaces work without a // shell. // +// Named workspaces: every workspace used is saved under a name +// (savedWorkspaces(), saveWorkspace()), its folder name made unique +// (uniqueName()), or, for a folder added from the project list, a name typed +// at askForWorkspaceName() and checked by checkWorkspaceName(). The name +// starts the header's breadcrumb. --workspace takes a saved name before a +// path; --list-workspaces and --remove-workspace (never the current one) +// manage them. A configuration saved before names existed lists its +// workspace under its folder name. +// // The menus are drawn on the alternate screen (screen.js). The CLI leaves it // (ui.leaveScreen) before a script runs, so its output stays on the normal // screen, and whenever the menus end, before any error or "Goodbye!". @@ -94,11 +104,13 @@ import { readColorSetting, readDepthSetting, readMouseSetting, + readSavedWorkspaces, readWorkspaceConfig, resetWorkspaceConfig, saveColorSetting, saveDepthSetting, saveMouseSetting, + saveSavedWorkspaces, saveWorkspaceConfig, } from './config.js' @@ -142,6 +154,7 @@ import { RUN_WITH_ARGUMENTS, askForArguments, askForWorkspace, + askForWorkspaceName, chooseAccent, chooseProject, chooseScript, @@ -155,7 +168,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') @@ -235,6 +248,57 @@ function exitCodeOf({ code, signal }) { return code ?? 1 } +// 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 /. @@ -278,11 +342,13 @@ const defaultDependencies = { readColorSetting, readDepthSetting, readMouseSetting, + readSavedWorkspaces, readWorkspaceConfig, resetWorkspaceConfig, saveColorSetting, saveDepthSetting, saveMouseSetting, + saveSavedWorkspaces, saveWorkspaceConfig, }, history: { @@ -311,6 +377,7 @@ const defaultDependencies = { prompts: { askForArguments, askForWorkspace, + askForWorkspaceName, chooseAccent, chooseProject, chooseScript, @@ -367,6 +434,8 @@ 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() @@ -379,7 +448,10 @@ export function createCli(overrides = {}) { // 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 @@ -435,18 +507,67 @@ 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) { @@ -463,10 +584,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 @@ -484,7 +616,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() @@ -503,10 +635,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) { @@ -556,6 +703,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 } @@ -726,6 +874,7 @@ export function createCli(overrides = {}) { for (const line of ui.drawHeader({ workspace: root, + name: workspaceName, crumbs: [project.name, script.name], tag: describePackageManager(packageManager), })) { @@ -1091,6 +1240,56 @@ export function createCli(overrides = {}) { ) } + 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) @@ -1108,6 +1307,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']) } diff --git a/lib/config.js b/lib/config.js index 032e61e..56e28a4 100644 --- a/lib/config.js +++ b/lib/config.js @@ -8,10 +8,14 @@ // Files left in ~/.dev-workspace-cli by versions before 0.3.0 are moved // automatically by migrateLegacyConfig(). // -// The file holds the workspace, the accent colour chosen on the first run, -// and, optionally, whether menus use the mouse and how deep projects are -// searched for: `{ "workspace": "", "color": "cyan", "mouse": false, -// "depth": 2 }`. readMouseSetting() is false only for `"mouse": false`, +// The file holds the workspace, the saved workspaces by name, the accent +// colour chosen on the first run, and, optionally, whether menus use the +// mouse and how deep projects are searched for: `{ "workspace": "", +// "workspaces": { "dev": "" }, "color": "cyan", "mouse": false, +// "depth": 2 }`. readSavedWorkspaces() returns the valid entries of +// `workspaces`, never failing, and saveSavedWorkspaces() replaces them; +// `workspace` stays the path of the current one, so files saved before +// names existed still work. readMouseSetting() is false only for `"mouse": false`, // readColorSetting() returns the colour's name or null, and // readDepthSetting() a depth from 1 to 3 (1 by default); none of them ever // fails: a problem with the file is reported by readWorkspaceConfig(). @@ -211,6 +215,25 @@ 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) { diff --git a/lib/prompts.js b/lib/prompts.js index 38812f6..60a1a63 100644 --- a/lib/prompts.js +++ b/lib/prompts.js @@ -28,10 +28,15 @@ // RUN_WITH_ARGUMENTS for the `… Run with args` button, or null for // `← Back` and Escape. With `forArguments`, it // asks which script to run with arguments, and Back returns to the scripts. -// chooseWorkspace() lists the suggested workspace folders, with details -// loaded lazily through `details` (cli.js passes the number of projects), the -// `current` folder tagged and selected, and `… Enter another path` last. It -// returns the folder or ENTER_PATH; with `cancellable`, Escape returns null. +// chooseWorkspace() lists the `saved` workspaces ({ name, directory, +// missing }: by name, with their path, and dimmed as `not found` when +// missing), then the suggested workspace folders, with details loaded lazily +// through `details` (cli.js passes the number of projects), under "Saved" +// and "Suggested" titles when there are both, the `current` folder tagged +// and selected, and `… Enter another path` last. It returns the folder or +// ENTER_PATH; with `cancellable`, Escape returns null. +// askForWorkspaceName() asks for a new workspace's name, filled in with +// `suggested`; Escape returns null. // chooseAccent() lists the accent colours, each name in its own colour and // the first tagged "default", calls `preview` with the colour under the // cursor (cli.js passes ui.setAccent, so the whole screen previews it) and @@ -199,22 +204,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, @@ -378,6 +417,7 @@ export function createPrompts({ export const { askForArguments, askForWorkspace, + askForWorkspaceName, chooseAccent, confirmWorkspaceChange, chooseProject, diff --git a/lib/ui.js b/lib/ui.js index 84c1cf8..c21396b 100644 --- a/lib/ui.js +++ b/lib/ui.js @@ -33,7 +33,8 @@ // ╰───────────────────────────────────────────────────────────────────╯ // // The top border carries the breadcrumb of the current screen, starting with -// the name of the workspace folder (folderName()), and an optional tag on +// the workspace's `name` (a saved workspace's name, or else the name of the +// workspace folder: folderName()), and an optional tag on // the right, dropped when the breadcrumb needs the room. The // workspace line ends with the `toolbar` segments (list.js passes its toolbar // buttons), and its path is shortened in the middle to fit next to them; on @@ -185,7 +186,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, @@ -193,7 +194,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/test/args.test.js b/test/args.test.js index 8ad836d..76b6944 100644 --- a/test/args.test.js +++ b/test/args.test.js @@ -55,6 +55,8 @@ 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', @@ -92,7 +94,11 @@ 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 @@ -139,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]')) }) diff --git a/test/cli.test.js b/test/cli.test.js index 7f404eb..7154e5e 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: [], @@ -50,6 +56,10 @@ 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 () => [], @@ -101,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 @@ -355,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), [ '', @@ -772,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) }) @@ -2292,3 +2306,185 @@ test('CLI runs a package script directly, by its full name or its last part', as ]) } }) + +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/) +}) diff --git a/test/config.test.js b/test/config.test.js index e584a22..d118e30 100644 --- a/test/config.test.js +++ b/test/config.test.js @@ -19,11 +19,13 @@ import { readColorSetting, readDepthSetting, readMouseSetting, + readSavedWorkspaces, readWorkspaceConfig, resetWorkspaceConfig, saveColorSetting, saveDepthSetting, saveMouseSetting, + saveSavedWorkspaces, saveWorkspaceConfig, } from '../lib/config.js' @@ -414,3 +416,37 @@ test('saveDepthSetting saves the depth, and readDepthSetting checks it', async ( 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/prompts.test.js b/test/prompts.test.js index af80b29..d4c821f 100644 --- a/test/prompts.test.js +++ b/test/prompts.test.js @@ -563,3 +563,53 @@ test('chooseProject expands a monorepo into its packages', async () => { ]) assert.equal(calls.select[0].default, api) }) + +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) +}) 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' }, From 8fa6f72a5ceeac336c60b1fb1102a48f89ceee9e Mon Sep 17 00:00:00 2001 From: versnic <37933264+versnic@users.noreply.github.com> Date: Wed, 11 Nov 2026 00:07:05 +0100 Subject: [PATCH 05/17] docs: label bigger workspaces as released in 0.10.0 --- ROADMAP.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index 47ea2b4..2657947 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.10.0 | Monorepos, nested projects, multiple named workspaces | | Configuration and scripts | Planned | Versioned config schema, `config` command, JSON output | | 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,7 +179,7 @@ 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.10.0)_ - [x] **Monorepos:** detect npm, Yarn and pnpm workspaces. A monorepo appears as one project with expandable packages; scripts run in the selected package. → or a click on its `▸` shows the 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). @@ -187,6 +187,8 @@ Every screen checked in the terminals people use, on their own schedule: they ne **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. From 09b4f254a1ad2cbe2dddf6e8182200b1a9f5375e Mon Sep 17 00:00:00 2001 From: versnic <37933264+versnic@users.noreply.github.com> Date: Wed, 11 Nov 2026 14:16:15 +0100 Subject: [PATCH 06/17] fix: keep the packages of a recent monorepo --- lib/prompts.js | 7 ++++--- test/prompts.test.js | 19 +++++++++++++++++++ 2 files changed, 23 insertions(+), 3 deletions(-) diff --git a/lib/prompts.js b/lib/prompts.js index 60a1a63..366753c 100644 --- a/lib/prompts.js +++ b/lib/prompts.js @@ -286,8 +286,9 @@ export function createPrompts({ { recent = [], details, packages, default: selected, ...options } = {}, ) { const item = project => projectItem(project, details) - // A monorepo in the list expands into its packages, each labelled with - // its path in the monorepo; in "Recent", items have their full name. + // A monorepo expands into its packages, each labelled with its path in + // the monorepo, in "Recent" as in "All projects"; a recent package has + // its full name. const tree = project => { const children = packages?.(project) ?? [] @@ -305,7 +306,7 @@ export function createPrompts({ 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', }) } diff --git a/test/prompts.test.js b/test/prompts.test.js index d4c821f..e4e4717 100644 --- a/test/prompts.test.js +++ b/test/prompts.test.js @@ -613,3 +613,22 @@ test('askForWorkspaceName suggests a name, trims it, and Escape returns null', a 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: 'api', value: api }] }, + { separator: 'All projects' }, + { label: 'web', value: web }, + ]) +}) From c3c63f228c9bb80d193d9ded2f35ce53d535c279 Mon Sep 17 00:00:00 2001 From: versnic <37933264+versnic@users.noreply.github.com> Date: Wed, 11 Nov 2026 14:27:38 +0100 Subject: [PATCH 07/17] feat: open monorepos into their root and packages, and ask for required arguments --- README.md | 7 ++- ROADMAP.md | 2 +- lib/cli.js | 42 +++++++++++--- lib/list.js | 57 ++++++++++++------- lib/prompts.js | 62 +++++++++++++++------ lib/script-arguments.js | 102 ++++++++++++++++++++++++++++++++++ lib/workspace.js | 11 +++- test/cli.test.js | 88 +++++++++++++++++++++++++++++ test/list.test.js | 72 ++++++++++++++++-------- test/prompts.test.js | 76 ++++++++++++++++++++++++- test/script-arguments.test.js | 49 ++++++++++++++++ test/workspace.test.js | 23 ++++++++ 12 files changed, 516 insertions(+), 75 deletions(-) create mode 100644 lib/script-arguments.js create mode 100644 test/script-arguments.test.js diff --git a/README.md b/README.md index 092af7b..e94dcff 100644 --- a/README.md +++ b/README.md @@ -152,6 +152,8 @@ 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`. @@ -166,10 +168,11 @@ In the script list, each script's command is shown next to its name, shortened t #### 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`). Press → on it, or click the `▸`, to show its packages under it, and ← to hide them again; Enter or a click on its name opens the scripts of the monorepo itself, as for any project. +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 apps/web 1 script packages/api 2 scripts @shop/api packages/ui 1 script @shop/ui @@ -211,7 +214,7 @@ 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 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. +- 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. diff --git a/ROADMAP.md b/ROADMAP.md index 2657947..6e7c307 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -181,7 +181,7 @@ Every screen checked in the terminals people use, on their own schedule: they ne ## Bigger workspaces _(released in 0.10.0)_ -- [x] **Monorepos:** detect npm, Yarn and pnpm workspaces. A monorepo appears as one project with expandable packages; scripts run in the selected package. → or a click on its `▸` shows the 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] **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). diff --git a/lib/cli.js b/lib/cli.js index 39d9e7a..9b1436e 100644 --- a/lib/cli.js +++ b/lib/cli.js @@ -759,12 +759,13 @@ export function createCli(overrides = {}) { // counts them) and Git branch, with its package manager as the tag. // 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 no - // branch: its monorepo shows both. - async function readDetails(project) { + // branch: its monorepo shows both. 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(toolDirectory(project)), - monorepo ? null : workspace.readGitBranch(directory), + monorepo || root ? null : workspace.readGitBranch(directory), ]) let detail @@ -778,6 +779,8 @@ export function createCli(overrides = {}) { detail = 'invalid package.json' } + if (root) return { detail } + if (project.workspaces) { const count = (await packagesOf(project)).length @@ -844,12 +847,12 @@ export function createCli(overrides = {}) { return [...projects, ...[...packages.values()].flat()] } - function projectDetails(project) { - if (!details.has(project.directory)) { - details.set(project.directory, readDetails(project)) - } + function projectDetails(project, { root = false } = {}) { + const key = root ? `root:${project.directory}` : project.directory - return details.get(project.directory) + if (!details.has(key)) details.set(key, readDetails(project, root)) + + return details.get(key) } async function readProjects() { @@ -948,9 +951,21 @@ 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 } } @@ -958,6 +973,7 @@ export function createCli(overrides = {}) { async function projectMenu(project) { details.delete(project.directory) + details.delete(`root:${project.directory}`) // Detected first: hooks are grouped under their main script only when the // package manager runs them. @@ -1049,6 +1065,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( diff --git a/lib/list.js b/lib/list.js index a84e375..bf8995d 100644 --- a/lib/list.js +++ b/lib/list.js @@ -12,10 +12,13 @@ // Items are { label, value, icon, detail, detailEnd, hint, hintStyle, // disabled, load, style, children } or { separator }. An item with // `children` (items too, one level deep) can be expanded: a ▸ before its -// label (▾ while open) shows it, → or a click on the ▸ opens it, and ← -// closes it again, also from one of its children, which then selects the -// parent. Its children are drawn indented under it while it is open; the -// parent holding the `default` value starts open. A search looks through +// label (▾ while open) shows it. Choosing it (Enter, a click, middle-click) +// opens or closes it instead of resolving, and while searching clears the +// search and opens it; → also opens it, and ← closes it again, also from +// one of its children, which then selects the parent. Its children are +// drawn indented under it while it is open; the parent holding the +// `default` value starts open, and a default value that is both a parent's +// and one of its children's selects the child. A search looks through // every child, open or not, showing each with its parent (`shop › api`), // and each value only once. `style` (a style name from // ui.js) colours the label while the item is not selected; the selected one @@ -574,12 +577,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() @@ -634,11 +640,24 @@ 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) + + 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, @@ -896,22 +915,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)}`) } - - // What the arrows do on the selected parent or child. - const item = focus === 'list' && !query ? rows[cursor]?.item : null - - if (item && (open.has(item) || parents.has(item))) { - help.push('← collapse') - } else if (item?.children?.length) { - help.push('→ expand') - } + 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 366753c..3d5d18a 100644 --- a/lib/prompts.js +++ b/lib/prompts.js @@ -15,9 +15,10 @@ // promise of { detail, hint }), the list loads each project's details as it // comes into view: cli.js passes `12 scripts · main` and the package manager. // With `packages` (a function of a project returning its packages, as -// projects with a `path` in the monorepo), a monorepo can be expanded in the -// list to show its packages under it (see list.js); a package opens like a -// project. The cursor starts on the `default` project or package, if given. +// projects with a `path` in the monorepo), opening a monorepo expands it in +// the list (see list.js): `root` first, which returns the monorepo itself so +// its own scripts open (its details are asked with `{ root: true }`), then +// its packages, which open like projects. The cursor starts on the `default` project or package, if given. // It returns the project, CHANGE_WORKSPACE for the `⚙ Workspace` button, or // null for `✕ Exit` and Escape. chooseScript() puts // the cursor on the project's last script, tagged "last run" in the accent @@ -41,6 +42,10 @@ // the first tagged "default", calls `preview` with the colour under the // cursor (cli.js passes ui.setAccent, so the whole screen previews it) and // returns the chosen name. +// chooseScript() tags a script that needs arguments `needs arguments` (unless +// it is the last run), and Enter, a click or `▶ run` on it asks for them +// (withArguments: true); askForArguments() with `required` then refuses an +// empty answer. // askForWorkspace() asks for a path; with `cancellable` (changing the // workspace from the project list), Escape aborts the question and it // returns null, so the CLI goes back. askForArguments() splits what the user @@ -122,6 +127,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', @@ -286,21 +294,28 @@ export function createPrompts({ { recent = [], details, packages, default: selected, ...options } = {}, ) { const item = project => projectItem(project, details) - // A monorepo expands into its packages, each labelled with its path in - // the monorepo, in "Recent" as in "All projects"; a recent package has - // its full name. + // A monorepo expands into `root`, which opens the scripts of its own + // package.json, then its packages, each labelled with its path in the + // monorepo, in "Recent" as in "All projects"; a recent package has its + // full name. const tree = project => { const children = packages?.(project) ?? [] - return children.length === 0 - ? item(project) - : { - ...item(project), - children: children.map(child => ({ - ...item(child), - label: child.path, - })), - } + 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: child.path })), + ], + } } const others = projects.filter(project => !recent.includes(project)) const items = others.map(tree) @@ -352,7 +367,10 @@ export function createPrompts({ rowButtons: [ { label: '▶ run', - value: script => ({ script, withArguments: false }), + value: script => ({ + script, + withArguments: Boolean(script.needsArguments), + }), }, { label: '… run with args', @@ -368,17 +386,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 diff --git a/lib/script-arguments.js b/lib/script-arguments.js new file mode 100644 index 0000000..1e5ed61 --- /dev/null +++ b/lib/script-arguments.js @@ -0,0 +1,102 @@ +// Recognising scripts that cannot run without arguments. +// +// Some scripts are helpers that other scripts call with the rest of the +// command, such as `"packages": "yarn workspaces foreach --all"`, called as +// `yarn packages run test`. Run on their own, they fail (Yarn: "Not enough +// positional arguments"). needsArguments() recognises them from the command +// alone, without running anything, so the menu can ask for the arguments +// first and direct mode can refuse to start them without any. +// +// Only the last command of a chain (after &&, ||, ; or |) is looked at, +// since the arguments are added at the end. It counts as needing arguments +// when, once its options are left out, 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 +// +// Options that take a value (VALUE_OPTIONS) skip that value too, so +// `--include '@modulane/*'` is not read as a command. Anything else counts +// as runnable on its own, so a script is never blocked by mistake. +// +// Used by workspace.js, whose getScripts() marks such scripts with +// `needsArguments: true`. + +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. +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/workspace.js b/lib/workspace.js index 967d7a0..e374575 100644 --- a/lib/workspace.js +++ b/lib/workspace.js @@ -21,7 +21,9 @@ // ignored, as npm does), and attaches pre/post hooks to their main script // instead of listing them separately. cli.js turns that off with // `{ groupHooks: false }` for package managers that never run the hooks -// (Yarn 2+), so the hooks stay listed and runnable on their own. +// (Yarn 2+), so the hooks stay listed and runnable on their own. A script +// that cannot run without arguments (needsArguments() from +// script-arguments.js) is marked `needsArguments: true`. // // readGitBranch() reads a project's current Git branch straight from // .git/HEAD, without running Git (a .git file, as in worktrees and @@ -48,6 +50,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) { @@ -569,7 +572,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/cli.test.js b/test/cli.test.js index 7154e5e..583620e 100644 --- a/test/cli.test.js +++ b/test/cli.test.js @@ -2488,3 +2488,91 @@ test('checkWorkspaceName refuses names that read as paths or are taken', () => { } 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/list.test.js b/test/list.test.js index 537bca8..dc4f218 100644 --- a/test/list.test.js +++ b/test/list.test.js @@ -1658,42 +1658,52 @@ test('row buttons are divided by a line in the faint accent', async () => { await result }) -// A monorepo with two packages, next to an ordinary project. +// 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: [api, ui] }, + { label: 'shop', value: 'shop', children: [root, api, ui] }, { label: 'web', value: 'web' }, ] } -test('an item with children opens with → and closes with ←', async () => { +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() }) + 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), /→ expand/) + assert.match(terminal.screen().at(-1), /enter expand/) - terminal.type(KEYS.right) + terminal.type(KEYS.enter) - assert.deepEqual(terminal.screen().slice(2, 6), [ + assert.deepEqual(terminal.screen().slice(2, 7), [ ' ❯ ▾ shop', + ' root', ' packages/api', ' packages/ui', ' web', ]) - assert.match(terminal.screen().at(-1), /← collapse/) + assert.match(terminal.screen().at(-1), /enter collapse/) - // ← on a child closes its parent and selects it. - terminal.type(KEYS.down, KEYS.down) - assert.equal(terminal.screen()[4], ' ❯ packages/ui') + 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.enter) + 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/) @@ -1701,11 +1711,10 @@ test('an item with children opens with → and closes with ←', async () => { test('a search looks through every child, each value once', async () => { const terminal = createTerminal() - const items = treeItems() const result = terminal.select({ message: 'Pick', // A recent copy of a child is not shown twice. - items: [{ label: 'shop/api', value: 'shop/api' }, ...items], + items: [{ label: 'shop/api', value: 'shop/api' }, ...treeItems()], }) terminal.type('u', 'i') @@ -1726,27 +1735,46 @@ test('a search looks through every child, each value once', async () => { assert.equal(await result, 'shop/api') }) -test('the parent of the default value starts open, and its ▸ is a button', async () => { +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(), - default: 'shop/ui', + // 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()[4], ' ❯ packages/ui') + 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, 5) - assert.equal(terminal.screen()[3], ' packages/api') - - // A click on the name opens the parent itself. terminal.click(3, 9) - assert.equal(await result, 'shop') + 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 e4e4717..5743336 100644 --- a/test/prompts.test.js +++ b/test/prompts.test.js @@ -557,7 +557,11 @@ test('chooseProject expands a monorepo into its packages', async () => { { label: 'shop', value: shop, - children: [{ label: 'packages/api', value: api }], + // root opens the monorepo's own scripts. + children: [ + { label: 'root', value: shop }, + { label: 'packages/api', value: api }, + ], }, { label: 'web', value: web }, ]) @@ -627,8 +631,76 @@ test('chooseProject keeps the packages of a recent monorepo', async () => { assert.deepEqual(calls.select[0].items, [ { separator: 'Recent' }, - { label: 'shop', value: shop, children: [{ label: 'api', value: api }] }, + { + 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/workspace.test.js b/test/workspace.test.js index a57af58..e62bdb8 100644 --- a/test/workspace.test.js +++ b/test/workspace.test.js @@ -714,3 +714,26 @@ test('getPackages expands the workspace patterns into packages', async () => { assert.equal(packages[2].directory, path.join(directory, 'packages', 'api')) }) }) + +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, + }, + ]) + }) +}) From f3ea217be228e6095d9d6378781ebe1cf3e36010 Mon Sep 17 00:00:00 2001 From: versnic <37933264+versnic@users.noreply.github.com> Date: Wed, 11 Nov 2026 14:55:42 +0100 Subject: [PATCH 08/17] feat: show packages by folder name in a tree, with their own branch MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A package no longer repeats its monorepo folder (packages/api is shown as api, under ├ or └ tree lines); two packages with the same folder name keep their whole path. A package that is a Git repository of its own shows its branch. --- README.md | 10 +++++----- lib/cli.js | 9 +++++---- lib/list.js | 6 ++++-- lib/prompts.js | 23 +++++++++++++++++++---- test/cli.test.js | 37 +++++++++++++++++++++++++++++++++---- test/list.test.js | 14 +++++++------- test/prompts.test.js | 21 ++++++++++++++++++++- 7 files changed, 93 insertions(+), 27 deletions(-) diff --git a/README.md b/README.md index e94dcff..c6f6022 100644 --- a/README.md +++ b/README.md @@ -172,14 +172,14 @@ A project that declares workspaces is shown as a monorepo: the `workspaces` fiel ```text ❯ ▾ shop 3 packages · 2 scripts · main pnpm - root 2 scripts - apps/web 1 script - packages/api 2 scripts @shop/api - packages/ui 1 script @shop/ui + ├ root 2 scripts + ├ web 1 script · feat/landing + ├ api 2 scripts @shop/api + └ ui 1 script @shop/ui web 2 scripts · main npm ``` -Each package is listed by its folder in the monorepo, with its `name` from `package.json` on the right when it differs from the folder name. 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`; they are read once per session. Searching looks through every package, shown or not: typing `ui` finds `shop › packages/ui`. Packages appear in the recent projects too, under their full name (`shop/packages/api`). +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`; 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 diff --git a/lib/cli.js b/lib/cli.js index 9b1436e..231a934 100644 --- a/lib/cli.js +++ b/lib/cli.js @@ -758,14 +758,15 @@ 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. // 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 no - // branch: its monorepo shows both. A monorepo's `root` entry (`root: - // true`) shows only the script count of its own package.json. + // 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(toolDirectory(project)), - monorepo || root ? null : workspace.readGitBranch(directory), + root ? null : workspace.readGitBranch(directory), ]) let detail diff --git a/lib/list.js b/lib/list.js index bf8995d..635a9b4 100644 --- a/lib/list.js +++ b/lib/list.js @@ -455,12 +455,14 @@ export function createList({ // 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 an indent before a child. While searching, + // 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) return query ? `${parent.label} › ` : ' ' + if (parent && query) return `${parent.label} › ` + if (parent) return parent.children.at(-1) === item ? ' └ ' : ' ├ ' if (!tree || query) return '' if (!item.children?.length) return ' ' diff --git a/lib/prompts.js b/lib/prompts.js index 3d5d18a..c993141 100644 --- a/lib/prompts.js +++ b/lib/prompts.js @@ -138,6 +138,18 @@ function scriptItem(script, lastScript) { } // The header and body for the list, left out while unset. +// 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 +} + function frame({ header, body } = {}) { return { ...(header && { header }), ...(body?.length && { body }) } } @@ -295,9 +307,9 @@ export function createPrompts({ ) { 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 path in the - // monorepo, in "Recent" as in "All projects"; a recent package has its - // full name. + // 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) ?? [] @@ -313,7 +325,10 @@ export function createPrompts({ ...item(project), children: [ root, - ...children.map(child => ({ ...item(child), label: child.path })), + ...children.map(child => ({ + ...item(child), + label: packageLabel(child, children), + })), ], } } diff --git a/test/cli.test.js b/test/cli.test.js index 583620e..c74b88c 100644 --- a/test/cli.test.js +++ b/test/cli.test.js @@ -2206,9 +2206,10 @@ function monorepoDependencies(overrides = {}) { 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 'main' + return directory === shop.directory ? 'main' : null }, ...overrides.workspace, }, @@ -2267,7 +2268,7 @@ test('CLI opens a package of a monorepo and runs its script there', async () => test('CLI shows a monorepo with its package count, and a package with its name', async () => { let options - const { dependencies, shop, asked } = monorepoDependencies({ + const { dependencies, shop } = monorepoDependencies({ prompts: { chooseProject: async (projects, given) => { options = given @@ -2288,12 +2289,40 @@ test('CLI shows a monorepo with its package count, and a package with its name', ], 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', }) - // A package has its monorepo's branch, so it is not read again. - assert.deepEqual(asked.branches, [shop.directory]) }) test('CLI runs a package script directly, by its full name or its last part', async () => { diff --git a/test/list.test.js b/test/list.test.js index dc4f218..c7c3c01 100644 --- a/test/list.test.js +++ b/test/list.test.js @@ -1685,9 +1685,9 @@ test('Enter on an item with children opens or closes it, and ← closes it', asy assert.deepEqual(terminal.screen().slice(2, 7), [ ' ❯ ▾ shop', - ' root', - ' packages/api', - ' packages/ui', + ' ├ root', + ' ├ packages/api', + ' └ packages/ui', ' web', ]) assert.match(terminal.screen().at(-1), /enter collapse/) @@ -1697,7 +1697,7 @@ test('Enter on an item with children opens or closes it, and ← closes it', asy // → 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.equal(terminal.screen()[4], ' ❯ ├ packages/api') assert.match(terminal.screen().at(-1), /enter open · ← collapse/) terminal.type(KEYS.left) @@ -1745,7 +1745,7 @@ test('Enter on a parent found by a search clears it and opens the parent', async terminal.type(KEYS.enter) assert.deepEqual(terminal.screen().slice(2, 4), [ ' ❯ ▾ shop', - ' root', + ' ├ root', ]) terminal.type(KEYS.down, KEYS.enter) @@ -1765,14 +1765,14 @@ test('the default value opens its parent, and a click opens or closes it', async }) // The list is drawn from row 1: the message, then shop on row 3. - assert.equal(terminal.screen()[3], ' ❯ root') + 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') + assert.equal(terminal.screen()[4], ' ├ packages/api') // A child is chosen with one click. terminal.click(5, 12) diff --git a/test/prompts.test.js b/test/prompts.test.js index 5743336..fa93196 100644 --- a/test/prompts.test.js +++ b/test/prompts.test.js @@ -560,7 +560,7 @@ test('chooseProject expands a monorepo into its packages', async () => { // root opens the monorepo's own scripts. children: [ { label: 'root', value: shop }, - { label: 'packages/api', value: api }, + { label: 'api', value: api }, ], }, { label: 'web', value: web }, @@ -568,6 +568,25 @@ test('chooseProject expands a monorepo into its packages', async () => { 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' }) From fe6ea2ccb6a61d1d2dee88ec971daa5098d6c3cc Mon Sep 17 00:00:00 2001 From: versnic <37933264+versnic@users.noreply.github.com> Date: Thu, 12 Nov 2026 11:15:36 +0100 Subject: [PATCH 09/17] docs: say how deep a ** workspace pattern is followed --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index c6f6022..12f180e 100644 --- a/README.md +++ b/README.md @@ -179,7 +179,7 @@ A project that declares workspaces is shown as a monorepo: the `workspaces` fiel 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`; 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`). +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 From a441b836b52da18223e0e0c01dcdb04a583783a6 Mon Sep 17 00:00:00 2001 From: versnic <37933264+versnic@users.noreply.github.com> Date: Thu, 12 Nov 2026 11:40:23 +0100 Subject: [PATCH 10/17] fix: find a monorepo by a prefix of its name again --- lib/cli.js | 9 ++++++++- test/cli.test.js | 23 +++++++++++++++++++++++ 2 files changed, 31 insertions(+), 1 deletion(-) diff --git a/lib/cli.js b/lib/cli.js index 1f8d602..65df657 100644 --- a/lib/cli.js +++ b/lib/cli.js @@ -218,6 +218,8 @@ export function checkWorkspaceName(typed, saved) { // 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() @@ -229,7 +231,12 @@ export function findProject(projects, typed, root) { ] 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] diff --git a/test/cli.test.js b/test/cli.test.js index c74b88c..dba0cc2 100644 --- a/test/cli.test.js +++ b/test/cli.test.js @@ -1358,6 +1358,29 @@ test('findProject finds nested projects by path or by their last part', () => { ) }) +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() From 2f9a5f887d6c2401a44d7a535e81c7488f4974b7 Mon Sep 17 00:00:00 2001 From: versnic <37933264+versnic@users.noreply.github.com> Date: Thu, 12 Nov 2026 11:40:42 +0100 Subject: [PATCH 11/17] fix: read pnpm workspace packages listed without indentation --- lib/workspace.js | 3 ++- test/workspace.test.js | 4 ++++ 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/lib/workspace.js b/lib/workspace.js index 9b9036c..6b3a844 100644 --- a/lib/workspace.js +++ b/lib/workspace.js @@ -244,7 +244,8 @@ export function parsePnpmWorkspace(content) { for (const line of lines.slice(start + 1)) { if (!line.trim() || line.trim().startsWith('#')) continue - const item = /^\s+-\s*(.+)$/.exec(line) + // 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 diff --git a/test/workspace.test.js b/test/workspace.test.js index e62bdb8..92a6c0e 100644 --- a/test/workspace.test.js +++ b/test/workspace.test.js @@ -605,6 +605,10 @@ test('parsePnpmWorkspace reads the packages list in either style', () => { 'a/*', 'b', ]) + assert.deepEqual( + parsePnpmWorkspace('packages:\n- apps/*\n- libs/*\ncatalog:\n- no\n'), + ['apps/*', 'libs/*'], + ) assert.deepEqual(parsePnpmWorkspace('catalog:\n react: ^19\n'), []) }) From 67437ff076a1a6f6a98c40265dfa491c1042f3b9 Mon Sep 17 00:00:00 2001 From: versnic <37933264+versnic@users.noreply.github.com> Date: Thu, 12 Nov 2026 11:40:56 +0100 Subject: [PATCH 12/17] fix: drop the comment after a quoted pnpm workspace package --- lib/workspace.js | 4 ++-- test/workspace.test.js | 3 ++- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/lib/workspace.js b/lib/workspace.js index 6b3a844..d75c7de 100644 --- a/lib/workspace.js +++ b/lib/workspace.js @@ -223,9 +223,9 @@ export function parsePnpmWorkspace(content) { const unquote = value => { const text = value.trim() - const quoted = /^(['"])(.*)\1$/.exec(text) + // A comment can follow the value, quoted or not. + const quoted = /^(['"])(.*?)\1(?:\s+#.*)?$/.exec(text) - // A comment can follow a value that has no quotes. return quoted ? quoted[2] : text.replace(/\s+#.*$/, '').trim() } const rest = lines[start].replace(/^packages\s*:/, '').trim() diff --git a/test/workspace.test.js b/test/workspace.test.js index 92a6c0e..372ed04 100644 --- a/test/workspace.test.js +++ b/test/workspace.test.js @@ -595,11 +595,12 @@ test('parsePnpmWorkspace reads the packages list in either style', () => { ' # tools too', ' - tools/cli # the CLI', " - '!**/test/**'", + " - 'docs' # it's the site", 'catalog:', ' - not-a-package', ].join('\r\n'), ), - ['packages/*', 'apps/**', 'tools/cli', '!**/test/**'], + ['packages/*', 'apps/**', 'tools/cli', '!**/test/**', 'docs'], ) assert.deepEqual(parsePnpmWorkspace('packages: [\'a/*\', "b"]\n'), [ 'a/*', From b7eac4f81831b7c144d65f1db7e51b4d059a4c4f Mon Sep 17 00:00:00 2001 From: versnic <37933264+versnic@users.noreply.github.com> Date: Thu, 12 Nov 2026 11:41:10 +0100 Subject: [PATCH 13/17] fix: read a pnpm workspace packages list spread over several lines --- lib/workspace.js | 14 +++++++++++++- test/workspace.test.js | 6 ++++++ 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/lib/workspace.js b/lib/workspace.js index d75c7de..9cced7a 100644 --- a/lib/workspace.js +++ b/lib/workspace.js @@ -231,7 +231,19 @@ export function parsePnpmWorkspace(content) { const rest = lines[start].replace(/^packages\s*:/, '').trim() if (rest.startsWith('[')) { - return rest + // 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(',') diff --git a/test/workspace.test.js b/test/workspace.test.js index 372ed04..25b54fa 100644 --- a/test/workspace.test.js +++ b/test/workspace.test.js @@ -606,6 +606,12 @@ test('parsePnpmWorkspace reads the packages list in either style', () => { '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/*'], From efaf33354970e2dbdc2616cb6dc72b77facc9e28 Mon Sep 17 00:00:00 2001 From: versnic <37933264+versnic@users.noreply.github.com> Date: Thu, 12 Nov 2026 11:43:13 +0100 Subject: [PATCH 14/17] docs: put the frame() comment back above frame() --- lib/prompts.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/prompts.js b/lib/prompts.js index 9ae50cf..e5f61e4 100644 --- a/lib/prompts.js +++ b/lib/prompts.js @@ -67,7 +67,6 @@ function scriptItem(script, lastScript) { } } -// The header and body for the list, left out while unset. // 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. @@ -80,6 +79,7 @@ function packageLabel(child, siblings) { 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 }) } } From 29b1ce83415e4869eee9a4b1b9ea7821a9d047bc Mon Sep 17 00:00:00 2001 From: versnic <37933264+versnic@users.noreply.github.com> Date: Thu, 12 Nov 2026 11:43:49 +0100 Subject: [PATCH 15/17] fix: read the packages of a monorepo again after opening it --- lib/cli.js | 9 +++++++++ test/cli.test.js | 22 ++++++++++++++++++++-- 2 files changed, 29 insertions(+), 2 deletions(-) diff --git a/lib/cli.js b/lib/cli.js index 65df657..ae43621 100644 --- a/lib/cli.js +++ b/lib/cli.js @@ -896,9 +896,18 @@ export function createCli(overrides = {}) { } 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( diff --git a/test/cli.test.js b/test/cli.test.js index dba0cc2..4534ba1 100644 --- a/test/cli.test.js +++ b/test/cli.test.js @@ -2275,8 +2275,11 @@ test('CLI opens a package of a monorepo and runs its script there', async () => assert.equal(api.name, 'shop/packages/api') assert.equal(api.monorepo, shop) assert.equal(lists[0].packages(web), undefined) - // Read once for the session. - assert.deepEqual(asked.packages, [[shop.directory, ['packages/*']]]) + // 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, [ @@ -2289,6 +2292,21 @@ test('CLI opens a package of a monorepo and runs its script there', async () => 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({ From 976ef84d65004e67bf2d957c5cfe91db874e40fd Mon Sep 17 00:00:00 2001 From: versnic <37933264+versnic@users.noreply.github.com> Date: Thu, 12 Nov 2026 11:44:18 +0100 Subject: [PATCH 16/17] fix: leave out the folder itself with a trailing /** exclusion --- lib/workspace.js | 7 ++++++- test/workspace.test.js | 21 +++++++++++++++++++++ 2 files changed, 27 insertions(+), 1 deletion(-) diff --git a/lib/workspace.js b/lib/workspace.js index 9cced7a..3f340b3 100644 --- a/lib/workspace.js +++ b/lib/workspace.js @@ -308,7 +308,12 @@ function patternToRegExp(pattern) { for (let index = 0; index < pattern.length; index++) { const character = pattern[index] - if (character === '*' && pattern[index + 1] === '*') { + 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] === '/' diff --git a/test/workspace.test.js b/test/workspace.test.js index 25b54fa..76a8544 100644 --- a/test/workspace.test.js +++ b/test/workspace.test.js @@ -726,6 +726,27 @@ test('getPackages expands the workspace patterns into packages', async () => { }) }) +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( From 3c5bd08bd2b95d50f3223da7ce34494dc4c156d9 Mon Sep 17 00:00:00 2001 From: versnic <37933264+versnic@users.noreply.github.com> Date: Thu, 12 Nov 2026 12:57:54 +0100 Subject: [PATCH 17/17] docs: label bigger workspaces as released in 0.11.0 --- ROADMAP.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index a08f415..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 | Released in 0.10.0 | 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,7 +179,7 @@ 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 _(released in 0.10.0)_ +## Bigger workspaces _(released in 0.11.0)_ - [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).