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.

Fix: Clearer CLI message when Docker is not running, and skippable upgrade tasks (#14978)

Damian Legawiec2df9371e81f2
diff --git a/.changeset/cli-docker-not-running.md b/.changeset/cli-docker-not-running.md
new file mode 100644
index 0000000000..595c76d17f
--- /dev/null
+++ b/.changeset/cli-docker-not-running.md
@@ -0,0 +1,7 @@
+---
+"@spree/cli": patch
+---
+
+`spree upgrade`, `spree db:reset` and `spree db:console` now say plainly when Docker is not running, and show Docker's own error for other failures instead of the command that failed.
+
+`spree upgrade` now asks before running the upgrade tasks (data backfills), so they can be skipped like the other steps.
diff --git a/packages/cli/src/commands/db.ts b/packages/cli/src/commands/db.ts
index 69ecb1b372..070249bb03 100644
--- a/packages/cli/src/commands/db.ts
+++ b/packages/cli/src/commands/db.ts
@@ -7,6 +7,7 @@ import {
dockerCompose,
dockerComposeExec,
dockerComposeRun,
+ dockerStackProblem,
isServiceRunning,
} from '../docker.js'
@@ -73,17 +74,10 @@ export function registerDbCommand(program: Command): void {
)
stackUp = running.some(Boolean)
} 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 API directory 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.',
- ])
+ // `compose ps` itself failed: daemon down, broken/stale compose, unknown
+ // service (mirrors upgrade.ts). `return` is load-bearing: it tells TS
+ // `stackUp` is assigned past here.
+ return refuse(dockerStackProblem(err, 'spree db:reset'))
}
if (stackUp) {
@@ -136,14 +130,7 @@ export function registerDbCommand(program: Command): void {
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'),
- )
+ p.cancel(dockerStackProblem(err, 'spree db:console').join('\n'))
process.exit(1)
}
diff --git a/packages/cli/src/commands/upgrade.ts b/packages/cli/src/commands/upgrade.ts
index 221942454f..c73782b4c8 100644
--- a/packages/cli/src/commands/upgrade.ts
+++ b/packages/cli/src/commands/upgrade.ts
@@ -9,6 +9,7 @@ import {
dockerCompose,
dockerComposeCapture,
dockerComposeExecOrRun,
+ dockerStackProblem,
isServiceRunning,
primeBundleVolume,
restartAppServices,
@@ -148,16 +149,10 @@ async function assertUpgradeable(projectDir: string): Promise<void> {
try {
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 API directory that slipped past detectProject re-rooting.)
- refuse([
- 'Could not inspect the Docker stack from this directory.',
- ` ${pc.dim(String((err as Error).message).split('\n')[0])}`,
- '',
- `Run ${pc.bold('spree upgrade')} from your project root (the directory holding the`,
- '.env with SECRET_KEY_BASE), and make sure Docker is running.',
- ])
+ // `compose ps` itself failed: daemon down, broken/stale compose, unknown
+ // service. (Backstop for a stale API directory that slipped past
+ // detectProject re-rooting.)
+ refuse(dockerStackProblem(err, 'spree upgrade'))
}
}
@@ -225,6 +220,13 @@ async function runMigrate(projectDir: string, flags: UpgradeFlags): Promise<void
}
async function runRakeUpgrade(projectDir: string, flags: UpgradeFlags): Promise<void> {
+ // --plan and --step already name the rake run the operator asked for.
+ const explicit = flags.plan || flags.step
+ if (!explicit && !(await confirmStep('Run the Spree upgrade tasks (data backfills)?', flags))) {
+ p.log.info('Skipping the upgrade tasks.')
+ return
+ }
+
// Flags map to env vars so prod (`STEP=channels rake spree:upgrade`) and dev share the same path.
const env: Record<string, string> = {}
if (flags.plan) env.DRY_RUN = '1'
diff --git a/packages/cli/src/docker.ts b/packages/cli/src/docker.ts
index 56359f7382..d204602d66 100644
--- a/packages/cli/src/docker.ts
+++ b/packages/cli/src/docker.ts
@@ -110,6 +110,53 @@ export async function isServiceRunning(service: string, projectDir: string): Pro
return stdout.split('\n').some((line) => line.trim() === 'running')
}
+// Docker Desktop, the Linux engine and the Windows named pipe each word a
+// stopped daemon differently.
+const DAEMON_DOWN =
+ /Cannot connect to the Docker daemon|failed to connect to the docker API|error during connect/i
+
+/**
+ * The refusal shown when `docker compose` itself failed while probing the
+ * stack (see isServiceRunning). A missing or stopped Docker gets a plain
+ * "install/start Docker"; anything else shows Docker's own reason rather than
+ * execa's command line.
+ *
+ * @param error the error `compose ps` threw
+ * @param command the spree command to re-run, e.g. `spree upgrade`
+ * @return the message lines
+ */
+export function dockerStackProblem(error: unknown, command: string): string[] {
+ const { code, stderr, originalMessage, message } = error as {
+ code?: string
+ stderr?: string
+ originalMessage?: string
+ message?: string
+ }
+ if (code === 'ENOENT') {
+ return [
+ 'Docker is not installed (the `docker` command was not found).',
+ `Install Docker Desktop (or Docker Engine), then re-run ${pc.bold(command)}.`,
+ ]
+ }
+
+ const output = String(stderr || originalMessage || message || '')
+ if (DAEMON_DOWN.test(output)) {
+ return [
+ 'Docker is not running.',
+ `Start Docker Desktop (or the Docker service), then re-run ${pc.bold(command)}.`,
+ ]
+ }
+
+ const reason = output.split('\n').find((line) => line.trim()) ?? ''
+ return [
+ 'Could not inspect the Docker stack from this directory.',
+ ` ${pc.dim(reason.trim())}`,
+ '',
+ `Run ${pc.bold(command)} from your project root (the directory holding the`,
+ '.env with SECRET_KEY_BASE), and make sure Docker is running.',
+ ]
+}
+
export interface DockerComposeExecOptions {
service?: string
tty?: boolean
diff --git a/packages/cli/tests/db.test.ts b/packages/cli/tests/db.test.ts
index 3733c98ca1..e0c1929196 100644
--- a/packages/cli/tests/db.test.ts
+++ b/packages/cli/tests/db.test.ts
@@ -11,7 +11,8 @@ vi.mock('../src/context', () => ({
hasMonorepoSpreePath: () => monorepoEdge,
}))
-vi.mock('../src/docker', () => ({
+vi.mock('../src/docker', async (importOriginal) => ({
+ dockerStackProblem: (await importOriginal<typeof import('../src/docker')>()).dockerStackProblem,
// Sidekiq-era compose shape by default — these tests exercise the two-service
// path; the Solid Queue single-service shape drops 'worker' from this list.
appServices: vi.fn().mockResolvedValue(['web', 'worker']),
@@ -117,6 +118,7 @@ describe('spree db:reset', () => {
await expect(runDbReset('--yes')).rejects.toMatchObject({ code: 1 })
+ expect(cancelMock).toHaveBeenCalledWith(expect.stringMatching(/^Docker is not running\./))
expect(dockerCompose).not.toHaveBeenCalled()
expect(dockerComposeRun).not.toHaveBeenCalled()
})
diff --git a/packages/cli/tests/upgrade.test.ts b/packages/cli/tests/upgrade.test.ts
index 2bb1520c0c..dc19b51405 100644
--- a/packages/cli/tests/upgrade.test.ts
+++ b/packages/cli/tests/upgrade.test.ts
@@ -27,6 +27,7 @@ vi.mock('@clack/prompts', () => ({
cancel: vi.fn(),
}))
+import * as p from '@clack/prompts'
import { execa } from 'execa'
import {
detectSpreeGems,
@@ -325,6 +326,88 @@ describe('spree upgrade', () => {
expect(commands.at(-1)).toBe('docker compose exec web bin/rake spree:upgrade')
})
+ describe('when `compose ps` fails', () => {
+ function failProbe(stderr: string): void {
+ mockExeca.mockImplementation((async (_cmd: string, args: string[]) => {
+ if (args.includes('ps')) {
+ throw Object.assign(
+ new Error(
+ "Command failed with exit code 1: docker compose ps web --format '{{.State}}'",
+ ),
+ { exitCode: 1, stderr },
+ )
+ }
+ return { stdout: '' }
+ }) as never)
+ }
+
+ beforeEach(() => {
+ writeProject({ ejected: false })
+ vi.spyOn(process, 'exit').mockImplementation(((code: number) => {
+ throw Object.assign(new Error('exit'), { code })
+ }) as never)
+ })
+
+ afterEach(() => {
+ vi.restoreAllMocks()
+ })
+
+ it('says Docker is not running when the daemon is down', async () => {
+ failProbe(
+ 'failed to connect to the docker API at unix:///var/run/docker.sock; check if the path is correct and if the daemon is running',
+ )
+
+ await expect(runUpgrade()).rejects.toMatchObject({ code: 1 })
+
+ expect(vi.mocked(p.cancel)).toHaveBeenCalledWith(
+ expect.stringMatching(/^Docker is not running\./),
+ )
+ expect(commands).toEqual([])
+ })
+
+ it('says Docker is not installed when the docker command is missing', async () => {
+ mockExeca.mockImplementation((async () => {
+ throw Object.assign(new Error('Command failed with ENOENT: docker compose ps web'), {
+ code: 'ENOENT',
+ originalMessage: 'spawn docker ENOENT',
+ stderr: '',
+ })
+ }) as never)
+
+ await expect(runUpgrade()).rejects.toMatchObject({ code: 1 })
+
+ expect(vi.mocked(p.cancel)).toHaveBeenCalledWith(
+ expect.stringMatching(/^Docker is not installed/),
+ )
+ })
+
+ it("shows Docker's own reason for any other failure", async () => {
+ failProbe('no such service: web')
+
+ await expect(runUpgrade()).rejects.toMatchObject({ code: 1 })
+
+ const message = vi.mocked(p.cancel).mock.calls.at(-1)?.[0]
+ expect(message).toMatch(/no such service: web/)
+ expect(message).not.toMatch(/Command failed/)
+ })
+ })
+
+ it('skips only the upgrade tasks when the operator declines them', async () => {
+ writeProject({ ejected: true })
+ vi.mocked(p.confirm).mockImplementation(
+ (async ({ message }: { message: string }) => !message.includes('upgrade tasks')) as never,
+ )
+
+ const program = new Command()
+ registerUpgradeCommand(program)
+ await program.parseAsync(['upgrade'], { from: 'user' })
+
+ expect(commands).toContain(
+ 'docker compose exec web bin/rails spree:install:migrations db:migrate',
+ )
+ expect(commands).not.toContain('docker compose exec web bin/rake spree:upgrade')
+ })
+
it('runs only the rake task with --plan or --step', async () => {
writeProject({ ejected: true })