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.

7.7 KB
Raw Blame
#!/usr/bin/env bash
# Provision the current worktree as a self-contained dev environment:
# its own server/ clone, .env, database (copied from the seeded template),
# gems, node modules, and dashboard proxy config. Idempotent — safe to re-run.
# Usage: setup.sh [branch]   (branch defaults to the current one; worktrunk
# passes it explicitly from the pre-start hook)
set -euo pipefail
WT_BRANCH="${1:-}"
source "$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/lib.sh"
cd "$(worktree_root)"

# Clone the Next.js storefront and point it at this worktree's Rails + seeded
# publishable keys. Unlike server/, the clone keeps its .git: the starter is a
# disposable host app, while the storefront is a repo we actually develop in and
# push from, so each worktree gets its own branch-able checkout.
#
# .env.local is only written when absent, so local edits (Stripe keys, a
# different channel) survive a re-run. It is regenerated by dev-storefront.sh
# on every boot for the values that follow the worktree — the API URL and keys.
setup_storefront() {
  if [ ! -d storefront ]; then
    echo "▸ Cloning storefront into storefront/"
    # Non-fatal: the storefront is optional, and most worktrees never boot it.
    # A failure here (offline, no access) must not abandon a provisioning run
    # that has already created the database and installed gems.
    if ! git clone --quiet --branch "$STOREFRONT_BRANCH" "$STOREFRONT_REPO" storefront; then
      echo "  ! Could not clone the storefront — skipping. Re-run this script to retry." >&2
      rm -rf storefront
      return 0
    fi
  fi

  if [ ! -f storefront/.env.local ]; then
    write_storefront_env
  fi
}

echo "▸ Provisioning worktree '$(branch_slug)' (db: $(db_name))"

primary_root=$(git worktree list --porcelain | head -1 | sed 's/^worktree //')
created_primary_server=0

if [ ! -d server ]; then
  echo "▸ Cloning spree-starter into server/"
  git clone --depth 1 https://github.com/spree/spree-starter.git server
  rm -rf server/.git server/.gitignore

  # Adopt the primary checkout's migration set (and its schema snapshot) before
  # the first migrate. `spree:install:migrations` stamps newly-copied gem
  # migrations with the current time, so a fresh clone would give any gem
  # migration the starter has not committed yet a version the template database
  # (built from the primary's server) has never seen — and db:migrate would
  # re-run it against tables the template already has. Copying the primary's
  # files keeps the versions identical; migrations this branch adds on top are
  # still installed and run normally below.
  if [ "$primary_root" != "$(pwd)" ] && [ -d "$primary_root/server/db/migrate" ]; then
    rsync -a --delete "$primary_root/server/db/migrate/" server/db/migrate/
    [ -f "$primary_root/server/db/schema.rb" ] && cp "$primary_root/server/db/schema.rb" server/db/schema.rb
  else
    # This IS the primary's server/, freshly cloned, so the renumbering above
    # has just happened to the migration set every other worktree copies. Any
    # existing template was built against the old numbers and is now unusable;
    # mark it so, and let the rebuild below replace it.
    created_primary_server=1
  fi
fi

if [ ! -f server/.env ]; then
  cat > server/.env <<EOF
SPREE_PATH=$(pwd)
SECRET_KEY_BASE=$(openssl rand -hex 64)
DATABASE_NAME=$(db_name)
DATABASE_NAME_TEST=$(test_db_name)
SPREE_DASHBOARD_URL=$(dashboard_url)
SPREE_SELLER_PANEL_URL=$(seller_url)
RAILS_HOST=$(rails_host)
RAILS_PROTOCOL=https
SMTP_HOST=$MAILPIT_HOST
SMTP_PORT=$MAILPIT_SMTP_PORT
EOF
fi

# Backfill for worktrees provisioned before this line existed — the seed's
# first-run setup link is built from it.
if ! grep -q '^SPREE_DASHBOARD_URL=' server/.env; then
  printf 'SPREE_DASHBOARD_URL=%s\n' "$(dashboard_url)" >> server/.env
fi

# Backfill likewise: without these, attachment URLs in API payloads fall back
# to the store's seeded `localhost:3000`, so dashboard images 404. portless
# terminates TLS in front of the dev server, so the public scheme is https even
# though Rails itself is serving plain http.
if ! grep -q '^RAILS_HOST=' server/.env; then
  printf 'RAILS_HOST=%s\n' "$(rails_host)" >> server/.env
