Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/PULL_REQUEST_TEMPLATE.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,6 @@

- [ ] The title follows Conventional Commits (`feat:`, `fix:`, `docs:`, …) and is lowercase
- [ ] Tests cover the change, or it needs none
- [ ] The README describes the change, and the header comment of each touched `lib/` file is up to date
- [ ] The README describes the change
- [ ] The roadmap is updated if this completes a roadmap item
- [ ] Tested in a real terminal with a temporary configuration (`DEV_WORKSPACE_CONFIG`), if the change affects what the CLI shows or does
2 changes: 1 addition & 1 deletion CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ Menus use the list in `list.js`, which owns the terminal while it is open; free-

Every colour comes from the theme in `ui.js`: `color()` for plain output, `styleText()` for the list, and `inquirerTheme()` for the `@inquirer/prompts` questions. Do not write ANSI codes elsewhere, so `NO_COLOR` and `FORCE_COLOR` are always respected. Ask for the `accent` style, never for cyan or another colour by name, so the user's chosen accent (`setAccent()`) reaches every screen.

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.
Each file in `lib/` starts with two comment lines: what the file is for, and which files use it. Update them only if your change makes them wrong, for example a new file that imports it. Explain how something works in a comment next to the code instead, where it is easier to keep right.

Modules receive their side effects (file system, prompts, process spawning) as parameters with real defaults, so tests can replace them with fakes. Tests live in `test/`, one file per module.

Expand Down
18 changes: 7 additions & 11 deletions lib/aliases.js
Original file line number Diff line number Diff line change
@@ -1,14 +1,5 @@
// Custom command aliases (`--add-alias`, `--remove-alias`, `--list-aliases`).
//
// An alias is a small launcher file written next to the installed
// `dev-workspace` command, which is found by searching PATH. On Windows each
// alias has three launchers (cmd, PowerShell, Git Bash); elsewhere one shell
// script. Every launcher carries a marker comment, so listing and removing
// only ever touch files this module created. The built-in `dws` command is
// not an alias: it comes from the `bin` field in package.json.
//
// Used by cli.js. Every exported function accepts `{ env, platform }` so tests
// can simulate any operating system and PATH.
// Custom command aliases: `--add-alias`, `--remove-alias` and `--list-aliases`.
// Used by cli.js.

import { chmod, readdir, readFile, rm, stat, writeFile } from 'node:fs/promises'
import path from 'node:path'
Expand Down Expand Up @@ -71,6 +62,11 @@ async function isFile(file) {
}
}

