1
0

foundation.test.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438
  1. /**
  2. * Foundation Tests
  3. *
  4. * Tests for the CodeGraph foundation layer.
  5. */
  6. import { describe, it, expect, beforeEach, afterEach } from 'vitest';
  7. import * as fs from 'fs';
  8. import * as path from 'path';
  9. import * as os from 'os';
  10. import { CodeGraph } from '../src';
  11. import { Node, Edge } from '../src/types';
  12. import { isInitialized, getCodeGraphDir, validateDirectory, codeGraphDirName, isCodeGraphDataDir } from '../src/directory';
  13. import { DatabaseConnection, getDatabasePath } from '../src/db';
  14. // Create a temporary directory for each test
  15. function createTempDir(): string {
  16. return fs.mkdtempSync(path.join(os.tmpdir(), 'codegraph-test-'));
  17. }
  18. // Clean up temporary directory
  19. function cleanupTempDir(dir: string): void {
  20. if (fs.existsSync(dir)) {
  21. fs.rmSync(dir, { recursive: true, force: true });
  22. }
  23. }
  24. describe('CodeGraph Foundation', () => {
  25. let tempDir: string;
  26. beforeEach(() => {
  27. tempDir = createTempDir();
  28. });
  29. afterEach(() => {
  30. cleanupTempDir(tempDir);
  31. });
  32. describe('Initialization', () => {
  33. it('should initialize a new project', () => {
  34. const cg = CodeGraph.initSync(tempDir);
  35. expect(CodeGraph.isInitialized(tempDir)).toBe(true);
  36. expect(fs.existsSync(getCodeGraphDir(tempDir))).toBe(true);
  37. expect(fs.existsSync(getDatabasePath(tempDir))).toBe(true);
  38. cg.close();
  39. });
  40. it('should create .gitignore in .CodeGraph directory', () => {
  41. const cg = CodeGraph.initSync(tempDir);
  42. const gitignorePath = path.join(getCodeGraphDir(tempDir), '.gitignore');
  43. expect(fs.existsSync(gitignorePath)).toBe(true);
  44. const content = fs.readFileSync(gitignorePath, 'utf-8');
  45. // Ignore everything in .codegraph/ except this file itself, so transient
  46. // files (db, daemon.pid, sockets, logs) never show up in git. (#492, #484)
  47. expect(content).toContain('*');
  48. expect(content).toContain('!.gitignore');
  49. cg.close();
  50. });
  51. it('should throw if already initialized', () => {
  52. const cg = CodeGraph.initSync(tempDir);
  53. cg.close();
  54. expect(() => CodeGraph.initSync(tempDir)).toThrow(/already initialized/i);
  55. });
  56. });
  57. describe('Opening Projects', () => {
  58. it('should open an existing project', () => {
  59. // First initialize
  60. const cg1 = CodeGraph.initSync(tempDir);
  61. cg1.close();
  62. // Then open
  63. const cg2 = CodeGraph.openSync(tempDir);
  64. expect(cg2.getProjectRoot()).toBe(path.resolve(tempDir));
  65. cg2.close();
  66. });
  67. it('should throw if not initialized', () => {
  68. expect(() => CodeGraph.openSync(tempDir)).toThrow(/not initialized/i);
  69. });
  70. });
  71. describe('Static Methods', () => {
  72. it('isInitialized should return false for new directory', () => {
  73. expect(CodeGraph.isInitialized(tempDir)).toBe(false);
  74. });
  75. it('isInitialized should return true after init', () => {
  76. const cg = CodeGraph.initSync(tempDir);
  77. expect(CodeGraph.isInitialized(tempDir)).toBe(true);
  78. cg.close();
  79. });
  80. });
  81. describe('Database', () => {
  82. it('should create database with correct schema', () => {
  83. const cg = CodeGraph.initSync(tempDir);
  84. // Check that we can get stats (requires tables to exist)
  85. const stats = cg.getStats();
  86. expect(stats.nodeCount).toBe(0);
  87. expect(stats.edgeCount).toBe(0);
  88. expect(stats.fileCount).toBe(0);
  89. cg.close();
  90. });
  91. it('should return correct database size', () => {
  92. const cg = CodeGraph.initSync(tempDir);
  93. const stats = cg.getStats();
  94. // Database should have some size (at least the schema)
  95. expect(stats.dbSizeBytes).toBeGreaterThan(0);
  96. cg.close();
  97. });
  98. it('should support optimize operation', () => {
  99. const cg = CodeGraph.initSync(tempDir);
  100. // Should not throw
  101. expect(() => cg.optimize()).not.toThrow();
  102. cg.close();
  103. });
  104. it('should support clear operation', () => {
  105. const cg = CodeGraph.initSync(tempDir);
  106. // Should not throw
  107. expect(() => cg.clear()).not.toThrow();
  108. const stats = cg.getStats();
  109. expect(stats.nodeCount).toBe(0);
  110. cg.close();
  111. });
  112. });
  113. describe('Directory Management', () => {
  114. it('should validate directory structure', () => {
  115. const cg = CodeGraph.initSync(tempDir);
  116. cg.close();
  117. const validation = validateDirectory(tempDir);
  118. expect(validation.valid).toBe(true);
  119. expect(validation.errors).toHaveLength(0);
  120. });
  121. it('should detect invalid directory', () => {
  122. const validation = validateDirectory(tempDir);
  123. expect(validation.valid).toBe(false);
  124. expect(validation.errors.length).toBeGreaterThan(0);
  125. });
  126. it('upgrades a stale pre-wildcard .gitignore in place (issue #788)', () => {
  127. const cg = CodeGraph.initSync(tempDir);
  128. cg.close();
  129. const gitignorePath = path.join(getCodeGraphDir(tempDir), '.gitignore');
  130. // A .gitignore written by an older version (<= 0.9.9): an explicit
  131. // allowlist that never ignored daemon.pid, so the daemon's runtime
  132. // pidfile got committed.
  133. const staleV099 =
  134. '# CodeGraph data files\n' +
  135. '# These are local to each machine and should not be committed\n\n' +
  136. '# Database\n*.db\n*.db-wal\n*.db-shm\n\n' +
  137. '# Cache\ncache/\n\n# Logs\n*.log\n\n# Hook markers\n.dirty\n';
  138. fs.writeFileSync(gitignorePath, staleV099, 'utf-8');
  139. // Opening the project runs validateDirectory, which self-heals.
  140. const cg2 = CodeGraph.openSync(tempDir);
  141. cg2.close();
  142. const upgraded = fs.readFileSync(gitignorePath, 'utf-8');
  143. expect(upgraded).toContain('\n*\n'); // wildcard ignores everything…
  144. expect(upgraded).toContain('!.gitignore'); // …except this file
  145. expect(upgraded).not.toContain('.dirty'); // old explicit list is gone
  146. });
  147. it('leaves a user-customized .codegraph/.gitignore untouched', () => {
  148. const cg = CodeGraph.initSync(tempDir);
  149. cg.close();
  150. const gitignorePath = path.join(getCodeGraphDir(tempDir), '.gitignore');
  151. // No CodeGraph header → user-authored → must not be rewritten.
  152. const custom = '# my own rules\n*.db\n!keep-this.json\n';
  153. fs.writeFileSync(gitignorePath, custom, 'utf-8');
  154. const cg2 = CodeGraph.openSync(tempDir);
  155. cg2.close();
  156. expect(fs.readFileSync(gitignorePath, 'utf-8')).toBe(custom);
  157. });
  158. });
  159. describe('Uninitialize', () => {
  160. it('should remove .CodeGraph directory', () => {
  161. const cg = CodeGraph.initSync(tempDir);
  162. cg.uninitialize();
  163. expect(fs.existsSync(getCodeGraphDir(tempDir))).toBe(false);
  164. expect(CodeGraph.isInitialized(tempDir)).toBe(false);
  165. });
  166. });
  167. describe('Close/Destroy', () => {
  168. it('should close database but keep .CodeGraph directory', () => {
  169. const cg = CodeGraph.initSync(tempDir);
  170. cg.destroy(); // destroy is alias for close
  171. expect(fs.existsSync(getCodeGraphDir(tempDir))).toBe(true);
  172. expect(CodeGraph.isInitialized(tempDir)).toBe(true);
  173. });
  174. });
  175. describe('Graph Query Methods', () => {
  176. it('should throw "Node not found" for non-existent nodes', () => {
  177. const cg = CodeGraph.initSync(tempDir);
  178. // getContext throws for non-existent nodes
  179. expect(() => cg.getContext('non-existent')).toThrow(/not found/i);
  180. cg.close();
  181. });
  182. it('should return empty results for non-existent nodes', () => {
  183. const cg = CodeGraph.initSync(tempDir);
  184. // These methods return empty results instead of throwing
  185. const traverseResult = cg.traverse('non-existent');
  186. expect(traverseResult.nodes.size).toBe(0);
  187. const callGraph = cg.getCallGraph('non-existent');
  188. expect(callGraph.nodes.size).toBe(0);
  189. const typeHierarchy = cg.getTypeHierarchy('non-existent');
  190. expect(typeHierarchy.nodes.size).toBe(0);
  191. const usages = cg.findUsages('non-existent');
  192. expect(usages.length).toBe(0);
  193. cg.close();
  194. });
  195. });
  196. });
  197. describe('Database Connection', () => {
  198. let tempDir: string;
  199. beforeEach(() => {
  200. tempDir = createTempDir();
  201. });
  202. afterEach(() => {
  203. cleanupTempDir(tempDir);
  204. });
  205. it('should initialize new database', () => {
  206. const dbPath = path.join(tempDir, 'test.db');
  207. const db = DatabaseConnection.initialize(dbPath);
  208. expect(db.isOpen()).toBe(true);
  209. expect(fs.existsSync(dbPath)).toBe(true);
  210. db.close();
  211. });
  212. it('should get schema version', () => {
  213. const dbPath = path.join(tempDir, 'test.db');
  214. const db = DatabaseConnection.initialize(dbPath);
  215. const version = db.getSchemaVersion();
  216. expect(version).not.toBeNull();
  217. expect(version?.version).toBe(5);
  218. db.close();
  219. });
  220. it('should support transactions', () => {
  221. const dbPath = path.join(tempDir, 'test.db');
  222. const db = DatabaseConnection.initialize(dbPath);
  223. const result = db.transaction(() => {
  224. return 42;
  225. });
  226. expect(result).toBe(42);
  227. db.close();
  228. });
  229. it('should throw when opening non-existent database', () => {
  230. const dbPath = path.join(tempDir, 'nonexistent.db');
  231. expect(() => DatabaseConnection.open(dbPath)).toThrow(/not found/i);
  232. });
  233. });
  234. describe('Query Builder', () => {
  235. let tempDir: string;
  236. let cg: CodeGraph;
  237. beforeEach(() => {
  238. tempDir = createTempDir();
  239. cg = CodeGraph.initSync(tempDir);
  240. });
  241. afterEach(() => {
  242. cg.close();
  243. cleanupTempDir(tempDir);
  244. });
  245. it('should return null for non-existent node', () => {
  246. const node = cg.getNode('nonexistent');
  247. expect(node).toBeNull();
  248. });
  249. it('should return empty array for nodes in non-existent file', () => {
  250. const nodes = cg.getNodesInFile('nonexistent.ts');
  251. expect(nodes).toEqual([]);
  252. });
  253. it('should return empty array for edges from non-existent node', () => {
  254. const edges = cg.getOutgoingEdges('nonexistent');
  255. expect(edges).toEqual([]);
  256. });
  257. it('should return null for non-existent file', () => {
  258. const file = cg.getFile('nonexistent.ts');
  259. expect(file).toBeNull();
  260. });
  261. it('should return empty array for files when none tracked', () => {
  262. const files = cg.getFiles();
  263. expect(files).toEqual([]);
  264. });
  265. });
  266. // Two environments that share one working tree (Windows-native + WSL) must not
  267. // share one `.codegraph/`. CODEGRAPH_DIR overrides the data directory name so
  268. // each side keeps its own index in the same tree (issue #636).
  269. describe('CODEGRAPH_DIR override (#636)', () => {
  270. const saved = process.env.CODEGRAPH_DIR;
  271. let tempDir: string;
  272. beforeEach(() => {
  273. tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'codegraph-dirname-'));
  274. });
  275. afterEach(() => {
  276. if (saved === undefined) delete process.env.CODEGRAPH_DIR;
  277. else process.env.CODEGRAPH_DIR = saved;
  278. fs.rmSync(tempDir, { recursive: true, force: true });
  279. });
  280. describe('codeGraphDirName()', () => {
  281. it('defaults to .codegraph when unset', () => {
  282. delete process.env.CODEGRAPH_DIR;
  283. expect(codeGraphDirName()).toBe('.codegraph');
  284. });
  285. it('honors a valid override', () => {
  286. process.env.CODEGRAPH_DIR = '.codegraph-win';
  287. expect(codeGraphDirName()).toBe('.codegraph-win');
  288. });
  289. // Anything that isn't a plain segment could escape the project root or
  290. // clobber it, so it's ignored in favor of the default.
  291. it.each(['foo/bar', 'a\\b', '..', '../x', '.', '/abs/path', ' ', ''])(
  292. 'falls back to .codegraph for invalid value %j',
  293. (bad) => {
  294. process.env.CODEGRAPH_DIR = bad;
  295. expect(codeGraphDirName()).toBe('.codegraph');
  296. }
  297. );
  298. });
  299. describe('isCodeGraphDataDir()', () => {
  300. it('matches the default, the active override, and .codegraph-* siblings', () => {
  301. process.env.CODEGRAPH_DIR = '.codegraph-win';
  302. expect(isCodeGraphDataDir('.codegraph')).toBe(true); // the other env's dir
  303. expect(isCodeGraphDataDir('.codegraph-win')).toBe(true); // active override
  304. expect(isCodeGraphDataDir('.codegraph-wsl')).toBe(true); // any sibling
  305. });
  306. it('does not match unrelated directories', () => {
  307. delete process.env.CODEGRAPH_DIR;
  308. for (const name of ['src', 'node_modules', '.git', 'codegraph', '.codegraphextra']) {
  309. expect(isCodeGraphDataDir(name)).toBe(false);
  310. }
  311. });
  312. });
  313. it('init writes the index under the overridden directory, not .codegraph', () => {
  314. process.env.CODEGRAPH_DIR = '.codegraph-win';
  315. const cg = CodeGraph.initSync(tempDir);
  316. try {
  317. expect(fs.existsSync(path.join(tempDir, '.codegraph-win', 'codegraph.db'))).toBe(true);
  318. expect(fs.existsSync(path.join(tempDir, '.codegraph'))).toBe(false);
  319. expect(getCodeGraphDir(tempDir)).toBe(path.join(tempDir, '.codegraph-win'));
  320. expect(CodeGraph.isInitialized(tempDir)).toBe(true);
  321. } finally {
  322. cg.close();
  323. }
  324. });
  325. it('two index dirs coexist in one tree and the override side skips the sibling', async () => {
  326. // WSL side: default `.codegraph`, with a source file.
  327. delete process.env.CODEGRAPH_DIR;
  328. fs.writeFileSync(path.join(tempDir, 'app.ts'), 'export function onlyReal() {}\n');
  329. const wsl = await CodeGraph.init(tempDir, { index: true });
  330. wsl.close();
  331. // Windows side: override dir, same tree. Plant a decoy source file INSIDE
  332. // the WSL data dir — the override-side index must not pick it up.
  333. process.env.CODEGRAPH_DIR = '.codegraph-win';
  334. fs.writeFileSync(path.join(tempDir, '.codegraph', 'decoy.ts'), 'export function decoyLeak() {}\n');
  335. const win = await CodeGraph.init(tempDir, { index: true });
  336. try {
  337. expect(fs.existsSync(path.join(tempDir, '.codegraph', 'codegraph.db'))).toBe(true);
  338. expect(fs.existsSync(path.join(tempDir, '.codegraph-win', 'codegraph.db'))).toBe(true);
  339. expect(win.searchNodes('onlyReal').length).toBeGreaterThan(0);
  340. expect(win.searchNodes('decoyLeak')).toEqual([]); // sibling data dir not indexed
  341. } finally {
  342. win.close();
  343. }
  344. });
  345. });