Skip to content

armgit / spree

Public Imported from GitHub
0

Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.

Fixed CLI `db:reset` command (#14251)

Damian Legawiec1146e78698e6
diff --git a/packages/cli/CHANGELOG.md b/packages/cli/CHANGELOG.md
index a1f3533747..5ecbbf7747 100644
--- a/packages/cli/CHANGELOG.md
+++ b/packages/cli/CHANGELOG.md
@@ -1,5 +1,11 @@
# @spree/cli
+## 2.3.5
+
+### Patch Changes
+
+- Fix `spree db:reset` and `spree console` when the stack is down or already serving. `db:reset` now self-heals from any state: it stops the web + worker containers holding open Postgres connections (which a plain `DROP DATABASE` rejects), then runs the drop/create/migrate/seed chain in a one-off `docker compose run --rm web` container whose dependencies cold-start automatically — so a reset works whether the stack is up, partially up, or fully stopped, and a stale host DB client (TablePlus/psql on port 5433) blocking the drop now produces an actionable hint instead of a raw error. `spree console` falls back to a one-off container when web is down (mirroring `spree bundle`) instead of failing, and `spree db:console` guides you to start the stack when Postgres isn't running. Both new fallbacks refuse cleanly in monorepo edge projects, consistent with the other commands.
+
## 2.3.4
### Patch Changes
diff --git a/packages/cli/package.json b/packages/cli/package.json
index adb687d455..0108e0e71b 100644
--- a/packages/cli/package.json
+++ b/packages/cli/package.json
@@ -1,6 +1,6 @@
{
"name": "@spree/cli",
- "version": "2.3.4",
+ "version": "2.3.5",
"description": "CLI for managing Spree Commerce projects",
"type": "module",
"bin": {
diff --git a/packages/cli/src/commands/bundle.ts b/packages/cli/src/commands/bundle.ts
index 6bc3568391..6f8c6cc6ed 100644
--- a/packages/cli/src/commands/bundle.ts
+++ b/packages/cli/src/commands/bundle.ts
@@ -1,14 +1,17 @@
-import * as p from '@clack/prompts'
import type { Command } from 'commander'
-import pc from 'picocolors'
-import { detectProject, hasMonorepoSpreePath } from '../context.js'
-import { dockerCompose, dockerComposeExec, isServiceRunning } from '../docker.js'
+import { detectProject } from '../context.js'
+import { dockerComposeExecOrRun } from '../docker.js'
// Run bundler inside the web container. Gems install into the bundle_cache
// volume and persist across container restarts without an image rebuild.
// spree bundle add stripe
// spree bundle update spree spree_api
// spree bundle outdated
+//
+// Gemfile.lock drift crashes the containers before `exec` can reach them —
+// exactly the state where bundler is needed most — so when web is down we fall
+// back to a one-off `compose run` container, which mounts the same bundle_cache
+// volume so gems land where the next boot expects them.
export function registerBundleCommand(program: Command): void {
program
.command('bundle')
@@ -18,31 +21,8 @@ export function registerBundleCommand(program: Command): void {
.passThroughOptions(true)
.action(async (args: string[]) => {
const ctx = detectProject()
-
- if (await isServiceRunning('web', ctx.projectDir)) {
- await dockerComposeExec(['bundle', ...args], ctx.projectDir)
- return
- }
-
- // Gemfile.lock drift crashes the containers before `exec` can reach
- // them — exactly the state where bundler is needed most. A one-off
- // `compose run` container mounts the same bundle_cache volume, so
- // gems land where the next boot expects them.
- if (hasMonorepoSpreePath(ctx.projectDir)) {
- p.cancel(
- [
- 'The web container is not running, and this is a monorepo edge project.',
- `Run ${pc.bold('pnpm server:dev')} from the monorepo root — the edge stack heals gem drift on boot.`,
- ].join('\n'),
- )
- process.exit(1)
- }
-
- p.log.info(
- 'web container is not running — using a one-off container (`docker compose run`) instead.',
- )
- await dockerCompose(['run', '--rm', 'web', 'bundle', ...args], ctx.projectDir, {
- stdio: 'inherit',
+ await dockerComposeExecOrRun(['bundle', ...args], ctx.projectDir, {
+ edgeHint: 'the edge stack heals gem drift on boot',
})
})
}
diff --git a/packages/cli/src/commands/console.ts b/packages/cli/src/commands/console.ts
index 9e9b42286d..a8472dd5d3 100644
--- a/packages/cli/src/commands/console.ts
+++ b/packages/cli/src/commands/console.ts
@@ -1,6 +1,6 @@
import type { Command } from 'commander'
import { detectProject } from '../context.js'
-import { dockerComposeExec } from '../docker.js'
+import { dockerComposeExecOrRun } from '../docker.js'
export function registerConsoleCommand(program: Command): void {
program
@@ -8,6 +8,11 @@ export function registerConsoleCommand(program: Command): void {
.description('Open Rails console')
.action(async () => {
const ctx = detectProject()
- await dockerComposeExec(['bin/rails', 'console'], ctx.projectDir)
+ // When web is down — a crash-looping container is exactly when an
+ // inspection console is most useful — fall back to a one-off `compose run`
+ // console against the same warm DB (its depends_on health-waits postgres).
+ await dockerComposeExecOrRun(['bin/rails', 'console'], ctx.projectDir, {
+ edgeHint: 'then open the console',
+ })
})
}
diff --git a/packages/cli/src/commands/db.ts b/packages/cli/src/commands/db.ts
index 6ee0971fa1..2a17543a38 100644
--- a/packages/cli/src/commands/db.ts
+++ b/packages/cli/src/commands/db.ts
@@ -1,16 +1,45 @@
import * as p from '@clack/prompts'
import type { Command } from 'commander'
-import { detectProject } from '../context.js'
-import { dockerComposeExec } from '../docker.js'
+import pc from 'picocolors'
+import { detectProject, hasMonorepoSpreePath } from '../context.js'
+import { dockerCompose, dockerComposeExec, dockerComposeRun, isServiceRunning } from '../docker.js'
+
+export const RESET_TASK = [
+ 'bin/rails',
+ 'db:drop',
+ 'db:create',
+ 'spree:install:migrations',
+ 'db:migrate',
+ 'db:seed',
+]
export function registerDbCommand(program: Command): void {
program
.command('db:reset')
- .description('Drop, create, migrate, and seed the dev database (destructive)')
+ .description(
+ 'Drop, create, migrate, and seed the dev database (destructive; self-heals a running stack)',
+ )
.option('--yes', 'skip the confirmation prompt (for CI)')
.action(async (flags: { yes?: boolean }) => {
const ctx = detectProject()
+ const refuse = (lines: string[]): never => {
+ p.cancel(lines.join('\n'))
+ process.exit(1)
+ }
+
+ // `compose run` materializes the project-local docker-compose.yml, which
+ // is not the running edge config — refuse like bundle.ts / upgrade.ts.
+ // The edge stack heals its own dev DB via `pnpm server:*`.
+ if (hasMonorepoSpreePath(ctx.projectDir)) {
+ refuse([
+ 'This is a monorepo edge project (SPREE_PATH set in .env).',
+ `Reset the dev database from the monorepo root with ${pc.bold('pnpm server:setup')}`,
+ '(or the relevant `pnpm server:*` script) — the project-local compose is not the',
+ 'running config here.',
+ ])
+ }
+
if (!flags.yes) {
const confirmed = await p.confirm({
message: 'This will drop the spree_development database. Continue?',
@@ -22,10 +51,69 @@ export function registerDbCommand(program: Command): void {
}
}
- await dockerComposeExec(
- ['bin/rails', 'db:drop', 'db:create', 'spree:install:migrations', 'db:migrate', 'db:seed'],
- ctx.projectDir,
- )
+ // The long-running web (Rails) + worker (Sidekiq) containers hold pooled
+ // connections to spree_development. Rails' db:drop issues a PLAIN
+ // `DROP DATABASE` (no WITH FORCE), which PostgreSQL rejects while any other
+ // session is connected — so a reset against a running stack deadlocks. We
+ // stop both regardless of which is up (the worker alone holds up to
+ // RAILS_MAX_THREADS pooled connections), so we only need to know if either
+ // is running; probe them concurrently.
+ let stackUp: boolean
+ try {
+ const [webUp, workerUp] = await Promise.all([
+ isServiceRunning('web', ctx.projectDir),
+ isServiceRunning('worker', ctx.projectDir),
+ ])
+ stackUp = webUp || workerUp
+ } catch (err) {
+ // `compose ps` itself failed: broken/stale compose, daemon down, unknown
+ // service. Point home rather than dumping the raw env-file error (mirrors
+ // upgrade.ts; backstop for a stale backend/ past detectProject re-rooting).
+ // `return` is load-bearing: it tells TS `stackUp` is assigned past here.
+ return refuse([
+ 'Could not inspect the Docker stack from this directory.',
+ ` ${pc.dim(String((err as Error).message).split('\n')[0])}`,
+ '',
+ `Run ${pc.bold('spree db:reset')} from your project root (the directory holding the`,
+ '.env with SECRET_KEY_BASE), and make sure Docker is running.',
+ ])
+ }
+
+ if (stackUp) {
+ const s = p.spinner()
+ s.start('Stopping web + worker to release database connections...')
+ await dockerCompose(['stop', 'web', 'worker'], ctx.projectDir)
+ s.stop('Stopped web + worker.')
+ }
+
+ try {
+ // One-off container: `run`'s depends_on cold-starts postgres (and waits
+ // for service_healthy) but never restarts web/worker, so nothing reopens
+ // a blocking connection. Works whether the stack was up, down, or partial.
+ // captureStderr so the Postgres "being accessed" error below is matchable.
+ await dockerComposeRun(RESET_TASK, ctx.projectDir, { captureStderr: true })
+ } catch (err) {
+ const stderr = String((err as { stderr?: string }).stderr ?? (err as Error).message ?? '')
+ if (/being accessed by other users|55006/.test(stderr)) {
+ // We stopped the app containers, so the remaining connection is a host
+ // client we can't see or stop (TablePlus/DataGrip/psql on port 5433).
+ // If we stopped the stack to get here, also tell them how to restore it.
+ refuse([
+ 'Could not drop spree_development — another client is still connected.',
+ `A database client (TablePlus, DataGrip, psql) may be connected on port ${pc.bold('5433')}.`,
+ 'Disconnect it, then re-run `spree db:reset`.',
+ ...(stackUp ? ['', `Bring the stack back up with ${pc.bold('spree dev')}.`] : []),
+ ])
+ }
+ throw err
+ }
+
+ p.log.success('Database reset.')
+ if (stackUp) {
+ // We stopped the operator's running stack to free the drop — they may not
+ // realize it, so tell them how to bring it back.
+ p.note(`Bring the stack back up with ${pc.bold('spree dev')}.`, 'Done')
+ }
})
program
@@ -33,6 +121,35 @@ export function registerDbCommand(program: Command): void {
.description('Open a psql session against the dev database')
.action(async () => {
const ctx = detectProject()
+
+ // psql needs a live postgres. postgres usually stays warm even when web is
+ // down, so guide rather than guess if it isn't running — never `compose run`
+ // here, which would start an empty server racing the psql shell.
+ let postgresUp: boolean
+ try {
+ postgresUp = await isServiceRunning('postgres', ctx.projectDir)
+ } catch (err) {
+ p.cancel(
+ [
+ 'Could not inspect the Docker stack from this directory.',
+ ` ${pc.dim(String((err as Error).message).split('\n')[0])}`,
+ '',
+ `Run ${pc.bold('spree db:console')} from your project root, and make sure Docker is running.`,
+ ].join('\n'),
+ )
+ process.exit(1)
+ }
+
+ if (!postgresUp) {
+ p.cancel(
+ [
+ 'Postgres is not running.',
+ `Start the stack with ${pc.bold('spree dev')}, then re-run ${pc.bold('spree db:console')}.`,
+ ].join('\n'),
+ )
+ process.exit(1)
+ }
+
await dockerComposeExec(['psql', '-U', 'postgres', 'spree_development'], ctx.projectDir, {
service: 'postgres',
})
diff --git a/packages/cli/src/docker.ts b/packages/cli/src/docker.ts
index f7b4c2103d..951d1591f8 100644
--- a/packages/cli/src/docker.ts
+++ b/packages/cli/src/docker.ts
@@ -1,4 +1,7 @@
+import * as p from '@clack/prompts'
import { type Options as ExecaOptions, execa } from 'execa'
+import pc from 'picocolors'
+import { hasMonorepoSpreePath } from './context.js'
export async function dockerCompose(args: string[], projectDir: string, options?: ExecaOptions) {
return execa('docker', ['compose', ...args], {
@@ -109,6 +112,96 @@ export async function dockerComposeExec(
await execa('docker', args, { cwd: projectDir, stdio: 'inherit' })
}
+export interface DockerComposeRunOptions {
+ service?: string
+ env?: Record<string, string>
+ // Also buffer the child's stderr into the thrown ExecaError so the caller can
+ // inspect failure output. Off by default: plain `stdio: 'inherit'` is right
+ // for interactive sessions (a Rails console's TTY) and leaves stderr
+ // unbuffered. db:reset opts in because it pattern-matches the Postgres error.
+ captureStderr?: boolean
+}
+
+// Run a command in a one-off `compose run --rm` container — the twin of
+// dockerComposeExec for when the service's long-running container is NOT up.
+// Unlike `exec`, `run` builds a fresh container and (in Compose v2) starts the
+// service's depends_on (postgres/redis/meilisearch), honoring their
+// `condition: service_healthy` healthchecks before the command runs — so it
+// works from a fully cold stack. We deliberately omit `--no-deps` (we WANT
+// those deps started + health-waited) and `--service-ports` (these callers
+// publish nothing, and skipping it avoids colliding with a running web's
+// ports). `--rm` removes only this one-off container on exit; the deps it
+// started are left warm for the next boot.
+//
+// stdio is inherited so the command stays transparent: an interactive console
+// keeps its TTY, db:seed streams progress, and the inner exit code propagates.
+// With `captureStderr`, stderr is teed to `['pipe', 'inherit']` — still printed
+// live, but also buffered onto ExecaError.stderr (plain `'inherit'` would leave
+// it undefined, so the caller's error inspection would see nothing).
+export async function dockerComposeRun(
+ argv: string[],
+ projectDir: string,
+ options: DockerComposeRunOptions = {},
+): Promise<void> {
+ const { service = 'web', env, captureStderr = false } = options
+ const args = ['compose', 'run', '--rm']
+ if (env) {
+ for (const [key, value] of Object.entries(env)) {
+ args.push('-e', `${key}=${value}`)
+ }
+ }
+ args.push(service, ...argv)
+
+ const stdio: ExecaOptions = captureStderr
+ ? { stdin: 'inherit', stdout: 'inherit', stderr: ['pipe', 'inherit'] }
+ : { stdio: 'inherit' }
+ await execa('docker', args, { cwd: projectDir, ...stdio })
+}
+
+export interface DockerComposeExecOrRunOptions {
+ service?: string
+ env?: Record<string, string>
+ // Extra line appended to the monorepo-edge refusal, after the generic
+ // "run pnpm server:dev from the monorepo root" sentence — lets a caller add
+ // command-specific context (e.g. bundle's "the edge stack heals gem drift").
+ edgeHint?: string
+}
+
+// Run a command in the service's container, transparently falling back to a
+// one-off `compose run` when the long-running container is down. This is the
+// shared shape behind `spree bundle` and `spree console`: exec into the live
+// container if it's up, otherwise boot a fresh one-off against the same warm
+// DB/volumes. A monorepo edge project (SPREE_PATH in .env) is refused, because
+// `run` materializes the project-local compose, which is not the running edge
+// config — there the operator must use `pnpm server:*` from the monorepo root.
+export async function dockerComposeExecOrRun(
+ argv: string[],
+ projectDir: string,
+ options: DockerComposeExecOrRunOptions = {},
+): Promise<void> {
+ const { service = 'web', env, edgeHint } = options
+
+ if (await isServiceRunning(service, projectDir)) {
+ await dockerComposeExec(argv, projectDir, { service, env })
+ return
+ }
+
+ if (hasMonorepoSpreePath(projectDir)) {
+ p.cancel(
+ [
+ `The ${service} container is not running, and this is a monorepo edge project.`,
+ `Run ${pc.bold('pnpm server:dev')} from the monorepo root${edgeHint ? ` — ${edgeHint}` : ''}.`,
+ ].join('\n'),
+ )
+ process.exit(1)
+ }
+
+ p.log.info(
+ `${service} container is not running — using a one-off container (\`docker compose run\`) instead.`,
+ )
+ await dockerComposeRun(argv, projectDir, { service, env })
+}
+
export async function streamLogs(service: string, projectDir: string): Promise<void> {
await execa('docker', ['compose', 'logs', '-f', service], {
cwd: projectDir,
diff --git a/packages/cli/tests/console.test.ts b/packages/cli/tests/console.test.ts
new file mode 100644
index 0000000000..987c404247
--- /dev/null
+++ b/packages/cli/tests/console.test.ts
@@ -0,0 +1,42 @@
+import { Command } from 'commander'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { registerConsoleCommand } from '../src/commands/console'
+import { dockerComposeExecOrRun } from '../src/docker'
+
+let projectDir: string
+
+vi.mock('../src/context', () => ({
+ detectProject: () => ({ mode: 'docker', projectDir, port: 3000 }),
+}))
+
+vi.mock('../src/docker', () => ({
+ dockerComposeExecOrRun: vi.fn().mockResolvedValue(undefined),
+}))
+
+async function runConsole(): Promise<void> {
+ const program = new Command()
+ registerConsoleCommand(program)
+ await program.parseAsync(['console'], { from: 'user' })
+}
+
+describe('spree console', () => {
+ beforeEach(() => {
+ projectDir = '/proj'
+ vi.clearAllMocks()
+ })
+
+ afterEach(() => {
+ vi.restoreAllMocks()
+ })
+
+ // Branching (exec vs one-off run vs monorepo-edge refusal) is covered by
+ // dockerComposeExecOrRun's own tests in docker.test.ts; here we only assert
+ // the command delegates with the right argv + edge hint.
+ it('delegates to dockerComposeExecOrRun with the console command', async () => {
+ await runConsole()
+
+ expect(dockerComposeExecOrRun).toHaveBeenCalledWith(['bin/rails', 'console'], '/proj', {
+ edgeHint: 'then open the console',
+ })
+ })
+})
diff --git a/packages/cli/tests/db.test.ts b/packages/cli/tests/db.test.ts
new file mode 100644
index 0000000000..1f6762fc30
--- /dev/null
+++ b/packages/cli/tests/db.test.ts
@@ -0,0 +1,201 @@
+import { Command } from 'commander'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { RESET_TASK, registerDbCommand } from '../src/commands/db'
+import { dockerCompose, dockerComposeExec, dockerComposeRun, isServiceRunning } from '../src/docker'
+
+let projectDir: string
+let monorepoEdge = false
+
+vi.mock('../src/context', () => ({
+ detectProject: () => ({ mode: 'docker', projectDir, port: 3000 }),
+ hasMonorepoSpreePath: () => monorepoEdge,
+}))
+
+vi.mock('../src/docker', () => ({
+ dockerCompose: vi.fn().mockResolvedValue(undefined),
+ dockerComposeExec: vi.fn().mockResolvedValue(undefined),
+ dockerComposeRun: vi.fn().mockResolvedValue(undefined),
+ isServiceRunning: vi.fn().mockResolvedValue(false),
+}))
+
+// p.confirm/p.spinner/p.cancel are not exercised here beyond not crashing; the
+// default --yes path skips the prompt. Stub the interactive surface so the
+// non-yes test can drive confirm.
+const confirmMock = vi.fn()
+const cancelMock = vi.fn()
+vi.mock('@clack/prompts', () => ({
+ confirm: (...args: unknown[]) => confirmMock(...args),
+ isCancel: (v: unknown) => v === CANCEL,
+ cancel: (...args: unknown[]) => cancelMock(...args),
+ log: { success: vi.fn(), info: vi.fn() },
+ note: vi.fn(),
+ spinner: () => ({ start: vi.fn(), stop: vi.fn() }),
+}))
+
+const CANCEL = Symbol('cancel')
+
+class ExitError extends Error {
+ constructor(public code: number) {
+ super(`process.exit(${code})`)
+ }
+}
+
+async function runDbReset(...argv: string[]): Promise<void> {
+ const program = new Command()
+ registerDbCommand(program)
+ await program.parseAsync(['db:reset', ...argv], { from: 'user' })
+}
+
+async function runDbConsole(): Promise<void> {
+ const program = new Command()
+ registerDbCommand(program)
+ await program.parseAsync(['db:console'], { from: 'user' })
+}
+
+describe('spree db:reset', () => {
+ beforeEach(() => {
+ projectDir = '/proj'
+ monorepoEdge = false
+ vi.clearAllMocks()
+ vi.mocked(isServiceRunning).mockResolvedValue(false)
+ vi.spyOn(process, 'exit').mockImplementation((code?: number) => {
+ throw new ExitError(code ?? 0)
+ })
+ })
+
+ afterEach(() => {
+ vi.restoreAllMocks()
+ })
+
+ it('runs the reset chain in a one-off container when the stack is fully down', async () => {
+ vi.mocked(isServiceRunning).mockResolvedValue(false)
+
+ await runDbReset('--yes')
+
+ expect(dockerComposeRun).toHaveBeenCalledWith(RESET_TASK, '/proj', { captureStderr: true })
+ // Nothing to stop when the stack is already down.
+ expect(dockerCompose).not.toHaveBeenCalled()
+ })
+
+ it('stops web + worker before the reset when the stack is up', async () => {
+ vi.mocked(isServiceRunning).mockResolvedValue(true)
+
+ await runDbReset('--yes')
+
+ expect(dockerCompose).toHaveBeenCalledWith(['stop', 'web', 'worker'], '/proj')
+ expect(dockerComposeRun).toHaveBeenCalledWith(RESET_TASK, '/proj', { captureStderr: true })
+ // stop must precede the destructive run.
+ const stopOrder = vi.mocked(dockerCompose).mock.invocationCallOrder[0]
+ const runOrder = vi.mocked(dockerComposeRun).mock.invocationCallOrder[0]
+ expect(stopOrder).toBeLessThan(runOrder)
+ })
+
+ it('stops both even when only the worker is running', async () => {
+ vi.mocked(isServiceRunning).mockImplementation(async (service: string) => service === 'worker')
+
+ await runDbReset('--yes')
+
+ expect(dockerCompose).toHaveBeenCalledWith(['stop', 'web', 'worker'], '/proj')
+ expect(dockerComposeRun).toHaveBeenCalledWith(RESET_TASK, '/proj', { captureStderr: true })
+ })
+
+ it('refuses in a monorepo edge project before touching the stack', async () => {
+ monorepoEdge = true
+
+ await expect(runDbReset('--yes')).rejects.toBeInstanceOf(ExitError)
+
+ expect(isServiceRunning).not.toHaveBeenCalled()
+ expect(dockerCompose).not.toHaveBeenCalled()
+ expect(dockerComposeRun).not.toHaveBeenCalled()
+ })
+
+ it('refuses with a friendly message when `compose ps` itself fails', async () => {
+ vi.mocked(isServiceRunning).mockRejectedValue(new Error('Cannot connect to the Docker daemon'))
+
+ await expect(runDbReset('--yes')).rejects.toMatchObject({ code: 1 })
+
+ expect(dockerCompose).not.toHaveBeenCalled()
+ expect(dockerComposeRun).not.toHaveBeenCalled()
+ })
+
+ it('cancels without running anything when the operator declines the prompt', async () => {
+ confirmMock.mockResolvedValue(false)
+
+ await expect(runDbReset()).rejects.toMatchObject({ code: 0 })
+
+ expect(dockerComposeRun).not.toHaveBeenCalled()
+ })
+
+ it('surfaces a host-client hint when the drop fails on an active connection', async () => {
+ vi.mocked(isServiceRunning).mockResolvedValue(false)
+ vi.mocked(dockerComposeRun).mockRejectedValue(
+ Object.assign(new Error('rails aborted'), {
+ stderr: 'ERROR: database "spree_development" is being accessed by other users',
+ }),
+ )
+
+ // The 55006 branch refuses with exit(1) rather than re-throwing the raw error.
+ await expect(runDbReset('--yes')).rejects.toMatchObject({ code: 1 })
+ expect(cancelMock).toHaveBeenCalledWith(expect.stringContaining('still connected'))
+ // Stack was already down, so no restore-stack hint.
+ expect(cancelMock.mock.calls[0][0]).not.toContain('spree dev')
+ })
+
+ it('adds the restore-stack hint to the host-client refusal when the stack was stopped', async () => {
+ // Stack up → reset stops web+worker, then the drop is still blocked by a host
+ // client. The refusal must also tell the operator how to restore the stack.
+ vi.mocked(isServiceRunning).mockResolvedValue(true)
+ vi.mocked(dockerComposeRun).mockRejectedValue(
+ Object.assign(new Error('rails aborted'), {
+ stderr: 'ERROR: database "spree_development" is being accessed by other users',
+ }),
+ )
+
+ await expect(runDbReset('--yes')).rejects.toMatchObject({ code: 1 })
+ expect(cancelMock).toHaveBeenCalledWith(expect.stringContaining('still connected'))
+ expect(cancelMock.mock.calls[0][0]).toContain('spree dev')
+ })
+
+ it('re-throws a non-connection failure from the reset chain', async () => {
+ vi.mocked(isServiceRunning).mockResolvedValue(false)
+ vi.mocked(dockerComposeRun).mockRejectedValue(new Error('boom: migration failed'))
+
+ await expect(runDbReset('--yes')).rejects.toThrow(/migration failed/)
+ })
+})
+
+describe('spree db:console', () => {
+ beforeEach(() => {
+ projectDir = '/proj'
+ monorepoEdge = false
+ vi.clearAllMocks()
+ vi.mocked(isServiceRunning).mockResolvedValue(true)
+ vi.spyOn(process, 'exit').mockImplementation((code?: number) => {
+ throw new ExitError(code ?? 0)
+ })
+ })
+
+ afterEach(() => {
+ vi.restoreAllMocks()
+ })
+
+ it('opens psql against the postgres service when it is running', async () => {
+ vi.mocked(isServiceRunning).mockResolvedValue(true)
+
+ await runDbConsole()
+
+ expect(dockerComposeExec).toHaveBeenCalledWith(
+ ['psql', '-U', 'postgres', 'spree_development'],
+ '/proj',
+ { service: 'postgres' },
+ )
+ })
+
+ it('refuses with a start-the-stack hint when postgres is down', async () => {
+ vi.mocked(isServiceRunning).mockResolvedValue(false)
+
+ await expect(runDbConsole()).rejects.toMatchObject({ code: 1 })
+
+ expect(dockerComposeExec).not.toHaveBeenCalled()
+ })
+})
diff --git a/packages/cli/tests/docker.test.ts b/packages/cli/tests/docker.test.ts
new file mode 100644
index 0000000000..bb0aa8f380
--- /dev/null
+++ b/packages/cli/tests/docker.test.ts
@@ -0,0 +1,186 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+
+vi.mock('execa', () => ({ execa: vi.fn().mockResolvedValue({ stdout: '' }) }))
+
+let monorepoEdge = false
+vi.mock('../src/context', () => ({
+ hasMonorepoSpreePath: () => monorepoEdge,
+}))
+
+const cancelMock = vi.fn()
+const logInfoMock = vi.fn()
+vi.mock('@clack/prompts', () => ({
+ cancel: (...args: unknown[]) => cancelMock(...args),
+ log: { info: (...args: unknown[]) => logInfoMock(...args) },
+}))
+
+import { execa } from 'execa'
+import { dockerComposeExecOrRun, dockerComposeRun } from '../src/docker'
+
+const mockExeca = vi.mocked(execa)
+
+// `dockerComposeExecOrRun` makes several `execa` calls (the `compose ps` probe,
+// then `exec`/`run`). Route by args: the probe contains `ps`, everything else
+// is the command itself. Lets a single mock drive web-up vs web-down.
+function routeExeca(webUp: boolean): void {
+ mockExeca.mockImplementation((async (_cmd: string, args: string[]) => {
+ if (args.includes('ps')) return { stdout: webUp ? 'running' : '' }
+ return { stdout: '' }
+ }) as never)
+}
+
+describe('dockerComposeRun', () => {
+ afterEach(() => mockExeca.mockReset())
+
+ it('builds `compose run --rm <service> <argv>` with inherited stdio', async () => {
+ await dockerComposeRun(['bin/rails', 'console'], '/proj')
+
+ expect(mockExeca).toHaveBeenCalledWith(
+ 'docker',
+ ['compose', 'run', '--rm', 'web', 'bin/rails', 'console'],
+ { cwd: '/proj', stdio: 'inherit' },
+ )
+ })
+
+ it('honors a non-default service', async () => {
+ await dockerComposeRun(['psql'], '/proj', { service: 'postgres' })
+
+ expect(mockExeca).toHaveBeenCalledWith(
+ 'docker',
+ ['compose', 'run', '--rm', 'postgres', 'psql'],
+ { cwd: '/proj', stdio: 'inherit' },
+ )
+ })
+
+ it('threads -e KEY=VALUE pairs before the service, like dockerComposeExec', async () => {
+ await dockerComposeRun(['bin/rake', 'spree:upgrade'], '/proj', {
+ env: { DRY_RUN: '1', STEP: 'channels' },
+ })
+
+ expect(mockExeca).toHaveBeenCalledWith(
+ 'docker',
+ [
+ 'compose',
+ 'run',
+ '--rm',
+ '-e',
+ 'DRY_RUN=1',
+ '-e',
+ 'STEP=channels',
+ 'web',
+ 'bin/rake',
+ 'spree:upgrade',
+ ],
+ { cwd: '/proj', stdio: 'inherit' },
+ )
+ })
+
+ it('does not pass --no-deps (deps must start + health-wait)', async () => {
+ await dockerComposeRun(['bin/rails', 'db:drop'], '/proj')
+
+ const [, args] = mockExeca.mock.calls[0] as [string, string[]]
+ expect(args).not.toContain('--no-deps')
+ })
+
+ it('inherits stdio wholesale by default (no stderr capture)', async () => {
+ await dockerComposeRun(['bin/rails', 'console'], '/proj')
+
+ const [, , opts] = mockExeca.mock.calls[0] as [string, string[], Record<string, unknown>]
+ expect(opts).toMatchObject({ cwd: '/proj', stdio: 'inherit' })
+ })
+
+ it('tees stderr to `[pipe, inherit]` when captureStderr is set', async () => {
+ // Plain `stdio: inherit` leaves ExecaError.stderr undefined; the tee keeps it
+ // printed live AND buffered so db:reset can match the Postgres error.
+ await dockerComposeRun(['bin/rails', 'db:drop'], '/proj', { captureStderr: true })
+
+ const [, , opts] = mockExeca.mock.calls[0] as [string, string[], Record<string, unknown>]
+ expect(opts).toMatchObject({
+ cwd: '/proj',
+ stdin: 'inherit',
+ stdout: 'inherit',
+ stderr: ['pipe', 'inherit'],
+ })
+ expect(opts).not.toHaveProperty('stdio')
+ })
+})
+
+describe('dockerComposeExecOrRun', () => {
+ class ExitError extends Error {
+ constructor(public code: number) {
+ super(`process.exit(${code})`)
+ }
+ }
+
+ beforeEach(() => {
+ monorepoEdge = false
+ cancelMock.mockClear()
+ logInfoMock.mockClear()
+ mockExeca.mockReset()
+ vi.spyOn(process, 'exit').mockImplementation((code?: number) => {
+ throw new ExitError(code ?? 0)
+ })
+ })
+
+ afterEach(() => vi.restoreAllMocks())
+
+ it('execs into the running container when the service is up', async () => {
+ routeExeca(true)
+
+ await dockerComposeExecOrRun(['bin/rails', 'console'], '/proj')
+
+ expect(mockExeca).toHaveBeenCalledWith(
+ 'docker',
+ ['compose', 'exec', 'web', 'bin/rails', 'console'],
+ { cwd: '/proj', stdio: 'inherit' },
+ )
+ expect(mockExeca).not.toHaveBeenCalledWith(
+ 'docker',
+ expect.arrayContaining(['run']),
+ expect.anything(),
+ )
+ })
+
+ it('falls back to a one-off `run` container when the service is down', async () => {
+ routeExeca(false)
+
+ await dockerComposeExecOrRun(['bin/rails', 'console'], '/proj')
+
+ expect(mockExeca).toHaveBeenCalledWith(
+ 'docker',
+ ['compose', 'run', '--rm', 'web', 'bin/rails', 'console'],
+ { cwd: '/proj', stdio: 'inherit' },
+ )
+ expect(logInfoMock).toHaveBeenCalled()
+ })
+
+ it('refuses the one-off fallback in a monorepo edge project', async () => {
+ routeExeca(false)
+ monorepoEdge = true
+
+ await expect(dockerComposeExecOrRun(['bin/rails', 'console'], '/proj')).rejects.toMatchObject({
+ code: 1,
+ })
+
+ expect(cancelMock).toHaveBeenCalled()
+ expect(mockExeca).not.toHaveBeenCalledWith(
+ 'docker',
+ expect.arrayContaining(['run']),
+ expect.anything(),
+ )
+ })
+
+ it('appends the edgeHint to the monorepo-edge refusal message', async () => {
+ routeExeca(false)
+ monorepoEdge = true
+
+ await expect(
+ dockerComposeExecOrRun(['bundle', 'install'], '/proj', {
+ edgeHint: 'the edge stack heals gem drift on boot',
+ }),
+ ).rejects.toMatchObject({ code: 1 })
+
+ const [message] = cancelMock.mock.calls[0] as [string]
+ expect(message).toContain('the edge stack heals gem drift on boot')
+ })
+})