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.

CLI: fixed spree bundle issues (#14250)

Damian Legawiec4f51513892f1
diff --git a/packages/cli/CHANGELOG.md b/packages/cli/CHANGELOG.md
index 72264f27e2..a1f3533747 100644
--- a/packages/cli/CHANGELOG.md
+++ b/packages/cli/CHANGELOG.md
@@ -1,5 +1,11 @@
# @spree/cli
+## 2.3.4
+
+### Patch Changes
+
+- Fix `spree upgrade` on create-spree-app projects. Running it from the `backend/` directory no longer fails on a missing `.env` — the CLI now resolves to the project root automatically. When the bundle is out of sync (e.g. an un-checked-out git gem source), it surfaces the real bundler error and points you at `spree bundle install` instead of a misleading "No Spree gems detected". And it now refuses early with a clear message when the stack is down or in a monorepo edge project, rather than failing deep in a Docker command.
+
## 2.3.3
### Patch Changes
diff --git a/packages/cli/package.json b/packages/cli/package.json
index db3982802e..adb687d455 100644
--- a/packages/cli/package.json
+++ b/packages/cli/package.json
@@ -1,6 +1,6 @@
{
"name": "@spree/cli",
- "version": "2.3.3",
+ "version": "2.3.4",
"description": "CLI for managing Spree Commerce projects",
"type": "module",
"bin": {
diff --git a/packages/cli/src/commands/upgrade.ts b/packages/cli/src/commands/upgrade.ts
index b62f461616..d9ef880fdd 100644
--- a/packages/cli/src/commands/upgrade.ts
+++ b/packages/cli/src/commands/upgrade.ts
@@ -4,8 +4,8 @@ import * as p from '@clack/prompts'
import type { Command } from 'commander'
import { execa } from 'execa'
import pc from 'picocolors'
-import { detectProject } from '../context.js'
-import { dockerComposeExec } from '../docker.js'
+import { detectProject, hasMonorepoSpreePath } from '../context.js'
+import { dockerComposeExec, 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,
@@ -23,6 +23,7 @@ export function registerUpgradeCommand(program: Command): void {
.option('--yes', 'skip prompts on automated steps')
.action(async (flags: { plan?: boolean; step?: string; to?: string; yes?: boolean }) => {
const ctx = detectProject()
+ await assertUpgradeable(ctx.projectDir)
const skipUniversal = Boolean(flags.plan || flags.step)
@@ -37,6 +38,50 @@ 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.
+async function assertUpgradeable(projectDir: string): Promise<void> {
+ const refuse = (lines: string[]): never => {
+ p.cancel(lines.join('\n'))
+ process.exit(1)
+ }
+
+ if (hasMonorepoSpreePath(projectDir)) {
+ refuse([
+ 'This is a monorepo edge project (SPREE_PATH set in .env).',
+ `Run the upgrade from the monorepo root with ${pc.bold('pnpm server:*')} — the`,
+ 'project-local docker-compose.yml is not the running config here.',
+ ])
+ }
+
+ let running: boolean
+ try {
+ running = 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([
+ '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.',
+ ])
+ }
+
+ 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> {
if (!flags.yes) {
const confirmed = await p.confirm({
@@ -66,26 +111,34 @@ async function runBundleUpdate(projectDir: string, flags: { yes?: boolean }): Pr
await dockerComposeExec(['bundle', 'update', ...spreeGems], projectDir)
}
-async function detectSpreeGems(projectDir: string): Promise<string[]> {
- // Let exec failures (stack down, web service missing) bubble up — the
- // upgrade should fail loudly, not silently skip the gem bump.
- const { stdout } = await execa(
- 'docker',
- [
- 'compose',
- 'exec',
- '-T',
- 'web',
- 'sh',
- '-c',
- "bundle list --name-only 2>/dev/null | grep '^spree' || true",
- ],
- { cwd: projectDir },
- )
- return stdout
- .split('\n')
- .map((line) => line.trim())
- .filter((line) => line.length > 0 && line.startsWith('spree'))
+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 },
+ )
+ return stdout
+ .split('\n')
+ .map((line) => line.trim())
+ .filter((line) => line.length > 0 && 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.
+ 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`.' +
+ (e.stderr?.trim() ? `\n\n${e.stderr.trim()}` : ''),
+ )
+ }
}
async function runMigrate(projectDir: string, flags: { yes?: boolean }): Promise<void> {
diff --git a/packages/cli/src/context.ts b/packages/cli/src/context.ts
index 2c2b684576..4b215ea214 100644
--- a/packages/cli/src/context.ts
+++ b/packages/cli/src/context.ts
@@ -4,7 +4,8 @@ import { DEFAULT_SPREE_PORT } from './constants.js'
import type { ProjectContext } from './types.js'
export function detectProject(cwd: string = process.cwd()): ProjectContext {
- const composeFile = path.join(cwd, 'docker-compose.yml')
+ const projectDir = resolveProjectDir(cwd)
+ const composeFile = path.join(projectDir, 'docker-compose.yml')
if (!fs.existsSync(composeFile)) {
throw new Error(
@@ -13,15 +14,49 @@ export function detectProject(cwd: string = process.cwd()): ProjectContext {
)
}
- const port = readPortFromEnv(cwd)
+ const port = readPortFromEnv(projectDir)
return {
mode: 'docker',
- projectDir: cwd,
+ projectDir,
port,
}
}
+// create-spree-app clones spree-starter into <root>/backend/ and copies its
+// compose files UP to the wrapper root, rewriting the dev bind-mount to
+// `./backend:/rails` and writing the only real `.env` at the root. The cloned
+// `backend/docker-compose.yml` is left behind as a stale leftover (mounts
+// `.:/rails`, expects a sibling `.env` that does not exist). Running the CLI
+// from `backend/` would target that broken file. When we can prove `cwd` is
+// the wrapper's `backend/` and the parent is the real (adjusted) root, re-root
+// there so every command runs against the runnable compose + root `.env`.
+function resolveProjectDir(cwd: string): string {
+ if (path.basename(cwd) !== 'backend') return cwd
+
+ const parent = path.dirname(cwd)
+
+ // The parent is the real wrapper root only if its compose was adjusted by the
+ // scaffold to mount THIS dir (`./backend:/rails`). The rewrite lands in the
+ // dev overlay (the base file is copied verbatim), so scan both. A coincidental
+ // nested layout — a `backend/` dir under an unrelated compose project — won't
+ // contain this exact marker, so re-root stays a no-op there.
+ for (const name of ['docker-compose.yml', 'docker-compose.dev.yml']) {
+ const file = path.join(parent, name)
+ if (!fs.existsSync(file)) continue
+ try {
+ // matches "- ./backend:/rails" and "- ./backend:/rails:cached" etc.
+ if (/\.\/backend:\/rails(:\w+)?(\s|$)/m.test(fs.readFileSync(file, 'utf-8'))) {
+ return parent
+ }
+ } catch {
+ // unreadable file — ignore, keep checking
+ }
+ }
+
+ return cwd
+}
+
// Monorepo edge projects (SPREE_PATH in .env) are booted from the monorepo
// root with the dev + edge compose overlay — the project-local
// docker-compose.yml the CLI would target is not the running config.
diff --git a/packages/cli/tests/context.test.ts b/packages/cli/tests/context.test.ts
index 0e92502448..2ceafe9f46 100644
--- a/packages/cli/tests/context.test.ts
+++ b/packages/cli/tests/context.test.ts
@@ -55,4 +55,50 @@ describe('detectProject', () => {
const ctx = detectProject(dir)
expect(ctx.port).toBe(3000)
})
+
+ it('re-roots to the wrapper parent when run from backend/ of a create-spree-app wrapper', () => {
+ const root = makeTempDir()
+ const backend = path.join(root, 'backend')
+ fs.mkdirSync(backend)
+ // root: adjusted compose (marker in dev overlay), real .env
+ fs.writeFileSync(path.join(root, 'docker-compose.yml'), 'services:\n web:\n')
+ fs.writeFileSync(
+ path.join(root, 'docker-compose.dev.yml'),
+ 'services:\n web:\n volumes:\n - ./backend:/rails\n',
+ )
+ fs.writeFileSync(path.join(root, '.env'), 'SECRET_KEY_BASE=abc\nSPREE_PORT=4001\n')
+ // backend: stale leftover compose
+ fs.writeFileSync(path.join(backend, 'docker-compose.yml'), 'services:\n web:\n')
+
+ const ctx = detectProject(backend)
+ expect(ctx.projectDir).toBe(root)
+ expect(ctx.port).toBe(4001) // port read from the ROOT .env, not backend/
+ })
+
+ it('does NOT re-root when the parent compose lacks the ./backend:/rails marker', () => {
+ const root = makeTempDir()
+ const backend = path.join(root, 'backend')
+ fs.mkdirSync(backend)
+ // parent has a compose but it's an unrelated project (no marker)
+ fs.writeFileSync(
+ path.join(root, 'docker-compose.yml'),
+ 'services:\n web:\n volumes:\n - .:/rails\n',
+ )
+ fs.writeFileSync(path.join(backend, 'docker-compose.yml'), 'services:')
+
+ const ctx = detectProject(backend)
+ expect(ctx.projectDir).toBe(backend)
+ })
+
+ it('does NOT re-root a standalone dir named backend with no parent compose', () => {
+ const root = makeTempDir()
+ const backend = path.join(root, 'backend')
+ fs.mkdirSync(backend)
+ // no compose at parent; backend/ is a standalone starter checkout
+ fs.writeFileSync(path.join(backend, 'docker-compose.yml'), 'services:')
+ fs.writeFileSync(path.join(backend, 'docker-compose.dev.yml'), 'services:\n - .:/rails\n')
+
+ const ctx = detectProject(backend)
+ expect(ctx.projectDir).toBe(backend)
+ })
})
diff --git a/packages/cli/tests/upgrade.test.ts b/packages/cli/tests/upgrade.test.ts
index 58ab8789ef..4cb8d8f6f2 100644
--- a/packages/cli/tests/upgrade.test.ts
+++ b/packages/cli/tests/upgrade.test.ts
@@ -1,8 +1,12 @@
import fs from 'node:fs'
import os from 'node:os'
import path from 'node:path'
-import { afterEach, describe, expect, it } from 'vitest'
-import { sdkAdvisory } from '../src/commands/upgrade'
+import { afterEach, describe, expect, it, vi } from 'vitest'
+
+vi.mock('execa', () => ({ execa: vi.fn() }))
+
+import { execa } from 'execa'
+import { detectSpreeGems, sdkAdvisory } from '../src/commands/upgrade'
describe('sdkAdvisory', () => {
const tempDirs: string[] = []
@@ -66,3 +70,39 @@ describe('sdkAdvisory', () => {
expect(sdkAdvisory(dir)).toContain('any storefront or integration')
})
})
+
+describe('detectSpreeGems', () => {
+ const mockExeca = vi.mocked(execa)
+ afterEach(() => mockExeca.mockReset())
+
+ it('parses spree gem names from bundle list output', async () => {
+ mockExeca.mockResolvedValue({ stdout: 'spree\nspree_core\nspree_api\nrails\n' } as never)
+ 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)
+ 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'), {
+ 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,
+ )
+ await expect(detectSpreeGems('/proj')).rejects.toThrow(
+ /bundle looks out of sync|no such service/,
+ )
+ })
+})
diff --git a/packages/create-spree-app/src/scaffold.ts b/packages/create-spree-app/src/scaffold.ts
index 7b0de2a6f5..6992b7da53 100644
--- a/packages/create-spree-app/src/scaffold.ts
+++ b/packages/create-spree-app/src/scaffold.ts
@@ -70,6 +70,13 @@ export async function scaffold(options: ScaffoldOptions): Promise<void> {
.replace('- .:/rails', '- ./backend:/rails'),
)
+ // The compose files now live (adjusted) at the wrapper root referencing
+ // ./backend + the root .env. The originals cloned into backend/ are stale
+ // leftovers (mount .:/rails, expect a sibling .env) — remove them so the CLI
+ // never accidentally targets them when run from backend/.
+ fs.rmSync(path.join(backendDir, 'docker-compose.yml'), { force: true })
+ fs.rmSync(path.join(backendDir, 'docker-compose.dev.yml'), { force: true })
+
fs.writeFileSync(path.join(projectDir, '.env'), envContent(generateSecretKeyBase(), port))
fs.writeFileSync(path.join(projectDir, 'package.json'), rootPackageJsonContent(projectName))
fs.writeFileSync(path.join(projectDir, 'README.md'), readmeContent(projectName, storefront, port))