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.

Add one-off container fallback to all app-facing commands (#14347)

Damian Legawieca4c464799962
diff --git a/packages/cli/CHANGELOG.md b/packages/cli/CHANGELOG.md
index adeb1d97b4..037ca2a309 100644
--- a/packages/cli/CHANGELOG.md
+++ b/packages/cli/CHANGELOG.md
@@ -1,5 +1,11 @@
# @spree/cli
+## 2.4.7
+
+### Patch Changes
+
+- [#14347](https://github.com/spree/spree/pull/14347) [`b78071f`](https://github.com/spree/spree/commit/b78071f5ae3f985a07eeeaa4d24ab4a4bdff7e3c) Thanks [@damianlegawiec](https://github.com/damianlegawiec)! - All app-facing commands now fall back to a one-off container (`docker compose run --rm`) when the web container is not running, instead of failing on `docker compose exec`. Previously only `spree bundle`, `spree console`, `spree shell`, and `spree rspec` did this; the same behavior now covers `spree migrate` (+ `migrate:rollback`, `migrate:status`), `spree rails`, `spree rake`, `spree task`, `spree exec`, `spree routes`, `spree generate`, `spree seed`, `spree sample-data`, `spree user`, `spree api-key`, and `spree upgrade` — which no longer refuses to run while the stack is down. The one-off container cold-starts and health-waits postgres, so these commands work from a fully stopped stack. On the fallback path `spree migrate` collapses its two steps into a single invocation, paying the one-off container's cold Rails boot once.
+
## 2.4.6
### Patch Changes
diff --git a/packages/cli/package.json b/packages/cli/package.json
index 4e332263b3..3555d98016 100644
--- a/packages/cli/package.json
+++ b/packages/cli/package.json
@@ -1,6 +1,6 @@
{
"name": "@spree/cli",
- "version": "2.4.6",
+ "version": "2.4.7",
"description": "CLI for managing Spree Commerce projects",
"type": "module",
"bin": {
diff --git a/packages/cli/src/commands/exec.ts b/packages/cli/src/commands/exec.ts
index 74bdcce67b..c2a08ca81c 100644
--- a/packages/cli/src/commands/exec.ts
+++ b/packages/cli/src/commands/exec.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'
// Universal escape hatch: run an arbitrary command inside the web container.
// Anything not pre-wrapped by another `spree` command can be reached via this.
@@ -16,6 +16,6 @@ export function registerExecCommand(program: Command): void {
.passThroughOptions(true)
.action(async (command: string[]) => {
const ctx = detectProject()
- await dockerComposeExec(command, ctx.projectDir)
+ await dockerComposeExecOrRun(command, ctx.projectDir)
})
}
diff --git a/packages/cli/src/commands/generate.ts b/packages/cli/src/commands/generate.ts
index 90d607175f..ed66c30803 100644
--- a/packages/cli/src/commands/generate.ts
+++ b/packages/cli/src/commands/generate.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'
// Forwarded as-is so `spree generate migration AddX` hits Rails's own
// generator instead of the non-existent `spree:migration`. `model` is
@@ -37,6 +37,6 @@ export function registerGenerateCommand(program: Command): void {
const ctx = detectProject()
const generator =
name.includes(':') || RAILS_BUILTIN_GENERATORS.has(name) ? name : `spree:${name}`
- await dockerComposeExec(['bin/rails', 'g', generator, ...args], ctx.projectDir)
+ await dockerComposeExecOrRun(['bin/rails', 'g', generator, ...args], ctx.projectDir)
})
}
diff --git a/packages/cli/src/commands/migrate.ts b/packages/cli/src/commands/migrate.ts
index cefc77f3a1..2afbc1b1eb 100644
--- a/packages/cli/src/commands/migrate.ts
+++ b/packages/cli/src/commands/migrate.ts
@@ -2,7 +2,7 @@ import * as p from '@clack/prompts'
import type { Command } from 'commander'
import pc from 'picocolors'
import { detectProject } from '../context.js'
-import { dockerComposeExec } from '../docker.js'
+import { dockerComposeExec, dockerComposeExecOrRun, isServiceRunning } from '../docker.js'
export function registerMigrateCommand(program: Command): void {
program
@@ -19,11 +19,22 @@ export function registerMigrateCommand(program: Command): void {
// Both Rails tasks are silent when there's nothing to do, which leaves
// the operator wondering whether anything ran. Print a visible header
// for each step and a footer summarising the outcome.
- console.log(`\n${pc.bold('→ Installing pending Spree migrations from gems...')}`)
- await dockerComposeExec(['bin/rails', 'spree:install:migrations'], ctx.projectDir)
+ if (await isServiceRunning('web', ctx.projectDir)) {
+ console.log(`\n${pc.bold('→ Installing pending Spree migrations from gems...')}`)
+ await dockerComposeExec(['bin/rails', 'spree:install:migrations'], ctx.projectDir)
- console.log(`\n${pc.bold('→ Running db:migrate...')}`)
- await dockerComposeExec(['bin/rails', 'db:migrate', ...args], ctx.projectDir)
+ console.log(`\n${pc.bold('→ Running db:migrate...')}`)
+ await dockerComposeExec(['bin/rails', 'db:migrate', ...args], ctx.projectDir)
+ } else {
+ // One combined invocation on the fallback path: a one-off container
+ // pays a cold Rails boot per invocation, so don't pay it twice.
+ console.log(`\n${pc.bold('→ Installing + running pending Spree migrations...')}`)
+ await dockerComposeExecOrRun(
+ ['bin/rails', 'spree:install:migrations', 'db:migrate', ...args],
+ ctx.projectDir,
+ { edgeHint: 'the edge boot installs and runs pending migrations itself' },
+ )
+ }
p.note(
`Run ${pc.bold('spree migrate:status')} to inspect the migration log.`,
@@ -39,7 +50,7 @@ export function registerMigrateCommand(program: Command): void {
.passThroughOptions(true)
.action(async (args: string[]) => {
const ctx = detectProject()
- await dockerComposeExec(['bin/rails', 'db:rollback', ...args], ctx.projectDir)
+ await dockerComposeExecOrRun(['bin/rails', 'db:rollback', ...args], ctx.projectDir)
})
program
@@ -47,6 +58,6 @@ export function registerMigrateCommand(program: Command): void {
.description('Show migration status (`bin/rails db:migrate:status`)')
.action(async () => {
const ctx = detectProject()
- await dockerComposeExec(['bin/rails', 'db:migrate:status'], ctx.projectDir)
+ await dockerComposeExecOrRun(['bin/rails', 'db:migrate:status'], ctx.projectDir)
})
}
diff --git a/packages/cli/src/commands/rails.ts b/packages/cli/src/commands/rails.ts
index 1fb53e3c0c..01d924a94b 100644
--- a/packages/cli/src/commands/rails.ts
+++ b/packages/cli/src/commands/rails.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'
// Run any Rails command. Short for `spree exec bin/rails …`.
// spree rails runner 'puts Rails.env'
@@ -15,6 +15,6 @@ export function registerRailsCommand(program: Command): void {
.passThroughOptions(true)
.action(async (args: string[]) => {
const ctx = detectProject()
- await dockerComposeExec(['bin/rails', ...args], ctx.projectDir)
+ await dockerComposeExecOrRun(['bin/rails', ...args], ctx.projectDir)
})
}
diff --git a/packages/cli/src/commands/rake.ts b/packages/cli/src/commands/rake.ts
index e270156838..1bf4c46229 100644
--- a/packages/cli/src/commands/rake.ts
+++ b/packages/cli/src/commands/rake.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'
// Run a rake task inside the web container. Variadic: anything after the
// task name is forwarded verbatim, including `KEY=value` rake args and flags.
@@ -16,6 +16,6 @@ export function registerRakeCommand(program: Command): void {
.passThroughOptions(true)
.action(async (args: string[]) => {
const ctx = detectProject()
- await dockerComposeExec(['bin/rake', ...args], ctx.projectDir)
+ await dockerComposeExecOrRun(['bin/rake', ...args], ctx.projectDir)
})
}
diff --git a/packages/cli/src/commands/routes.ts b/packages/cli/src/commands/routes.ts
index f7e6f27929..2dee3c0c36 100644
--- a/packages/cli/src/commands/routes.ts
+++ b/packages/cli/src/commands/routes.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 registerRoutesCommand(program: Command): void {
program
@@ -11,6 +11,6 @@ export function registerRoutesCommand(program: Command): void {
.passThroughOptions(true)
.action(async (args: string[]) => {
const ctx = detectProject()
- await dockerComposeExec(['bin/rails', 'routes', ...args], ctx.projectDir)
+ await dockerComposeExecOrRun(['bin/rails', 'routes', ...args], ctx.projectDir)
})
}
diff --git a/packages/cli/src/commands/task.ts b/packages/cli/src/commands/task.ts
index da7add1d39..6a469eef64 100644
--- a/packages/cli/src/commands/task.ts
+++ b/packages/cli/src/commands/task.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'
// Shortcut for `spree rake spree:<name>` — most rake tasks a Spree dev runs
// are in the `spree:` namespace, so this saves the prefix.
@@ -17,6 +17,6 @@ export function registerTaskCommand(program: Command): void {
.passThroughOptions(true)
.action(async (name: string, args: string[]) => {
const ctx = detectProject()
- await dockerComposeExec(['bin/rake', `spree:${name}`, ...args], ctx.projectDir)
+ await dockerComposeExecOrRun(['bin/rake', `spree:${name}`, ...args], ctx.projectDir)
})
}
diff --git a/packages/cli/src/commands/upgrade.ts b/packages/cli/src/commands/upgrade.ts
index d9ef880fdd..2c2b3f4e16 100644
--- a/packages/cli/src/commands/upgrade.ts
+++ b/packages/cli/src/commands/upgrade.ts
@@ -2,10 +2,9 @@ import fs from 'node:fs'
import path from 'node:path'
import * as p from '@clack/prompts'
import type { Command } from 'commander'
-import { execa } from 'execa'
import pc from 'picocolors'
import { detectProject, hasMonorepoSpreePath } from '../context.js'
-import { dockerComposeExec, isServiceRunning } from '../docker.js'
+import { dockerComposeCapture, dockerComposeExecOrRun, isServiceRunning } from '../docker.js'
// Sequences bundle update + db:migrate + spree:upgrade rake. Flags map
// to env vars on the inner rake task: --plan → DRY_RUN, --step → STEP,
@@ -39,9 +38,10 @@ export function registerUpgradeCommand(program: Command): void {
}
// Upgrade migrates the DB and runs spree:upgrade rake against the project's
-// REAL Postgres + warm bundle_cache. Unlike `spree bundle`, a one-off
-// `compose run` is wrong here (it would migrate an ephemeral DB), so we refuse
-// rather than fall back. Shared cheap pre-checks: monorepo-edge + web running.
+// REAL Postgres + warm bundle_cache. A one-off `compose run` reaches the same
+// named volumes (`run`'s depends_on cold-starts postgres, like db:reset), so
+// each step falls back to one when web is down. Cheap pre-checks: monorepo-edge
+// + the compose stack being inspectable at all.
async function assertUpgradeable(projectDir: string): Promise<void> {
const refuse = (lines: string[]): never => {
p.cancel(lines.join('\n'))
@@ -56,14 +56,13 @@ async function assertUpgradeable(projectDir: string): Promise<void> {
])
}
- let running: boolean
try {
- running = await isServiceRunning('web', projectDir)
+ await isServiceRunning('web', projectDir)
} catch (err) {
// `compose ps` itself failed: broken/stale compose, daemon down, unknown
// service. Point home instead of dumping the raw env-file error. (Backstop
// for a stale backend/ that slipped past detectProject re-rooting.)
- return refuse([
+ refuse([
'Could not inspect the Docker stack from this directory.',
` ${pc.dim(String((err as Error).message).split('\n')[0])}`,
'',
@@ -71,15 +70,6 @@ async function assertUpgradeable(projectDir: string): Promise<void> {
'.env with SECRET_KEY_BASE), and make sure Docker is running.',
])
}
-
- if (!running) {
- refuse([
- 'The web container is not running.',
- `Upgrade runs migrations and the ${pc.bold('spree:upgrade')} rake against your live`,
- `database, so the stack must be up. Start it with ${pc.bold('spree dev')}, then`,
- 're-run `spree upgrade`.',
- ])
- }
}
async function runBundleUpdate(projectDir: string, flags: { yes?: boolean }): Promise<void> {
@@ -108,31 +98,24 @@ async function runBundleUpdate(projectDir: string, flags: { yes?: boolean }): Pr
}
p.log.step(pc.bold(`bundle update ${spreeGems.join(' ')}`))
- await dockerComposeExec(['bundle', 'update', ...spreeGems], projectDir)
+ await dockerComposeExecOrRun(['bundle', 'update', ...spreeGems], projectDir)
}
export async function detectSpreeGems(projectDir: string): Promise<string[]> {
try {
- // No `2>/dev/null` and no `|| true`: a bundler failure (out-of-sync
- // lockfile, un-checked-out git source) must reach us as a nonzero exit
- // with stderr intact, not get laundered into an empty list that becomes
- // a misleading "No Spree gems detected".
- const { stdout } = await execa(
- 'docker',
- ['compose', 'exec', '-T', 'web', 'sh', '-c', "bundle list --name-only | grep '^spree'"],
- { cwd: projectDir },
- )
+ // Filter in JS rather than piping through grep: `bundle list` exits 0 even
+ // with zero spree gems, so a nonzero exit unambiguously means bundler
+ // itself errored (out-of-sync lockfile, un-checked-out git source) — no
+ // exit-code disambiguation against grep's "no match" needed.
+ const stdout = await dockerComposeCapture(['bundle', 'list', '--name-only'], projectDir)
return stdout
.split('\n')
.map((line) => line.trim())
- .filter((line) => line.length > 0 && line.startsWith('spree'))
+ .filter((line) => line.startsWith('spree'))
} catch (err) {
- const e = err as { exitCode?: number; stderr?: string }
- // grep exits 1 with empty stderr ⇒ bundle is fine but resolves zero spree
- // gems. Return [] so the caller prints the friendly "No Spree gems" message.
- if (e.exitCode === 1 && !e.stderr?.trim()) return []
- // Anything else: bundler itself errored (its stderr survives the pipe).
- // Surface it + the real next step instead of the misleading gem message.
+ const e = err as { stderr?: string }
+ // Surface bundler's error + the real next step instead of laundering it
+ // into a misleading "No Spree gems detected".
throw new Error(
'Could not list gems in the web container — the bundle looks out of sync.\n' +
'Run `spree bundle install` first, then re-run `spree upgrade`.' +
@@ -157,7 +140,7 @@ async function runMigrate(projectDir: string, flags: { yes?: boolean }): Promise
}
}
p.log.step(pc.bold('spree:install:migrations + db:migrate'))
- await dockerComposeExec(['bin/rails', 'spree:install:migrations', 'db:migrate'], projectDir)
+ await dockerComposeExecOrRun(['bin/rails', 'spree:install:migrations', 'db:migrate'], projectDir)
}
async function runRakeUpgrade(
@@ -171,7 +154,7 @@ async function runRakeUpgrade(
if (flags.to) env.TO = flags.to
p.log.step(pc.bold('spree:upgrade'))
- await dockerComposeExec(['bin/rake', 'spree:upgrade'], projectDir, { env })
+ await dockerComposeExecOrRun(['bin/rake', 'spree:upgrade'], projectDir, { env })
}
// The backend upgrade never touches frontend source — SDK bumps go through
diff --git a/packages/cli/src/docker.ts b/packages/cli/src/docker.ts
index a258c12965..cd9fa7bd25 100644
--- a/packages/cli/src/docker.ts
+++ b/packages/cli/src/docker.ts
@@ -45,17 +45,7 @@ export async function rakeTask(
projectDir: string,
env?: Record<string, string>,
): Promise<string> {
- const args = ['compose', 'exec', '-T']
-
- if (env) {
- for (const [key, value] of Object.entries(env)) {
- args.push('-e', `${key}=${value}`)
- }
- }
-
- args.push('web', 'bin/rails', task)
-
- const { stdout } = await execa('docker', args, { cwd: projectDir })
+ const stdout = await dockerComposeCapture(['bin/rails', task], projectDir, { env })
// Rails boot prints noise to stdout (e.g. "[Spree Events] ...") — strip it
return stdout
@@ -229,24 +219,18 @@ export interface DockerComposeExecOrRunOptions {
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
+// The single gate every app-facing command goes through: `exec` into the
+// service's running container, or fall back to a one-off `compose run` when
+// it's down. 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[],
+async function resolveComposeMode(
projectDir: string,
options: DockerComposeExecOrRunOptions = {},
-): Promise<void> {
- const { service = 'web', env, edgeHint } = options
+): Promise<'exec' | 'run'> {
+ const { service = 'web', edgeHint } = options
- if (await isServiceRunning(service, projectDir)) {
- await dockerComposeExec(argv, projectDir, { service, env })
- return
- }
+ if (await isServiceRunning(service, projectDir)) return 'exec'
if (hasMonorepoSpreePath(projectDir)) {
p.cancel(
@@ -261,7 +245,52 @@ export async function dockerComposeExecOrRun(
p.log.info(
`${service} container is not running — using a one-off container (\`docker compose run\`) instead.`,
)
- await dockerComposeRun(argv, projectDir, { service, env })
+ return 'run'
+}
+
+// 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 every app-facing command (`spree migrate`, `spree
+// bundle`, `spree console`, `spree rake`, …): exec into the live container if
+// it's up, otherwise boot a fresh one-off against the same warm DB/volumes.
+export async function dockerComposeExecOrRun(
+ argv: string[],
+ projectDir: string,
+ options: DockerComposeExecOrRunOptions = {},
+): Promise<void> {
+ const { service = 'web', env } = options
+
+ if ((await resolveComposeMode(projectDir, options)) === 'exec') {
+ await dockerComposeExec(argv, projectDir, { service, env })
+ } else {
+ await dockerComposeRun(argv, projectDir, { service, env })
+ }
+}
+
+// Captured-output twin of dockerComposeExecOrRun, for callers that parse
+// stdout (rakeTask, `bundle list`). Non-interactive (`-T`) so a TTY never
+// mangles the captured stream; compose's own progress noise goes to stderr,
+// which stays off stdout and is buffered onto ExecaError for failure paths.
+export async function dockerComposeCapture(
+ argv: string[],
+ projectDir: string,
+ options: DockerComposeExecOrRunOptions = {},
+): Promise<string> {
+ const { service = 'web', env } = options
+ const mode = await resolveComposeMode(projectDir, options)
+
+ const args = ['compose', mode]
+ if (mode === 'run') args.push('--rm')
+ args.push('-T')
+ if (env) {
+ for (const [key, value] of Object.entries(env)) {
+ args.push('-e', `${key}=${value}`)
+ }
+ }
+ args.push(service, ...argv)
+
+ const { stdout } = await execa('docker', args, { cwd: projectDir })
+ return stdout
}
export async function streamLogs(service: string, projectDir: string): Promise<void> {
diff --git a/packages/cli/tests/docker.test.ts b/packages/cli/tests/docker.test.ts
index 9a61219a4e..74c1e7c990 100644
--- a/packages/cli/tests/docker.test.ts
+++ b/packages/cli/tests/docker.test.ts
@@ -17,20 +17,22 @@ vi.mock('@clack/prompts', () => ({
import { execa } from 'execa'
import {
buildAdminStylesheets,
+ dockerComposeCapture,
dockerComposeExecOrRun,
dockerComposeRun,
+ rakeTask,
watchAdminStylesheets,
} from '../src/docker'
const mockExeca = vi.mocked(execa)
-// `dockerComposeExecOrRun` makes several `execa` calls (the `compose ps` probe,
+// The exec-or-run helpers make 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 {
+function routeExeca(webUp: boolean, commandStdout = ''): void {
mockExeca.mockImplementation((async (_cmd: string, args: string[]) => {
if (args.includes('ps')) return { stdout: webUp ? 'running' : '' }
- return { stdout: '' }
+ return { stdout: commandStdout }
}) as never)
}
@@ -219,3 +221,104 @@ describe('dockerComposeExecOrRun', () => {
expect(message).toContain('the edge stack heals gem drift on boot')
})
})
+
+describe('dockerComposeCapture', () => {
+ 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('captures stdout via a non-interactive exec when the service is up', async () => {
+ routeExeca(true, 'spree\nspree_core\n')
+
+ await expect(dockerComposeCapture(['bundle', 'list', '--name-only'], '/proj')).resolves.toBe(
+ 'spree\nspree_core\n',
+ )
+ expect(mockExeca).toHaveBeenCalledWith(
+ 'docker',
+ ['compose', 'exec', '-T', 'web', 'bundle', 'list', '--name-only'],
+ { cwd: '/proj' },
+ )
+ })
+
+ it('falls back to a one-off `run --rm -T` container when the service is down', async () => {
+ routeExeca(false, 'output')
+
+ await expect(dockerComposeCapture(['bin/rails', 'db:seed'], '/proj')).resolves.toBe('output')
+ expect(mockExeca).toHaveBeenCalledWith(
+ 'docker',
+ ['compose', 'run', '--rm', '-T', 'web', 'bin/rails', 'db:seed'],
+ { cwd: '/proj' },
+ )
+ expect(logInfoMock).toHaveBeenCalled()
+ })
+
+ it('threads -e KEY=VALUE pairs before the service', async () => {
+ routeExeca(true)
+
+ await dockerComposeCapture(['bin/rails', 'spree:cli:create_admin'], '/proj', {
+ env: { EMAIL: '[email protected]' },
+ })
+
+ expect(mockExeca).toHaveBeenCalledWith(
+ 'docker',
+ ['compose', 'exec', '-T', '-e', '[email protected]', 'web', 'bin/rails', 'spree:cli:create_admin'],
+ { cwd: '/proj' },
+ )
+ })
+
+ it('refuses the one-off fallback in a monorepo edge project', async () => {
+ routeExeca(false)
+ monorepoEdge = true
+
+ await expect(dockerComposeCapture(['bin/rails', 'db:seed'], '/proj')).rejects.toMatchObject({
+ code: 1,
+ })
+ expect(cancelMock).toHaveBeenCalled()
+ })
+})
+
+describe('rakeTask', () => {
+ beforeEach(() => {
+ monorepoEdge = false
+ logInfoMock.mockClear()
+ mockExeca.mockReset()
+ })
+
+ afterEach(() => vi.restoreAllMocks())
+
+ it('strips Rails boot noise from the captured output', async () => {
+ routeExeca(true, '[Spree Events] subscribers loaded\napi_key_abc\n')
+
+ await expect(rakeTask('spree:cli:ensure_api_key', '/proj')).resolves.toBe('api_key_abc')
+ expect(mockExeca).toHaveBeenCalledWith(
+ 'docker',
+ ['compose', 'exec', '-T', 'web', 'bin/rails', 'spree:cli:ensure_api_key'],
+ { cwd: '/proj' },
+ )
+ })
+
+ it('falls back to a one-off container when web is down', async () => {
+ routeExeca(false, 'seeded')
+
+ await expect(rakeTask('db:seed', '/proj')).resolves.toBe('seeded')
+ expect(mockExeca).toHaveBeenCalledWith(
+ 'docker',
+ ['compose', 'run', '--rm', '-T', 'web', 'bin/rails', 'db:seed'],
+ { cwd: '/proj' },
+ )
+ })
+})
diff --git a/packages/cli/tests/migrate.test.ts b/packages/cli/tests/migrate.test.ts
new file mode 100644
index 0000000000..f3a68421be
--- /dev/null
+++ b/packages/cli/tests/migrate.test.ts
@@ -0,0 +1,86 @@
+import { Command } from 'commander'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { registerMigrateCommand } from '../src/commands/migrate'
+import { dockerComposeExec, dockerComposeExecOrRun, isServiceRunning } from '../src/docker'
+
+let projectDir: string
+
+vi.mock('../src/context', () => ({
+ detectProject: () => ({ mode: 'docker', projectDir, port: 3000 }),
+}))
+
+vi.mock('../src/docker', () => ({
+ dockerComposeExec: vi.fn().mockResolvedValue(undefined),
+ dockerComposeExecOrRun: vi.fn().mockResolvedValue(undefined),
+ isServiceRunning: vi.fn().mockResolvedValue(true),
+}))
+
+vi.mock('@clack/prompts', () => ({ note: vi.fn() }))
+
+async function runMigrate(argv: string[]): Promise<void> {
+ // The real root program enables positional options (src/index.ts), which
+ // commander requires for subcommands using passThroughOptions.
+ const program = new Command().enablePositionalOptions()
+ registerMigrateCommand(program)
+ await program.parseAsync(argv, { from: 'user' })
+}
+
+describe('spree migrate', () => {
+ beforeEach(() => {
+ projectDir = '/proj'
+ vi.clearAllMocks()
+ vi.mocked(isServiceRunning).mockResolvedValue(true)
+ vi.spyOn(console, 'log').mockImplementation(() => {})
+ })
+
+ afterEach(() => {
+ vi.restoreAllMocks()
+ })
+
+ it('runs install + migrate as separate steps when web is up', async () => {
+ await runMigrate(['migrate', 'VERSION=20260101000000'])
+
+ expect(dockerComposeExec).toHaveBeenNthCalledWith(
+ 1,
+ ['bin/rails', 'spree:install:migrations'],
+ '/proj',
+ )
+ expect(dockerComposeExec).toHaveBeenNthCalledWith(
+ 2,
+ ['bin/rails', 'db:migrate', 'VERSION=20260101000000'],
+ '/proj',
+ )
+ expect(dockerComposeExecOrRun).not.toHaveBeenCalled()
+ })
+
+ it('collapses both steps into one one-off invocation when web is down', async () => {
+ vi.mocked(isServiceRunning).mockResolvedValue(false)
+
+ await runMigrate(['migrate', 'VERSION=20260101000000'])
+
+ expect(dockerComposeExecOrRun).toHaveBeenCalledWith(
+ ['bin/rails', 'spree:install:migrations', 'db:migrate', 'VERSION=20260101000000'],
+ '/proj',
+ { edgeHint: expect.any(String) },
+ )
+ expect(dockerComposeExec).not.toHaveBeenCalled()
+ })
+
+ // Branching (exec vs one-off run vs monorepo-edge refusal) for the
+ // subcommands below is covered by dockerComposeExecOrRun's own tests in
+ // docker.test.ts; here we only assert they delegate with the right argv.
+ it('migrate:rollback delegates with forwarded args', async () => {
+ await runMigrate(['migrate:rollback', 'STEP=2'])
+
+ expect(dockerComposeExecOrRun).toHaveBeenCalledWith(
+ ['bin/rails', 'db:rollback', 'STEP=2'],
+ '/proj',
+ )
+ })
+
+ it('migrate:status delegates', async () => {
+ await runMigrate(['migrate:status'])
+
+ expect(dockerComposeExecOrRun).toHaveBeenCalledWith(['bin/rails', 'db:migrate:status'], '/proj')
+ })
+})
diff --git a/packages/cli/tests/upgrade.test.ts b/packages/cli/tests/upgrade.test.ts
index 4cb8d8f6f2..224b91264d 100644
--- a/packages/cli/tests/upgrade.test.ts
+++ b/packages/cli/tests/upgrade.test.ts
@@ -75,32 +75,42 @@ describe('detectSpreeGems', () => {
const mockExeca = vi.mocked(execa)
afterEach(() => mockExeca.mockReset())
+ // detectSpreeGems goes through dockerComposeCapture, which probes the web
+ // container first (`compose ps`) — route the probe to "running" so the
+ // command call itself drives each scenario.
+ function routeBundleList(command: () => Promise<{ stdout: string }>): void {
+ mockExeca.mockImplementation((async (_cmd: string, args: string[]) => {
+ if (args.includes('ps')) return { stdout: 'running' }
+ return command()
+ }) as never)
+ }
+
it('parses spree gem names from bundle list output', async () => {
- mockExeca.mockResolvedValue({ stdout: 'spree\nspree_core\nspree_api\nrails\n' } as never)
+ routeBundleList(async () => ({ stdout: 'spree\nspree_core\nspree_api\nrails\n' }))
await expect(detectSpreeGems('/proj')).resolves.toEqual(['spree', 'spree_core', 'spree_api'])
})
- it('returns [] when bundle is healthy but resolves no spree gems (grep rc=1, empty stderr)', async () => {
- mockExeca.mockRejectedValue(Object.assign(new Error('x'), { exitCode: 1, stderr: '' }) as never)
+ it('returns [] when bundle is healthy but resolves no spree gems', async () => {
+ routeBundleList(async () => ({ stdout: 'rails\npg\n' }))
await expect(detectSpreeGems('/proj')).resolves.toEqual([])
})
- it('throws a bundle-install hint when bundler itself errors (rc=1, real stderr)', async () => {
- mockExeca.mockRejectedValue(
- Object.assign(new Error('x'), {
+ it('throws a bundle-install hint when bundler itself errors', async () => {
+ routeBundleList(async () => {
+ throw Object.assign(new Error('x'), {
exitCode: 1,
stderr:
'The git source https://github.com/spree/spree.git is not yet checked out. Please run bundle install',
- }) as never,
- )
+ })
+ })
await expect(detectSpreeGems('/proj')).rejects.toThrow(/spree bundle install/)
await expect(detectSpreeGems('/proj')).rejects.toThrow(/not yet checked out/)
})
- it('re-throws non-grep failures (stack down, exitCode 255) with the bundle hint', async () => {
- mockExeca.mockRejectedValue(
- Object.assign(new Error('x'), { exitCode: 255, stderr: 'no such service: web' }) as never,
- )
+ it('wraps daemon-level failures (exitCode 255) with the bundle hint', async () => {
+ routeBundleList(async () => {
+ throw Object.assign(new Error('x'), { exitCode: 255, stderr: 'no such service: web' })
+ })
await expect(detectSpreeGems('/proj')).rejects.toThrow(
/bundle looks out of sync|no such service/,
)