-
Notifications
You must be signed in to change notification settings - Fork 4.5k
Expand file tree
/
Copy pathdirectory.ts
More file actions
344 lines (285 loc) · 9.39 KB
/
Copy pathdirectory.ts
File metadata and controls
344 lines (285 loc) · 9.39 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
/**
* Directory Management
*
* Manages the .codegraph/ directory structure for CodeGraph data.
*/
import * as fs from 'fs';
import * as path from 'path';
import { execFileSync } from 'child_process';
/**
* CodeGraph directory name
*/
export const CODEGRAPH_DIR = '.codegraph';
/**
* Get the .codegraph directory path for a project
*/
export function getCodeGraphDir(projectRoot: string): string {
return path.join(projectRoot, CODEGRAPH_DIR);
}
/**
* Check if a project has been initialized with CodeGraph
* Requires both .codegraph/ directory AND codegraph.db to exist
*/
export function isInitialized(projectRoot: string): boolean {
const codegraphDir = getCodeGraphDir(projectRoot);
if (!fs.existsSync(codegraphDir) || !fs.statSync(codegraphDir).isDirectory()) {
return false;
}
// Must have codegraph.db, not just .codegraph folder
const dbPath = path.join(codegraphDir, 'codegraph.db');
return fs.existsSync(dbPath);
}
/**
* Find the nearest parent directory containing .codegraph/
*
* Walks up from the given path to find a CodeGraph-initialized project,
* similar to how git finds .git/ directories.
*
* @param startPath - Directory to start searching from
* @returns The project root containing .codegraph/, or null if not found
*/
export function findNearestCodeGraphRoot(startPath: string): string | null {
let current = path.resolve(startPath);
const root = path.parse(current).root;
while (current !== root) {
if (isInitialized(current)) {
return current;
}
const parent = path.dirname(current);
if (parent === current) break; // Reached filesystem root
current = parent;
}
// Check root as well
if (isInitialized(current)) {
return current;
}
return null;
}
/**
* Create the .codegraph directory structure
* Note: Only throws if codegraph.db already exists, not just if .codegraph/ exists.
*/
export function createDirectory(projectRoot: string): void {
const codegraphDir = getCodeGraphDir(projectRoot);
const dbPath = path.join(codegraphDir, 'codegraph.db');
// Only throw if CodeGraph is actually initialized (db exists)
// .codegraph/ folder alone is fine
if (fs.existsSync(dbPath)) {
throw new Error(`CodeGraph already initialized in ${projectRoot}`);
}
// Create main directory (if it doesn't exist)
fs.mkdirSync(codegraphDir, { recursive: true });
// Create .gitignore inside .codegraph (if it doesn't exist)
const gitignorePath = path.join(codegraphDir, '.gitignore');
if (!fs.existsSync(gitignorePath)) {
const gitignoreContent = `# CodeGraph data files
# These are local to each machine and should not be committed
# Database
*.db
*.db-wal
*.db-shm
# Cache
cache/
# Logs
*.log
# Hook markers
.dirty
`;
fs.writeFileSync(gitignorePath, gitignoreContent, 'utf-8');
}
ignoreCodeGraphDirectory(projectRoot);
}
/**
* Add .codegraph/ to this repository's local excludes.
*
* We use .git/info/exclude instead of the project's .gitignore because the
* CodeGraph index is local machine state. This keeps it out of commits without
* changing a tracked file just because someone ran `codegraph init`.
*/
export function ignoreCodeGraphDirectory(projectRoot: string): void {
const exclude = gitExclude(projectRoot);
if (!exclude) return;
let content = '';
try {
content = fs.existsSync(exclude.path) ? fs.readFileSync(exclude.path, 'utf-8') : '';
} catch {
return;
}
if (hasIgnoreEntry(content, exclude.entry)) return;
const nextContent = appendIgnoreEntry(content, exclude.entry);
try {
fs.mkdirSync(path.dirname(exclude.path), { recursive: true });
fs.writeFileSync(exclude.path, nextContent, 'utf-8');
} catch {
// Local exclude is a convenience. Initialization should still succeed if
// git metadata is read-only or otherwise inaccessible.
}
}
function gitExclude(projectRoot: string): { path: string; entry: string } | null {
try {
const inside = execFileSync('git', ['rev-parse', '--is-inside-work-tree'], {
cwd: projectRoot,
encoding: 'utf8',
stdio: ['ignore', 'pipe', 'ignore'],
windowsHide: true,
}).trim();
if (inside !== 'true') return null;
const worktreeRoot = execFileSync('git', ['rev-parse', '--show-toplevel'], {
cwd: projectRoot,
encoding: 'utf8',
stdio: ['ignore', 'pipe', 'ignore'],
windowsHide: true,
}).trim();
if (!worktreeRoot) return null;
const gitPath = execFileSync('git', ['rev-parse', '--git-path', 'info/exclude'], {
cwd: projectRoot,
encoding: 'utf8',
stdio: ['ignore', 'pipe', 'ignore'],
windowsHide: true,
}).trim();
if (!gitPath) return null;
const excludePath = path.isAbsolute(gitPath) ? gitPath : path.resolve(projectRoot, gitPath);
const relativeProject = path.relative(worktreeRoot, projectRoot).split(path.sep).join('/');
const entry = relativeProject
? `${relativeProject}/${CODEGRAPH_DIR}/`
: `${CODEGRAPH_DIR}/`;
return { path: excludePath, entry };
} catch {
return null;
}
}
function hasIgnoreEntry(content: string, entry: string): boolean {
return content
.split(/\r?\n/)
.map((line) => line.trim())
.some((line) => line === entry || line === entry.replace(/\/$/, ''));
}
function appendIgnoreEntry(content: string, entry: string): string {
const trimmed = content.replace(/\s*$/, '');
const block = `# CodeGraph local index\n${entry}\n`;
return trimmed.length > 0 ? `${trimmed}\n\n${block}` : block;
}
/**
* Remove the .codegraph directory
*/
export function removeDirectory(projectRoot: string): void {
const codegraphDir = getCodeGraphDir(projectRoot);
if (!fs.existsSync(codegraphDir)) {
return;
}
// Verify .codegraph is a real directory, not a symlink pointing elsewhere
const lstat = fs.lstatSync(codegraphDir);
if (lstat.isSymbolicLink()) {
// Only remove the symlink itself, never follow it for recursive delete
fs.unlinkSync(codegraphDir);
return;
}
if (!lstat.isDirectory()) {
// Not a directory - remove the single file
fs.unlinkSync(codegraphDir);
return;
}
// Recursively remove directory
fs.rmSync(codegraphDir, { recursive: true, force: true });
}
/**
* Get all files in the .codegraph directory
*/
export function listDirectoryContents(projectRoot: string): string[] {
const codegraphDir = getCodeGraphDir(projectRoot);
if (!fs.existsSync(codegraphDir)) {
return [];
}
const files: string[] = [];
function walkDir(dir: string, prefix: string = ''): void {
const entries = fs.readdirSync(dir, { withFileTypes: true });
for (const entry of entries) {
const relativePath = prefix ? `${prefix}/${entry.name}` : entry.name;
// Skip symlinks to prevent following links outside .codegraph
if (entry.isSymbolicLink()) {
continue;
}
if (entry.isDirectory()) {
walkDir(path.join(dir, entry.name), relativePath);
} else {
files.push(relativePath);
}
}
}
walkDir(codegraphDir);
return files;
}
/**
* Get the total size of the .codegraph directory in bytes
*/
export function getDirectorySize(projectRoot: string): number {
const codegraphDir = getCodeGraphDir(projectRoot);
if (!fs.existsSync(codegraphDir)) {
return 0;
}
let totalSize = 0;
function walkDir(dir: string): void {
const entries = fs.readdirSync(dir, { withFileTypes: true });
for (const entry of entries) {
// Skip symlinks to prevent following links outside .codegraph
if (entry.isSymbolicLink()) {
continue;
}
const fullPath = path.join(dir, entry.name);
if (entry.isDirectory()) {
walkDir(fullPath);
} else {
const stats = fs.statSync(fullPath);
totalSize += stats.size;
}
}
}
walkDir(codegraphDir);
return totalSize;
}
/**
* Ensure a subdirectory exists within .codegraph
*/
export function ensureSubdirectory(projectRoot: string, subdirName: string): string {
if (subdirName.includes('..') || subdirName.includes(path.sep) || subdirName.includes('/')) {
throw new Error(`Invalid subdirectory name: ${subdirName}`);
}
const subdirPath = path.join(getCodeGraphDir(projectRoot), subdirName);
if (!fs.existsSync(subdirPath)) {
fs.mkdirSync(subdirPath, { recursive: true });
}
return subdirPath;
}
/**
* Check if the .codegraph directory has valid structure
*/
export function validateDirectory(projectRoot: string): {
valid: boolean;
errors: string[];
} {
const errors: string[] = [];
const codegraphDir = getCodeGraphDir(projectRoot);
if (!fs.existsSync(codegraphDir)) {
errors.push('CodeGraph directory does not exist');
return { valid: false, errors };
}
if (!fs.statSync(codegraphDir).isDirectory()) {
errors.push('.codegraph exists but is not a directory');
return { valid: false, errors };
}
// Auto-repair missing .gitignore (non-critical file)
const gitignorePath = path.join(codegraphDir, '.gitignore');
if (!fs.existsSync(gitignorePath)) {
try {
const gitignoreContent = `# CodeGraph data files\n# These are local to each machine and should not be committed\n\n# Database\n*.db\n*.db-wal\n*.db-shm\n\n# Cache\ncache/\n\n# Logs\n*.log\n\n# Hook markers\n.dirty\n`;
fs.writeFileSync(gitignorePath, gitignoreContent, 'utf-8');
} catch {
// Non-fatal: warn but don't block
errors.push('.gitignore missing in .codegraph directory and could not be created');
}
}
return {
valid: errors.length === 0,
errors,
};
}