* 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)
| 538 | * instance holds it until its first indexAll() finishes or it is closed. |
| 539 | */ |
| 540 | static async recreate(projectRoot: string): Promise<CodeGraph> { |
| 541 | await initGrammars(); |
| 542 | const resolvedRoot = path.resolve(projectRoot); |
| 543 | |
| 544 | // Check if initialized — recreate REBUILDS an existing project; it is not a |
| 545 | // first-time `init`. |
| 546 | if (!isInitialized(resolvedRoot)) { |
| 547 | throw new Error(`CodeGraph not initialized in ${resolvedRoot}. Run init() first.`); |
| 548 | } |
| 549 | |
| 550 | const dbPath = getDatabasePath(resolvedRoot); |
| 551 | const lock = new FileLock(path.join(path.dirname(dbPath), 'codegraph.lock')); |
| 552 | try { |
| 553 | lock.acquire(); |
| 554 | } catch { |
| 555 | throw new LockUnavailableError('Could not acquire file lock - another process may be indexing'); |
| 556 | } |
| 557 | |
| 558 | try { |
| 559 | try { |
| 560 | removeDatabaseFiles(dbPath); |
| 561 | } catch (err) { |
| 562 | // POSIX unlinks an open file fine; this fires mainly on Windows when a |
| 563 | // live daemon/MCP server still holds the database. Turn the raw EBUSY into |
| 564 | // an actionable instruction instead of a generic failure. |
| 565 | const reason = err instanceof Error ? err.message : String(err); |
| 566 | throw new Error( |
| 567 | `Could not rebuild the index — the database file is in use (${reason}). ` + |
| 568 | `Stop any running CodeGraph MCP server/daemon for this project and retry, ` + |
| 569 | `or remove the ${path.dirname(dbPath)} directory and run "codegraph init".` |
| 570 | ); |
| 571 | } |
| 572 | |
| 573 | // Re-create an empty, freshly-schema'd database at the same path. |
| 574 | const db = DatabaseConnection.initialize(dbPath); |
| 575 | const queries = new QueryBuilder(db.getDb()); |
| 576 | |
| 577 | return new CodeGraph(db, queries, resolvedRoot, lock); |
| 578 | } catch (err) { |
| 579 | lock.release(); |
| 580 | throw err; |
| 581 | } |
| 582 | } |
| 583 | |
| 584 | /** |
| 585 | * Open synchronously (without sync). |