* Rebuild the project's database from scratch and return a fresh, empty * instance — the "same result as a fresh init" semantics that `codegraph * index` documents. * * Unlike `open()` followed by `clear()`, this DISCARDS the existing * `.codegraph/codegraph.db` (and its `-wal`/`-shm`
(projectRoot: string)
| 344 | * (and running migrations against) the poisoned database entirely. |
| 345 | */ |
| 346 | static async recreate(projectRoot: string): Promise<CodeGraph> { |
| 347 | await initGrammars(); |
| 348 | const resolvedRoot = path.resolve(projectRoot); |
| 349 | |
| 350 | // Check if initialized — recreate REBUILDS an existing project; it is not a |
| 351 | // first-time `init`. |
| 352 | if (!isInitialized(resolvedRoot)) { |
| 353 | throw new Error(`CodeGraph not initialized in ${resolvedRoot}. Run init() first.`); |
| 354 | } |
| 355 | |
| 356 | const dbPath = getDatabasePath(resolvedRoot); |
| 357 | try { |
| 358 | removeDatabaseFiles(dbPath); |
| 359 | } catch (err) { |
| 360 | // POSIX unlinks an open file fine; this fires mainly on Windows when a |
| 361 | // live daemon/MCP server still holds the database. Turn the raw EBUSY into |
| 362 | // an actionable instruction instead of a generic failure. |
| 363 | const reason = err instanceof Error ? err.message : String(err); |
| 364 | throw new Error( |
| 365 | `Could not rebuild the index — the database file is in use (${reason}). ` + |
| 366 | `Stop any running CodeGraph MCP server/daemon for this project and retry, ` + |
| 367 | `or remove the ${getCodeGraphDir(resolvedRoot)} directory and run "codegraph init".` |
| 368 | ); |
| 369 | } |
| 370 | |
| 371 | // Re-create an empty, freshly-schema'd database at the same path. |
| 372 | const db = DatabaseConnection.initialize(dbPath); |
| 373 | const queries = new QueryBuilder(db.getDb()); |
| 374 | |
| 375 | return new CodeGraph(db, queries, resolvedRoot); |
| 376 | } |
| 377 | |
| 378 | /** |
| 379 | * Open synchronously (without sync) |
no test coverage detected