fi

if ! grep -q '^RAILS_PROTOCOL=' server/.env; then
  printf 'RAILS_PROTOCOL=%s\n' 'https' >> server/.env
fi

# Active Record encryption keys, so Spree's encrypted columns (webhook signing
# keys, gateway customer ids, OAuth tokens) are encrypted in dev like they are
# in a scaffolded project. Per worktree: the seeded template holds no encrypted
# rows. Only added when missing — changing them makes encrypted rows unreadable.
for key in PRIMARY_KEY DETERMINISTIC_KEY KEY_DERIVATION_SALT; do
  if ! grep -q "^ACTIVE_RECORD_ENCRYPTION_${key}=" server/.env; then
    printf 'ACTIVE_RECORD_ENCRYPTION_%s=%s\n' "$key" "$(openssl rand -hex 16)" >> server/.env
  fi
done

# Mail goes to Mailpit, as it does in the starter's Docker stack. Without
# SMTP_HOST the starter falls back to a delivery method that does not exist,
# so every email raises rather than being delivered anywhere.
if ! grep -q '^SMTP_HOST=' server/.env; then
  printf 'SMTP_HOST=%s\nSMTP_PORT=%s\n' "$MAILPIT_HOST" "$MAILPIT_SMTP_PORT" >> server/.env
fi

# Backfill likewise: without it a seller's invitation links to the operator's
# dashboard, where accepting issues an admin session rather than a seller one.
if ! grep -q '^SPREE_SELLER_PANEL_URL=' server/.env; then
  printf 'SPREE_SELLER_PANEL_URL=%s\n' "$(seller_url)" >> server/.env
fi

require_current_starter

# Never copy a template that no longer matches the migrations this worktree is
# about to run: the mismatch would otherwise surface as a duplicate-table error
# from db:migrate several minutes in, long after the database, the gems and the
# node modules have been installed.
drifted=$(template_drift "$primary_root")
if [ -n "$drifted" ] && ! db_exists "$(db_name)"; then
  if [ "$created_primary_server" = 1 ]; then
    # We caused the drift moments ago by re-cloning this checkout's server/, so
    # rebuild rather than sending the developer away to run a script we could
    # have run ourselves.
    echo "▸ server/ was re-created, so $TEMPLATE_DB no longer matches — rebuilding it"
    "$(dirname "${BASH_SOURCE[0]}")/make-template.sh"
  else
    echo "Template database '$TEMPLATE_DB' is out of date: it records $(echo "$drifted" | grep -c .) migrations that no longer exist in $primary_root/server/db/migrate." >&2
    echo "This happens when that checkout's server/ is re-created, which renumbers the gem migrations." >&2
    echo "Rebuild it, then re-run this script:  pnpm wt:template" >&2
    exit 1
  fi
fi

if ! db_exists "$(db_name)"; then
  if ! db_exists "$TEMPLATE_DB"; then
    echo "Template database '$TEMPLATE_DB' missing — run scripts/worktree/make-template.sh first." >&2
    exit 1
  fi
  echo "▸ Creating $(db_name) from $TEMPLATE_DB"
  createdb "${PG_ARGS[@]}" -T "$TEMPLATE_DB" "$(db_name)"
fi

# Warm boot caches from the primary checkout's server, if it has any.
if [ -d "$primary_root/server/tmp/cache/bootsnap" ] && [ ! -d server/tmp/cache/bootsnap ]; then
  mkdir -p server/tmp/cache
  cp -R "$primary_root/server/tmp/cache/bootsnap" server/tmp/cache/
fi

echo "▸ Installing gems + migrations"
(cd server && bundle install --quiet && bin/rails spree:install:migrations db:migrate)

echo "▸ Installing node modules"
pnpm install --silent

mkdir -p packages/dashboard-starter
printf 'VITE_API_PROXY_TARGET=%s\n' "$(rails_url)" > packages/dashboard-starter/.env.local

setup_storefront

echo "✓ Worktree ready"
echo "  rails:      $(rails_url)   (pnpm wt:dev)"
echo "  dashboard:  $(dashboard_url)   (pnpm wt:dashboard)"
echo "  seller:     $(seller_url)   (pnpm wt:seller)"
echo "  storefront: $(storefront_url)   (pnpm wt:storefront)"
echo "  mail:       $(mailpit_url)"
warn_unless_mailpit