diff --git a/CLAUDE.md b/CLAUDE.md index 897467d..4e7e302 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -131,7 +131,7 @@ All commands support `--json` for machine-readable output. 1. Export MySQL dump via SSH (`wp db export`) 2. Strip SSH MOTD from dump output 3. Convert MySQL → SQLite using `mysql2sqlite` (awk script) -4. Import directly into `.ht.sqlite` via `sqlite3` CLI +4. Import directly into `.ht.sqlite` via `better-sqlite3`, into a wiped `wp-content/database/` (the SQLite plugin migrates it into its secret dir on first boot; a leftover `db-path.php` would make WP ignore it) 5. Rename table prefix to `wp_` (tables + meta keys + option names) 6. Search-replace cloud URL → `http://127.0.0.1:` across all tables 7. Pull wp-content via rsync (plugins, themes, uploads) @@ -141,6 +141,7 @@ All commands support `--json` for machine-readable output. ### DB push flow (`local push --with-db`) — SQLite → MySQL (the reverse of clone) Pushes the local Playground DB back to the cloud MySQL, OVERWRITING it. Implemented in `pushDatabase()` (`commands/local.ts`) + `lib/sqlite-to-mysql.ts`. +0. Locate the local DB with `resolveLocalSqlitePath()` (`lib/local-sqlite.ts`): sqlite-database-integration 3.x stores it at `wp-content/database/.ht./.ht.sqlite`, recorded in `db-path.php` (parsed, never executed). Order: `db-path.php` → `.ht.*/.ht.sqlite` glob (newest mtime, always warns: WP never scans for these) → legacy `.ht.sqlite`. Push goes through `resolvePushSqlitePath()`, which REFUSES when `db-path.php` exists but was unusable (WP treats it as the authority, so any fallback is not the live DB). Also drives `isClone` in `local-env.ts`. 1. Read local siteurl from `wp_options` (authoritative; handles port drift) 2. Discover cloud `table_prefix` + existing tables via SSH — **MOTD-stripped** (`parseTablePrefix`/`parseSqlTableNames` in `lib/local-instance.ts`); a banner leaking in would mismatch every table → silent empty push 3. `generateMysqlDump()`: **data-only** (`TRUNCATE`+`INSERT`, no `CREATE TABLE`) for local `wp_*` tables whose cloud-prefixed name exists on the cloud (intersection — so a missing-table TRUNCATE can't abort the import). Pins `sql_mode` (backslash escaping), `safeIntegers(true)` (no >2^53 loss), BLOB→`0x` hex (empty→`''`), byte-budgeted INSERT batching diff --git a/src/__tests__/local-sqlite.test.ts b/src/__tests__/local-sqlite.test.ts new file mode 100644 index 0000000..e8e71e6 --- /dev/null +++ b/src/__tests__/local-sqlite.test.ts @@ -0,0 +1,242 @@ +import { describe, it, expect, beforeEach, afterEach } from 'vitest'; +import { mkdtempSync, mkdirSync, writeFileSync, rmSync, utimesSync, symlinkSync, realpathSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import path from 'node:path'; +import { resolveLocalSqlitePath, resolvePushSqlitePath, parseDbPathPhp, isInsideDir } from '../lib/local-sqlite.js'; +import { buildServerArgs } from '../lib/local-env.js'; + +let root: string; +let dbDir: string; +const instance = () => ({ path: root }); + +/** A non-empty stand-in for a SQLite file (the resolver only checks it is a non-empty regular file). */ +function dbFile(p: string, tag = 'x'): string { + mkdirSync(path.dirname(p), { recursive: true }); + writeFileSync(p, `SQLite format 3\0${tag}`); + return realpathSync(p); +} +/** Exactly what WP_SQLite_Storage::publish_database_path() writes. */ +function dbPathPhp(rel: string): void { + writeFileSync(path.join(dbDir, 'db-path.php'), + ` { + root = mkdtempSync(path.join(tmpdir(), 'iwp-sqlite-')); + dbDir = path.join(root, 'wp-content', 'database'); + mkdirSync(dbDir, { recursive: true }); +}); +afterEach(() => rmSync(root, { recursive: true, force: true })); + +describe('resolveLocalSqlitePath', () => { + it('uses the path recorded in db-path.php, over a stale legacy .ht.sqlite and another secret dir', () => { + const secret = '.ht.51e23a042b788a98d0283c084cb1962c'; + const want = dbFile(path.join(dbDir, secret, '.ht.sqlite'), 'live'); + dbPathPhp(`${secret}/.ht.sqlite`); + dbFile(path.join(dbDir, '.ht.sqlite'), 'stale'); + const other = dbFile(path.join(dbDir, '.ht.ffff', '.ht.sqlite'), 'other'); + const future = new Date(Date.now() + 60_000); + utimesSync(other, future, future); // newer than `want`: the recorded path must still win + + const r = resolveLocalSqlitePath(instance()); + expect(r).toMatchObject({ path: want, source: 'db-path.php', warnings: [], recordedPathIgnored: false }); + }); + + it('finds the path literal in a db-path.php that has other statements (it is parsed, not run)', () => { + writeFileSync(path.join(dbDir, 'db-path.php'), + `/.ht.sqlite', () => { + const want = dbFile(path.join(dbDir, '.ht.0123abcd', '.ht.sqlite')); + // Plugin housekeeping files also start with ".ht." and must not be mistaken for dirs. + writeFileSync(path.join(dbDir, '.ht.sqlite.lock'), 'x'); + writeFileSync(path.join(dbDir, '.ht.sqlite.maintenance'), ''); + const r = resolveLocalSqlitePath(instance()); + expect(r).toMatchObject({ path: want, source: 'secret-dir', recordedPathIgnored: false }); + // WordPress never scans for .ht.* dirs, so even a lone match is flagged. + expect(r.warnings).toHaveLength(1); + expect(r.warnings[0]).toContain('No usable db-path.php'); + }); + + it('order: with no db-path.php, a secret dir wins over a legacy .ht.sqlite', () => { + const want = dbFile(path.join(dbDir, '.ht.0123abcd', '.ht.sqlite'), 'secret'); + dbFile(path.join(dbDir, '.ht.sqlite'), 'legacy'); + expect(resolveLocalSqlitePath(instance())).toMatchObject({ path: want, source: 'secret-dir' }); + }); + + it.skipIf(process.platform === 'win32')('works when the instance path itself is reached through a symlink', () => { + const want = dbFile(path.join(dbDir, '.ht.abc', '.ht.sqlite')); + dbPathPhp('.ht.abc/.ht.sqlite'); + const link = path.join(mkdtempSync(path.join(tmpdir(), 'iwp-link-')), 'home'); + symlinkSync(root, link); + try { + expect(resolveLocalSqlitePath({ path: link })).toMatchObject({ path: want, source: 'db-path.php' }); + } finally { + rmSync(path.dirname(link), { recursive: true, force: true }); + } + }); + + it.each([['.ht.aaaa', '.ht.bbbb'], ['.ht.bbbb', '.ht.aaaa']])( + 'glob with several matches: picks the newest by mtime and warns (newest=%s)', (newestDir, olderDir) => { + // Run with each dir as the newest, so directory-listing order cannot explain the pick. + const newest = dbFile(path.join(dbDir, newestDir, '.ht.sqlite')); + const older = dbFile(path.join(dbDir, olderDir, '.ht.sqlite')); + utimesSync(older, new Date('2020-01-01'), new Date('2020-01-01')); + utimesSync(newest, new Date('2026-01-01'), new Date('2026-01-01')); + const r = resolveLocalSqlitePath(instance()); + expect(r.path).toBe(newest); + expect(r.source).toBe('secret-dir'); + expect(r.warnings).toHaveLength(1); + expect(r.warnings[0]).toContain('Found 2 SQLite databases'); + expect(r.warnings[0]).toContain(older); + }); + + it('unparseable db-path.php: warns and falls back to the glob', () => { + writeFileSync(path.join(dbDir, 'db-path.php'), ' { + const want = dbFile(path.join(dbDir, '.ht.sqlite')); + expect(resolveLocalSqlitePath(instance())).toMatchObject({ path: want, source: 'legacy', warnings: [] }); + }); + + it('none found: returns null and lists every location checked', () => { + // Empty files are not databases. + mkdirSync(path.join(dbDir, '.ht.0123')); + writeFileSync(path.join(dbDir, '.ht.0123', '.ht.sqlite'), ''); + writeFileSync(path.join(dbDir, '.ht.sqlite'), ''); + const r = resolveLocalSqlitePath(instance()); + expect(r.path).toBeNull(); + expect(r.source).toBeNull(); + expect(r.checked).toEqual([ + path.join(dbDir, 'db-path.php'), + path.join(dbDir, '.ht.*', '.ht.sqlite'), + path.join(dbDir, '.ht.sqlite'), + path.join(dbDir, '.ht.sqlite.php'), + ]); + }); + + it('none found when wp-content/database does not exist', () => { + rmSync(dbDir, { recursive: true }); + const r = resolveLocalSqlitePath(instance()); + expect(r.path).toBeNull(); + expect(r.checked).toContain(path.join(dbDir, 'db-path.php')); + expect(r.checked).toContain(path.join(dbDir, '.ht.sqlite')); + }); + + it('wp-content/database is a file, not a dir: not found, no throw (runs on every local start)', () => { + rmSync(dbDir, { recursive: true }); + writeFileSync(dbDir, 'not a dir'); + expect(resolveLocalSqlitePath(instance()).path).toBeNull(); + }); + + it('rejects a db-path.php path that traverses outside wp-content/database', () => { + // A REAL database exists at the traversal target, so only the containment check can refuse it. + const outside = dbFile(path.join(root, 'outside', '.ht.sqlite'), 'secret'); + dbPathPhp('../../outside/.ht.sqlite'); + const legacy = dbFile(path.join(dbDir, '.ht.sqlite')); + const r = resolveLocalSqlitePath(instance()); + expect(r.path).not.toBe(outside); + expect(r).toMatchObject({ path: legacy, source: 'legacy', recordedPathIgnored: true }); + expect(r.warnings[0]).toContain('outside wp-content/database'); + }); + + it.skipIf(process.platform === 'win32')('rejects a secret dir that is a symlink to outside wp-content/database', () => { + dbFile(path.join(root, 'elsewhere', '.ht.sqlite'), 'secret'); + symlinkSync(path.join(root, 'elsewhere'), path.join(dbDir, '.ht.0123abcd')); + dbPathPhp('.ht.0123abcd/.ht.sqlite'); + const r = resolveLocalSqlitePath(instance()); + expect(r.path).toBeNull(); + expect(r.warnings[0]).toContain('outside wp-content/database'); + }); +}); + +describe('resolvePushSqlitePath (what local push --with-db may overwrite the cloud with)', () => { + it('pushes the recorded database', () => { + const want = dbFile(path.join(dbDir, '.ht.abc', '.ht.sqlite')); + dbPathPhp('.ht.abc/.ht.sqlite'); + expect(resolvePushSqlitePath(instance())).toEqual({ path: want, warnings: [] }); + }); + + it('refuses when db-path.php exists but points outside, even though a legacy DB exists', () => { + dbFile(path.join(root, 'outside', '.ht.sqlite')); + dbPathPhp('../../outside/.ht.sqlite'); + dbFile(path.join(dbDir, '.ht.sqlite')); + const r = resolvePushSqlitePath(instance()); + expect('error' in r && r.error).toContain('db-path.php exists but does not point to a usable database'); + }); + + it('refuses when the recorded file is missing, even though a secret dir exists', () => { + dbPathPhp('.ht.gone/.ht.sqlite'); + dbFile(path.join(dbDir, '.ht.other', '.ht.sqlite')); + const r = resolvePushSqlitePath(instance()); + expect('error' in r && r.error).toContain('db-path.php exists'); + }); + + it('pushes a legacy DB when there is no db-path.php', () => { + const want = dbFile(path.join(dbDir, '.ht.sqlite')); + expect(resolvePushSqlitePath(instance())).toEqual({ path: want, warnings: [] }); + }); + + it('none found: the error lists every path checked', () => { + const r = resolvePushSqlitePath(instance()); + expect('error' in r).toBe(true); + const msg = 'error' in r ? r.error : ''; + for (const p of [path.join(dbDir, 'db-path.php'), path.join(dbDir, '.ht.*', '.ht.sqlite'), path.join(dbDir, '.ht.sqlite')]) { + expect(msg).toContain(p); + } + }); +}); + +describe('buildServerArgs isClone (start an instance with a persisted DB in clone mode)', () => { + const inst = () => ({ name: 't', port: 9400, php: '8.3', wp: 'latest', path: root, createdAt: '' }); + const mountsWholeWpContent = (args: string[]) => args.some((a) => a.includes('before-install')); + + it('a DB at the db-path.php location → clone-mode mounts (database dir mounted after install)', () => { + dbFile(path.join(dbDir, '.ht.abc', '.ht.sqlite')); + dbPathPhp('.ht.abc/.ht.sqlite'); + const args = buildServerArgs(inst()); + expect(mountsWholeWpContent(args)).toBe(false); + expect(args.join(' ')).toContain(dbDir); + }); + + it('no DB yet → fresh-mode mount of the whole wp-content before install', () => { + expect(mountsWholeWpContent(buildServerArgs(inst()))).toBe(true); + }); +}); + +describe('parseDbPathPhp', () => { + it('reads the __DIR__ literal in either quote style', () => { + expect(parseDbPathPhp("return __DIR__ . '/.ht.ab/.ht.sqlite';")).toBe('.ht.ab/.ht.sqlite'); + expect(parseDbPathPhp('return __DIR__."/.ht.ab/.ht.sqlite";')).toBe('.ht.ab/.ht.sqlite'); + }); + it('returns null for anything else', () => { + expect(parseDbPathPhp("return '/abs/.ht.sqlite';")).toBeNull(); + expect(parseDbPathPhp(' { + it('posix', () => { + expect(isInsideDir('/a/db', '/a/db/.ht.x/.ht.sqlite', path.posix)).toBe(true); + expect(isInsideDir('/a/db', '/a/db', path.posix)).toBe(false); + expect(isInsideDir('/a/db', '/a/dbx/.ht.sqlite', path.posix)).toBe(false); + expect(isInsideDir('/a/db', '/a/outside', path.posix)).toBe(false); + }); + it('windows', () => { + const w = path.win32; + expect(isInsideDir('C:\\s\\wp-content\\database', 'C:\\s\\wp-content\\database\\.ht.x\\.ht.sqlite', w)).toBe(true); + expect(isInsideDir('C:\\s\\wp-content\\database', 'C:\\s\\wp-content\\databasex\\.ht.sqlite', w)).toBe(false); + expect(isInsideDir('C:\\s\\wp-content\\database', 'D:\\s\\wp-content\\database\\.ht.sqlite', w)).toBe(false); + expect(isInsideDir('C:\\s\\wp-content\\database', 'C:\\s\\outside\\.ht.sqlite', w)).toBe(false); + // ..foo is a legal name inside the dir, not a traversal + expect(isInsideDir('C:\\s\\db', 'C:\\s\\db\\..foo\\.ht.sqlite', w)).toBe(true); + }); +}); diff --git a/src/commands/local.ts b/src/commands/local.ts index 9d4a1f4..c346507 100644 --- a/src/commands/local.ts +++ b/src/commands/local.ts @@ -35,6 +35,7 @@ import { listLocalFiles } from '../lib/sftp-sync.js'; import { sanitizeName, defaultInstanceName, pushTargetRef, parseTablePrefix, parseSqlTableNames } from '../lib/local-instance.js'; import { generateMysqlDump } from '../lib/sqlite-to-mysql.js'; import { loadSqlite } from '../lib/sqlite.js'; +import { resolvePushSqlitePath } from '../lib/local-sqlite.js'; import { success, error, table, spinner, info, isJsonMode } from '../lib/output.js'; import type { LocalInstance, SshConnection } from '../types.js'; @@ -624,7 +625,10 @@ export function registerLocalCommand(program: Command): void { const dbDir = join(dir, 'wp-content', 'database'); const sqliteDbPath = join(dbDir, '.ht.sqlite'); - // Clean slate for database dir + // Clean slate for database dir. Load-bearing: sqlite-database-integration 3.x + // reads the path recorded in db-path.php first and only migrates a legacy + // .ht.sqlite when no recorded DB exists — so a leftover db-path.php + .ht./ + // would make WordPress silently ignore the .ht.sqlite written below. if (existsSync(dbDir)) rmSync(dbDir, { recursive: true, force: true }); mkdirSync(dbDir, { recursive: true }); @@ -810,11 +814,16 @@ function isShellSafeUrl(u: string): boolean { * (serialization-safe). Honors --dry-run / --no-backup / --force. */ async function pushDatabase(instance: LocalInstance, site: any, conn: SshConnection, opts: any): Promise<'done' | 'cancelled' | 'dry'> { - const sqlitePath = join(instance.path, 'wp-content', 'database', '.ht.sqlite'); - if (!existsSync(sqlitePath)) { - error('No local database found (expected wp-content/database/.ht.sqlite). Skipping DB push.'); + // sqlite-database-integration 3.x keeps the DB in a secret .ht./ dir recorded + // in db-path.php, not at the legacy .ht.sqlite — see resolveLocalSqlitePath(). + const resolved = resolvePushSqlitePath(instance); + for (const w of resolved.warnings) console.error(chalk.yellow('! ' + w)); + if ('error' in resolved) { + error('Skipping DB push. ' + resolved.error); process.exit(1); } + const sqlitePath = resolved.path; + info(`Local database: ${chalk.dim(sqlitePath)}`); const wpPath = remoteDocRoot(conn); diff --git a/src/lib/local-env.ts b/src/lib/local-env.ts index cd22021..4d68c1a 100644 --- a/src/lib/local-env.ts +++ b/src/lib/local-env.ts @@ -9,6 +9,7 @@ import { homedir } from 'node:os'; import net from 'node:net'; import chalk from 'chalk'; import { isJsonMode } from './output.js'; +import { resolveLocalSqlitePath } from './local-sqlite.js'; import type { LocalInstance } from '../types.js'; const LOCAL_BASE_DIR = join(homedir(), '.instawp', 'local'); @@ -186,10 +187,12 @@ export function buildMountArgs( return [`${opts.beforeInstall ? '--mount-before-install' : '--mount'}=${hostPath}:${vfsPath}`]; } -function buildServerArgs(instance: LocalInstance, blueprint?: string): string[] { +export function buildServerArgs(instance: LocalInstance, blueprint?: string): string[] { const wpContentDir = join(instance.path, 'wp-content'); + // "Has a persisted DB" — at the db-path.php / .ht./ location of + // sqlite-database-integration 3.x, or the legacy .ht.sqlite. const isClone = existsSync(join(instance.path, 'sqlite-import.sql')) || - existsSync(join(wpContentDir, 'database', '.ht.sqlite')); + resolveLocalSqlitePath(instance).path !== null; const args = [ 'server', diff --git a/src/lib/local-sqlite.ts b/src/lib/local-sqlite.ts new file mode 100644 index 0000000..f1f9c22 --- /dev/null +++ b/src/lib/local-sqlite.ts @@ -0,0 +1,179 @@ +import { existsSync, readFileSync, readdirSync, realpathSync, statSync } from 'node:fs'; +import path from 'node:path'; + +/** + * Where a local Playground instance keeps its SQLite database. + * + * sqlite-database-integration 3.x (`WP_SQLite_Storage`, which Playground downloads + * at its latest version) no longer stores the DB at wp-content/database/.ht.sqlite. + * It moves it into a secret directory and records the location in + * wp-content/database/db-path.php: + * + * return __DIR__ . '/.ht.<32 hex chars>/.ht.sqlite'; + * + * and migrates any legacy .ht.sqlite into that directory on the next boot. + * + * Resolution order: + * 1. the path recorded in db-path.php — PARSED, never executed (same literal match + * as instacp's v-instawp-import-site-playground); + * 2. wp-content/database/.ht./.ht.sqlite (newest mtime wins if there are several); + * 3. the legacy wp-content/database/.ht.sqlite (or .ht.sqlite.php). + * + * Every candidate must resolve, symlinks followed, to a non-empty regular file inside + * wp-content/database. Pure fs: no logging, no exit — callers print `warnings`. + */ +export interface LocalSqliteResolution { + /** Absolute path of the database file, or null when nothing usable was found. */ + path: string | null; + source: 'db-path.php' | 'secret-dir' | 'legacy' | null; + /** Every location that was looked at, in order (for the "not found" message). */ + checked: string[]; + /** Things the user should see before we act on `path`. */ + warnings: string[]; + /** + * db-path.php exists but was not what produced `path`. WP_SQLite_Storage treats + * db-path.php as the authority (it opens the recorded file, or migrates/creates one + * THERE), so any fallback result is not the database WordPress is using. + */ + recordedPathIgnored: boolean; +} + +const DB_FILENAME = '.ht.sqlite'; + +/** `__DIR__ . '/.ht./.ht.sqlite'` → `.ht./.ht.sqlite`. Null if the file does not have that shape. */ +export function parseDbPathPhp(contents: string): string | null { + const m = contents.match(/__DIR__\s*\.\s*(['"])\/([^'"\0]+)\1/); + return m ? m[2] : null; +} + +/** + * True if `target` is strictly below `dir` (not `dir` itself). Both must already be canonical + * (realpath'd). `p` is injectable so the Windows semantics can be tested on Linux. + */ +export function isInsideDir(dir: string, target: string, p: path.PlatformPath = path): boolean { + const rel = p.relative(dir, target); + if (rel === '') return false; + if (p.isAbsolute(rel)) return false; // different drive on Windows + return rel !== '..' && !rel.startsWith('..' + p.sep); +} + +/** Canonical path of a non-empty regular file inside `realDbDir`, else a reason it was refused. */ +function usable(candidate: string, realDbDir: string): { ok: string } | { refused: string } { + let real: string; + try { + real = realpathSync(candidate); + } catch { + return { refused: 'does not exist' }; + } + if (!isInsideDir(realDbDir, real)) return { refused: 'resolves outside wp-content/database' }; + try { + const st = statSync(real); + if (!st.isFile()) return { refused: 'is not a file' }; + if (st.size === 0) return { refused: 'is empty' }; + } catch { + return { refused: 'cannot be read' }; + } + return { ok: real }; +} + +export function resolveLocalSqlitePath(instance: { path: string }): LocalSqliteResolution { + const dbDir = path.join(instance.path, 'wp-content', 'database'); + const dbPathPhp = path.join(dbDir, 'db-path.php'); + const globLabel = path.join(dbDir, '.ht.*', DB_FILENAME); + const legacy = [path.join(dbDir, DB_FILENAME), path.join(dbDir, DB_FILENAME + '.php')]; + const checked: string[] = []; + const warnings: string[] = []; + let recordedPathIgnored = false; + const result = (p: string | null, source: LocalSqliteResolution['source']): LocalSqliteResolution => + ({ path: p, source, checked, warnings, recordedPathIgnored }); + + let realDbDir: string; + try { + realDbDir = realpathSync(dbDir); + } catch { + checked.push(dbPathPhp, globLabel, ...legacy); + return result(null, null); + } + + // 1. db-path.php + checked.push(dbPathPhp); + if (existsSync(dbPathPhp)) { + recordedPathIgnored = true; // cleared below if the recorded path is used + let rel: string | null = null; + try { + rel = parseDbPathPhp(readFileSync(dbPathPhp, 'utf-8')); + } catch { /* unreadable: treated as unparseable */ } + if (rel === null) { + warnings.push(`${dbPathPhp} exists but its database path could not be read; falling back.`); + } else { + const recorded = path.join(dbDir, ...rel.split('/')); + checked.push(recorded); + const u = usable(recorded, realDbDir); + if ('ok' in u) { + recordedPathIgnored = false; + return result(u.ok, 'db-path.php'); + } + warnings.push(`db-path.php points to ${recorded}, which ${u.refused}; falling back.`); + } + } + + // 2. .ht.*/.ht.sqlite + checked.push(globLabel); + const found: { path: string; mtime: number }[] = []; + let names: string[] = []; + try { + names = readdirSync(dbDir); + } catch { /* not a directory / unreadable: nothing to glob */ } + for (const name of names) { + // Non-directories (.ht.sqlite, .ht.sqlite.lock, …) fail realpath with ENOTDIR inside usable(). + if (!name.startsWith('.ht.')) continue; + const u = usable(path.join(dbDir, name, DB_FILENAME), realDbDir); + if ('ok' in u) found.push({ path: u.ok, mtime: statSync(u.ok).mtimeMs }); + } + if (found.length > 0) { + found.sort((a, b) => b.mtime - a.mtime); + if (found.length === 1) { + warnings.push(`No usable db-path.php; using ${found[0].path}. ` + + 'WordPress only opens the database db-path.php records, so check this is the site you expect.'); + } else { + warnings.push(`Found ${found.length} SQLite databases and no usable db-path.php; using the most recently modified:\n` + + found.map((f, i) => ` ${i === 0 ? '→' : ' '} ${f.path} (modified ${new Date(f.mtime).toISOString()})`).join('\n')); + } + return result(found[0].path, 'secret-dir'); + } + + // 3. legacy + for (const candidate of legacy) { + checked.push(candidate); + const u = usable(candidate, realDbDir); + if ('ok' in u) return result(u.ok, 'legacy'); + } + + return result(null, null); +} + +/** + * The database `local push --with-db` may overwrite the cloud with, or why it refuses. + * Stricter than resolveLocalSqlitePath(): when db-path.php exists but could not be + * used, every fallback is a file WordPress is NOT using, so pushing it would replace + * the cloud site with stale (or someone else's) data. Refuse rather than guess. + */ +export function resolvePushSqlitePath(instance: { path: string }): + { path: string; warnings: string[] } | { error: string; warnings: string[] } { + const r = resolveLocalSqlitePath(instance); + if (r.recordedPathIgnored) { + return { + warnings: r.warnings, + error: `${path.join(instance.path, 'wp-content', 'database', 'db-path.php')} exists but does not point to a usable ` + + 'database inside wp-content/database, so the database WordPress is using cannot be determined ' + + 'and nothing was pushed. Check that file and the .ht.* folders next to it, then retry.', + }; + } + if (!r.path) { + return { + warnings: r.warnings, + error: 'No local database found. Checked:\n' + r.checked.map((p) => ` - ${p}`).join('\n'), + }; + } + return { path: r.path, warnings: r.warnings }; +} diff --git a/src/lib/sqlite-to-mysql.ts b/src/lib/sqlite-to-mysql.ts index b799e2b..c23ffc9 100644 --- a/src/lib/sqlite-to-mysql.ts +++ b/src/lib/sqlite-to-mysql.ts @@ -51,7 +51,7 @@ export function quoteIdent(name: string): string { } export interface DumpParams { - /** Path to the Playground SQLite file (…/wp-content/database/.ht.sqlite). */ + /** Path to the Playground SQLite file (from resolveLocalSqlitePath()). */ sqlitePath: string; /** The cloud site's real table prefix (e.g. `wp_`). Local tables are `wp_*`. */ cloudPrefix: string;