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 `spree generate`, `migrate`, `build`, `db:reset`, `db:console`, `routes`

Damian Legawiecec1c995d5a1f
diff --git a/packages/cli/src/commands/build.ts b/packages/cli/src/commands/build.ts
new file mode 100644
index 0000000000..a6e7477249
--- /dev/null
+++ b/packages/cli/src/commands/build.ts
@@ -0,0 +1,76 @@
+import fs from 'node:fs'
+import path from 'node:path'
+import * as p from '@clack/prompts'
+import type { Command } from 'commander'
+import pc from 'picocolors'
+import { detectProject } from '../context.js'
+import { dockerCompose } from '../docker.js'
+
+// Rebuild the dev image. Needed after Dockerfile or .ruby-version changes;
+// `spree bundle add` does NOT require this — gems land in the bundle_cache
+// volume which survives image rebuilds.
+//
+// --reset-bundle wipes the bundle_cache volume so the new image's gem
+// baseline gets re-seeded. Use when you bumped .ruby-version (gems compiled
+// against the old Ruby won't load against the new one).
+//
+// Targets docker-compose.dev.yml explicitly when present, so this works
+// before `spree eject` too (eject collapses the two files into one).
+export function registerBuildCommand(program: Command): void {
+ program
+ .command('build')
+ .description('Rebuild the dev image (after Dockerfile / .ruby-version changes)')
+ .option('--reset-bundle', 'also wipe the bundle_cache volume to re-seed gems')
+ .option('--yes', 'skip confirmation prompts (for CI)')
+ .action(async (flags: { resetBundle?: boolean; yes?: boolean }) => {
+ const ctx = detectProject()
+ const composeArgs = composeFileArgs(ctx.projectDir)
+
+ if (flags.resetBundle) {
+ if (!flags.yes) {
+ const confirmed = await p.confirm({
+ message:
+ 'Wipe the bundle_cache volume? Any gems added via `spree bundle add` since the last image build will be lost.',
+ initialValue: false,
+ })
+ if (p.isCancel(confirmed) || !confirmed) {
+ p.cancel('Build cancelled.')
+ process.exit(0)
+ }
+ }
+
+ const s = p.spinner()
+ s.start('Wiping bundle_cache volume...')
+ // `docker compose down -v` is portable (no project-name guessing) but
+ // also tears down all containers. Acceptable: rebuilding the image
+ // means the user is recreating containers anyway.
+ await dockerCompose([...composeArgs, 'down', '-v'], ctx.projectDir, { stdio: 'ignore' })
+ s.stop('bundle_cache volume wiped.')
+ }
+
+ console.log(`\n${pc.bold('Rebuilding dev image...')}\n`)
+ await dockerCompose([...composeArgs, 'build', 'web', 'worker'], ctx.projectDir, {
+ stdio: 'inherit',
+ })
+
+ p.note(
+ [
+ `Image rebuilt. Start the stack with ${pc.bold('spree dev')}.`,
+ flags.resetBundle
+ ? `On next boot, gems will re-seed into a fresh ${pc.dim('bundle_cache')} volume.`
+ : '',
+ ]
+ .filter(Boolean)
+ .join('\n'),
+ 'Build complete',
+ )
+ })
+}
+
+// Pre-eject projects have `docker-compose.dev.yml` alongside the prod compose;
+// we need `-f` to build against it. Post-eject the two files are the same
+// (eject overwrites docker-compose.yml with the dev one), so `-f` is harmless.
+function composeFileArgs(projectDir: string): string[] {
+ const devCompose = path.join(projectDir, 'docker-compose.dev.yml')
+ return fs.existsSync(devCompose) ? ['-f', 'docker-compose.dev.yml'] : []
+}
diff --git a/packages/cli/src/commands/db.ts b/packages/cli/src/commands/db.ts
new file mode 100644
index 0000000000..f0a345cedd
--- /dev/null
+++ b/packages/cli/src/commands/db.ts
@@ -0,0 +1,46 @@
+import * as p from '@clack/prompts'
+import type { Command } from 'commander'
+import { detectProject } from '../context.js'
+import { dockerComposeExec } from '../docker.js'
+
+// Two related but independent commands: db:reset (destructive) and db:console
+// (read-only). Registered as flat commands rather than under a `spree db`
+// parent because Rails uses the same flat style (`rails db:reset`).
+export function registerDbCommand(program: Command): void {
+ program
+ .command('db:reset')
+ .description('Drop, create, migrate, and seed the dev database (destructive)')
+ .option('--yes', 'skip the confirmation prompt (for CI)')
+ .action(async (flags: { yes?: boolean }) => {
+ const ctx = detectProject()
+
+ if (!flags.yes) {
+ const confirmed = await p.confirm({
+ message: 'This will drop the spree_development database. Continue?',
+ initialValue: false,
+ })
+ if (p.isCancel(confirmed) || !confirmed) {
+ p.cancel('Cancelled.')
+ process.exit(0)
+ }
+ }
+
+ // Single Rails invocation chaining all four tasks so any failure short-circuits.
+ await dockerComposeExec(
+ ['bin/rails', 'db:drop', 'db:create', 'db:migrate', 'db:seed'],
+ ctx.projectDir,
+ )
+ })
+
+ program
+ .command('db:console')
+ .description('Open a psql session against the dev database')
+ .action(async () => {
+ const ctx = detectProject()
+ // Targets the postgres service, not web. The dev compose sets
+ // POSTGRES_HOST_AUTH_METHOD=trust so no password is needed.
+ await dockerComposeExec(['psql', '-U', 'postgres', 'spree_development'], ctx.projectDir, {
+ service: 'postgres',
+ })
+ })
+}
diff --git a/packages/cli/src/commands/eject.ts b/packages/cli/src/commands/eject.ts
index dde2fa19a5..b4893a6d42 100644
--- a/packages/cli/src/commands/eject.ts
+++ b/packages/cli/src/commands/eject.ts
@@ -6,10 +6,17 @@ import pc from 'picocolors'
import { detectProject } from '../context.js'
import { dockerCompose } from '../docker.js'
+// Switch the project from the prebuilt-image compose to the bind-mounted
+// dev compose. Source under ./backend becomes live in the container —
+// edits reload via Zeitwerk on next request, no rebuild needed.
+//
+// Image rebuilds (`spree build`) are only required for Dockerfile or
+// .ruby-version changes; gem changes go through `spree bundle add` and
+// persist in the bundle_cache volume.
export function registerEjectCommand(program: Command) {
program
.command('eject')
- .description('Switch from prebuilt Docker image to building from local backend/')
+ .description('Switch to the dev compose: bind-mount ./backend with hot reload')
.action(async () => {
const ctx = detectProject()
@@ -25,25 +32,24 @@ export function registerEjectCommand(program: Command) {
process.exit(1)
}
- // Replace docker-compose.yml with the dev version
+ // Replace docker-compose.yml with the dev version. The dev compose has
+ // `build:` defined, so `up -d` below will build on first invocation —
+ // no separate explicit build step needed.
fs.copyFileSync(devCompose, path.join(ctx.projectDir, 'docker-compose.yml'))
- console.log(`\n${pc.bold('Building backend from local source...')}\n`)
- await dockerCompose(['build'], ctx.projectDir, { stdio: 'inherit' })
-
- console.log(`\n${pc.bold('Restarting services...')}\n`)
+ console.log(`\n${pc.bold('Switching to dev compose (bind-mounts ./backend)...')}\n`)
await dockerCompose(['up', '-d'], ctx.projectDir, { stdio: 'inherit' })
p.note(
[
- `Backend now builds from ${pc.bold('./backend')}`,
+ `Backend is now bind-mounted from ${pc.bold('./backend')} — edits are live.`,
'',
'You can now customize:',
- ` ${pc.dim('backend/Gemfile')} — add gems`,
- ` ${pc.dim('backend/app/')} — models, controllers, etc.`,
- ` ${pc.dim('backend/config/')} — Rails configuration`,
+ ` ${pc.dim('backend/app/')} — models, controllers, services (instant reload)`,
+ ` ${pc.dim('backend/config/')} — Rails configuration (instant reload)`,
+ ` ${pc.dim('backend/Gemfile')} — add gems via ${pc.bold('spree bundle add <gem>')}`,
'',
- `Run ${pc.bold('npx spree dev')} to restart with your changes.`,
+ `Rebuild only on Dockerfile / .ruby-version changes: ${pc.bold('spree build')}`,
].join('\n'),
'Ejected!',
)
diff --git a/packages/cli/src/commands/generate.ts b/packages/cli/src/commands/generate.ts
new file mode 100644
index 0000000000..f1cf11123d
--- /dev/null
+++ b/packages/cli/src/commands/generate.ts
@@ -0,0 +1,25 @@
+import type { Command } from 'commander'
+import { detectProject } from '../context.js'
+import { dockerComposeExec } from '../docker.js'
+
+// Run a Spree generator. Auto-prefixes `spree:` so the common case stays
+// short: `spree generate model Brand` → `bin/rails g spree:model Brand`.
+//
+// If the name already contains a colon (e.g. `spree:model`, `active_storage:install`)
+// it's treated as fully-qualified and forwarded as-is. For non-Spree generators
+// reach for `spree rails g <name> …` directly.
+export function registerGenerateCommand(program: Command): void {
+ program
+ .command('generate')
+ .alias('g')
+ .description('Run a Spree generator (auto-prefixes `spree:`)')
+ .argument('<name>', 'generator name (`model`, `model_decorator`, …)')
+ .argument('[args...]', 'arguments to pass to the generator')
+ .allowUnknownOption(true)
+ .passThroughOptions(true)
+ .action(async (name: string, args: string[]) => {
+ const ctx = detectProject()
+ const generator = name.includes(':') ? name : `spree:${name}`
+ await dockerComposeExec(['bin/rails', 'g', generator, ...args], ctx.projectDir)
+ })
+}
diff --git a/packages/cli/src/commands/migrate.ts b/packages/cli/src/commands/migrate.ts
new file mode 100644
index 0000000000..6bb84e16c0
--- /dev/null
+++ b/packages/cli/src/commands/migrate.ts
@@ -0,0 +1,37 @@
+import type { Command } from 'commander'
+import { detectProject } from '../context.js'
+import { dockerComposeExec } from '../docker.js'
+
+// Three flat commands matching Rails's own naming: `spree migrate`,
+// `spree migrate:rollback [STEP=n]`, `spree migrate:status`.
+export function registerMigrateCommand(program: Command): void {
+ program
+ .command('migrate')
+ .description('Run pending database migrations (`bin/rails db:migrate`)')
+ .argument('[args...]', 'extra args forwarded to db:migrate')
+ .allowUnknownOption(true)
+ .passThroughOptions(true)
+ .action(async (args: string[]) => {
+ const ctx = detectProject()
+ await dockerComposeExec(['bin/rails', 'db:migrate', ...args], ctx.projectDir)
+ })
+
+ program
+ .command('migrate:rollback')
+ .description('Roll back the last migration (`STEP=n` to roll back n steps)')
+ .argument('[args...]', 'extra args forwarded to db:rollback (e.g. STEP=2)')
+ .allowUnknownOption(true)
+ .passThroughOptions(true)
+ .action(async (args: string[]) => {
+ const ctx = detectProject()
+ await dockerComposeExec(['bin/rails', 'db:rollback', ...args], ctx.projectDir)
+ })
+
+ program
+ .command('migrate:status')
+ .description('Show migration status (`bin/rails db:migrate:status`)')
+ .action(async () => {
+ const ctx = detectProject()
+ await dockerComposeExec(['bin/rails', 'db:migrate:status'], ctx.projectDir)
+ })
+}
diff --git a/packages/cli/src/commands/routes.ts b/packages/cli/src/commands/routes.ts
new file mode 100644
index 0000000000..ea44e3297e
--- /dev/null
+++ b/packages/cli/src/commands/routes.ts
@@ -0,0 +1,20 @@
+import type { Command } from 'commander'
+import { detectProject } from '../context.js'
+import { dockerComposeExec } from '../docker.js'
+
+// `bin/rails routes [-g pattern] [-c controller] [--expanded]` passthrough.
+// spree routes
+// spree routes -g products
+// spree routes -c Spree::Api::V3::Store::ProductsController
+export function registerRoutesCommand(program: Command): void {
+ program
+ .command('routes')
+ .description('Show Rails routes (`bin/rails routes`)')
+ .argument('[args...]', 'arguments to pass to bin/rails routes')
+ .allowUnknownOption(true)
+ .passThroughOptions(true)
+ .action(async (args: string[]) => {
+ const ctx = detectProject()
+ await dockerComposeExec(['bin/rails', 'routes', ...args], ctx.projectDir)
+ })
+}
diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.ts
index ab1320b7a9..66f8c6ae45 100644
--- a/packages/cli/src/index.ts
+++ b/packages/cli/src/index.ts
@@ -1,16 +1,21 @@
import { Command } from 'commander'
import pc from 'picocolors'
import { registerApiKeyCommand } from './commands/api-key.js'
+import { registerBuildCommand } from './commands/build.js'
import { registerBundleCommand } from './commands/bundle.js'
import { registerConsoleCommand } from './commands/console.js'
+import { registerDbCommand } from './commands/db.js'
import { registerDevCommand } from './commands/dev.js'
import { registerEjectCommand } from './commands/eject.js'
import { registerExecCommand } from './commands/exec.js'
+import { registerGenerateCommand } from './commands/generate.js'
import { registerInitCommand } from './commands/init.js'
import { registerLogsCommand } from './commands/logs.js'
+import { registerMigrateCommand } from './commands/migrate.js'
import { registerOpenCommand } from './commands/open.js'
import { registerRailsCommand } from './commands/rails.js'
import { registerRakeCommand } from './commands/rake.js'
+import { registerRoutesCommand } from './commands/routes.js'
import { registerSampleDataCommand } from './commands/sample-data.js'
import { registerSeedCommand } from './commands/seed.js'
import { registerStopCommand } from './commands/stop.js'
@@ -34,6 +39,13 @@ registerStopCommand(program)
registerUpdateCommand(program)
registerLogsCommand(program)
registerEjectCommand(program)
+registerBuildCommand(program)
+
+// Dev workflow
+registerGenerateCommand(program)
+registerMigrateCommand(program)
+registerDbCommand(program)
+registerRoutesCommand(program)
// Run things inside the container
registerExecCommand(program)