// An alias is a launcher file written next to the installed `dev-workspace`
// command: three on Windows (cmd, PowerShell, Git Bash), one shell script
// elsewhere. Every exported function takes `{ env, platform }`, so tests can
// simulate any system and PATH.
//
// Return the first file on PATH that runs as `name`, or null.
export async function findCommand(name, options) {
const settings = defaults(options)
Expand Down
24 changes: 4 additions & 20 deletions lib/args.js
Original file line number Diff line number Diff line change
@@ -1,28 +1,12 @@
// Command-line parsing and the `--help` text.
//
// parseCliArgs() turns process arguments into an options object using Node's
// built-in parseArgs, and replaces its errors with a message pointing to
// `--help`. Up to two positional arguments select a project and a script
// (direct mode); everything after `--` is kept, untouched, as the script's
// arguments.
//
// formatHelp() builds the `--help` text, which must list every option defined
// 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.
//
// splitArguments() splits arguments typed at the "Run with arguments…" prompt
// into a list, honouring single and double quotes. No shell is involved, so
// nothing else is special.
//
// Used by cli.js, whose start() decides what each option does, and by
// prompts.js.
// Reading the command-line options, and the `--help` text.
// Used by cli.js and prompts.js.

import { parseArgs } from 'node:util'

import { ACCENTS } from './ui.js'

// The `--help` text, which must list every option parseCliArgs() accepts.
// `color` is ui.color, so NO_COLOR and the accent are respected.
export function formatHelp(color = value => String(value)) {
return `
${color('Usage:', 'bold')} ${color('dev-workspace', 'accent')} [options] [project [script] [-- arguments]]
Expand Down
69 changes: 2 additions & 67 deletions lib/cli.js
Original file line number Diff line number Diff line change
@@ -1,70 +1,5 @@
// The CLI itself: option handling, workspace setup and the interactive menus.
//
// 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
// 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.
// 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.
// Changing the workspace from the project list (⚙ Workspace) opens the same
// list, and Escape there, or at the path prompt, keeps the current one.
// Workspace paths typed at the prompt or passed with --workspace go through
// resolveDirectoryInput(), so ~, quotes and escaped spaces work without a
// shell.
//
// 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!".
//
// The run screen, on the normal screen: the header box with the project and
// script as breadcrumb (ui.drawHeader, drawn once with list.js), the command
// (`▶ npm run build`), the script's output, then the result: `✔ build
// finished in 4.2s` in green, or `✖ build failed · exit 1 · 0.8s` in red,
// with the signal name in place of the exit code when a signal stopped it.
// The duration is measured with clock.now() and shown by formatDuration().
// The Run again / Back to scripts buttons follow (waitAfterCommand).
//
// Menus and questions need a terminal for input: without one, and without
// a script to run directly, run() fails with a message saying so.
//
// Direct mode: `dev-workspace <project>` opens that project's scripts, and
// `dev-workspace <project> <script> [-- args]` runs the script without any
// menu or prompt and resolves with its exit code (128 + the signal number
// when a signal stopped it), which index.js uses as the process exit code.
// The project is found by exact name, then ignoring case, then by unique
// prefix (findProject).
//
// 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
// script may have changed them.
//
// The history (state.js) records each opened project and run script; it is
// read once per run, and saving it never stops the CLI.
//
// Menus use the mouse unless --no-mouse (this run) or `"mouse": false` in
// the configuration (saved with --set-mouse off) turns it off, input or
// output is not a terminal, or the terminal (terminal.js) reports no mouse
// events. In a terminal without full support, the first menu shows a note
// from mouseNote(), once per terminal: the history records it when a menu
// shows it.
//
// Every side effect goes through a dependency group (aliases, config,
// history, terminal, workspace, commands, prompts, ui, clock, output) that
// createCli() accepts as overrides, so tests drive the whole flow with
// fakes. index.js calls startCli(), which uses the real modules and process
// arguments.
// The CLI itself: the options, the workspace setup, the menus and direct mode.
// Used by index.js.

import { createRequire } from 'node:module'
import os from 'node:os'
Expand Down
14 changes: 1 addition & 13 deletions lib/commands.js
Original file line number Diff line number Diff line change
@@ -1,17 +1,5 @@
// Running a project's script with its package manager.
//
// runCommand() starts `<tool> run <script>` (npm, pnpm, yarn or bun), with
// any extra arguments for the script (`args`), in the project directory with
// the terminal attached, without a shell (cross-spawn handles Windows .cmd
// files), and resolves with the exit code or signal once the script ends. A
// missing tool produces an error with an install hint. Node.js reports a
// missing project folder with the same ENOENT error, so the folder is checked
// before blaming the tool.
//
// Used by cli.js, which passes the tool chosen by detectPackageManager(), and
// `classicYarn` for Yarn 1, which needs extra arguments passed differently.
// The spawn function, signal source, folder check and Node.js version (which
// changes the install hint) can be injected for tests.
// Used by cli.js.

import spawn from 'cross-spawn'

Expand Down
26 changes: 6 additions & 20 deletions lib/config.js
Original file line number Diff line number Diff line change
@@ -1,23 +1,4 @@
// The saved configuration: where it lives, and reading, writing and deleting it.
//
// The file is stored in the platform's config directory (%APPDATA%,
// ~/Library/Preferences or $XDG_CONFIG_HOME), outside the package so it
// survives updates and uninstalls. DEV_WORKSPACE_CONFIG overrides the path;
// getConfigPaths() then reports `custom: true`, which state.js uses to name
// the history file.
// 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:
// `{ "workspace": "<path>", "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
// workspace counts as no workspace configured yet. A file
// saved with a UTF-8 byte order mark, as some editors do, is read normally.
// The configuration file: where it lives, and reading and saving it.
// Used by cli.js.

import {
Expand Down Expand Up @@ -113,6 +94,11 @@ export async function migrateLegacyConfig({ file, legacyFile }) {
return legacyFile
}

// The file looks like this; every key but `workspace` is optional, and
// saving one setting keeps the others:
//
// { "workspace": "<path>", "color": "cyan", "mouse": false }
//
// Return null when no configuration exists yet.
// Invalid configuration should produce an actionable error.
export async function readWorkspaceConfig(configFile) {
Expand Down
15 changes: 1 addition & 14 deletions lib/fuzzy.js
Original file line number Diff line number Diff line change
@@ -1,17 +1,4 @@
// Fuzzy matching for the search in the project and script lists.
//
// fuzzyMatch() checks whether every character of the query appears in the
// text in order (a subsequence, ignoring case) and scores the best such
// alignment: matches at the start of the text, at the start of a word (after
// - _ . / @ or a space, or a camelCase capital) and runs of consecutive
// characters score higher, gaps between matches lower. It also returns the
// matched positions, so the list can highlight them. Positions count
// characters as [...text] does, so an emoji, or a letter whose lowercase is
// longer (İ), never shifts the highlight.
//
// fuzzyFilter() keeps the items that match and sorts them best first; equal
// scores keep the shorter text first, then the original order.
//
// Fuzzy matching for the search in the menus.
// Used by list.js.

const BONUS_START = 10
Expand Down
13 changes: 4 additions & 9 deletions lib/json.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,8 @@
// Parsing JSON files the way npm reads them.
//
// parseJson() is JSON.parse() after removing a leading UTF-8 byte order mark
// (U+FEFF). Windows PowerShell 5.1 and some editors write one at the start of
// a file; JSON.parse() rejects it, while npm ignores it. A U+FEFF anywhere
// else, such as inside a string value, is kept.
//
// Used by config.js, package-managers.js and workspace.js, which keep their
// own error messages.
// Reading JSON the way npm does, ignoring a leading byte order mark.
// Used by config.js, package-managers.js, state.js and workspace.js.

// JSON.parse() after removing a leading U+FEFF, which Windows PowerShell 5.1
// and some editors write and npm ignores.
export function parseJson(text) {
return JSON.parse(text.startsWith('\uFEFF') ? text.slice(1) : text)
}
Loading
Loading