forked from colbymchenry/codegraph
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconfig.ts
More file actions
299 lines (258 loc) · 8.56 KB
/
config.ts
File metadata and controls
299 lines (258 loc) · 8.56 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
/**
* Configuration Management
*
* Load, save, and validate CodeGraph configuration.
*/
import * as fs from 'fs';
import * as path from 'path';
import picomatch from 'picomatch';
import { CodeGraphConfig, DEFAULT_CONFIG, Language, NodeKind } from './types';
import { normalizePath } from './utils';
/**
* Configuration filename
*/
export const CONFIG_FILENAME = 'config.json';
/**
* Get the config file path for a project
*/
export function getConfigPath(projectRoot: string): string {
return path.join(projectRoot, '.codegraph', CONFIG_FILENAME);
}
/**
* Check if a regex pattern is safe from ReDoS attacks.
*
* Rejects patterns with nested quantifiers (e.g., (a+)+, (a*)*) which
* are the primary source of catastrophic backtracking. Also rejects
* excessively long patterns and validates compilability.
*/
function isSafeRegex(pattern: string): boolean {
// Reject excessively long patterns
if (pattern.length > 500) return false;
// Reject nested quantifiers: (...)+ followed by +, *, or {
// These are the primary cause of catastrophic backtracking
if (/([+*}])\s*[+*{]/.test(pattern)) return false;
if (/\([^)]*[+*][^)]*\)[+*{]/.test(pattern)) return false;
// Verify the pattern is a valid regex
try {
new RegExp(pattern);
return true;
} catch {
return false;
}
}
/**
* Validate a configuration object
*/
export function validateConfig(config: unknown): config is CodeGraphConfig {
if (typeof config !== 'object' || config === null) {
return false;
}
const c = config as Record<string, unknown>;
// Required fields
if (typeof c.version !== 'number') return false;
if (typeof c.rootDir !== 'string') return false;
if (!Array.isArray(c.include)) return false;
if (!Array.isArray(c.exclude)) return false;
if (!Array.isArray(c.languages)) return false;
if (!Array.isArray(c.frameworks)) return false;
if (typeof c.maxFileSize !== 'number') return false;
if (typeof c.extractDocstrings !== 'boolean') return false;
if (typeof c.trackCallSites !== 'boolean') return false;
if (typeof c.enableEmbeddings !== 'boolean') return false;
// Validate include/exclude are string arrays
if (!c.include.every((p) => typeof p === 'string')) return false;
if (!c.exclude.every((p) => typeof p === 'string')) return false;
// Validate languages
const validLanguages: Language[] = [
'typescript',
'javascript',
'python',
'go',
'rust',
'java',
'svelte',
'unknown',
];
if (!c.languages.every((l) => validLanguages.includes(l as Language))) return false;
// Validate frameworks
for (const fw of c.frameworks) {
if (typeof fw !== 'object' || fw === null) return false;
const framework = fw as Record<string, unknown>;
if (typeof framework.name !== 'string') return false;
}
// Validate custom patterns if present
if (c.customPatterns !== undefined) {
if (!Array.isArray(c.customPatterns)) return false;
for (const pattern of c.customPatterns) {
if (typeof pattern !== 'object' || pattern === null) return false;
const p = pattern as Record<string, unknown>;
if (typeof p.name !== 'string') return false;
if (typeof p.pattern !== 'string') return false;
if (typeof p.kind !== 'string') return false;
// Validate regex is compilable and reject patterns with known ReDoS risks
if (!isSafeRegex(p.pattern)) return false;
}
}
return true;
}
/**
* Merge configuration with defaults
*/
function mergeConfig(
defaults: CodeGraphConfig,
overrides: Partial<CodeGraphConfig>
): CodeGraphConfig {
return {
version: overrides.version ?? defaults.version,
rootDir: overrides.rootDir ?? defaults.rootDir,
include: overrides.include ?? defaults.include,
exclude: overrides.exclude ?? defaults.exclude,
languages: overrides.languages ?? defaults.languages,
frameworks: overrides.frameworks ?? defaults.frameworks,
maxFileSize: overrides.maxFileSize ?? defaults.maxFileSize,
extractDocstrings: overrides.extractDocstrings ?? defaults.extractDocstrings,
trackCallSites: overrides.trackCallSites ?? defaults.trackCallSites,
enableEmbeddings: overrides.enableEmbeddings ?? defaults.enableEmbeddings,
customPatterns: overrides.customPatterns ?? defaults.customPatterns,
};
}
/**
* Load configuration from a project
*/
export function loadConfig(projectRoot: string): CodeGraphConfig {
const configPath = getConfigPath(projectRoot);
if (!fs.existsSync(configPath)) {
// Return default config with adjusted rootDir
return {
...DEFAULT_CONFIG,
rootDir: projectRoot,
};
}
try {
const content = fs.readFileSync(configPath, 'utf-8');
const parsed = JSON.parse(content) as unknown;
// Merge with defaults to ensure all fields are present
const merged = mergeConfig(DEFAULT_CONFIG, parsed as Partial<CodeGraphConfig>);
merged.rootDir = projectRoot; // Always use actual project root
if (!validateConfig(merged)) {
throw new Error('Invalid configuration format');
}
return merged;
} catch (error) {
if (error instanceof SyntaxError) {
throw new Error(`Invalid JSON in config file: ${configPath}`);
}
throw error;
}
}
/**
* Save configuration to a project
*/
export function saveConfig(projectRoot: string, config: CodeGraphConfig): void {
const configPath = getConfigPath(projectRoot);
const dir = path.dirname(configPath);
// Ensure directory exists
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir, { recursive: true });
}
// Create a copy without rootDir (it's always derived from project path)
const toSave = { ...config };
delete (toSave as Partial<CodeGraphConfig>).rootDir;
const content = JSON.stringify(toSave, null, 2);
// Atomic write: write to temp file then rename to prevent partial/corrupt configs
const tmpPath = configPath + '.tmp';
fs.writeFileSync(tmpPath, content, 'utf-8');
fs.renameSync(tmpPath, configPath);
}
/**
* Create default configuration for a new project
*/
export function createDefaultConfig(projectRoot: string): CodeGraphConfig {
return {
...DEFAULT_CONFIG,
rootDir: projectRoot,
};
}
/**
* Update specific configuration values
*/
export function updateConfig(
projectRoot: string,
updates: Partial<CodeGraphConfig>
): CodeGraphConfig {
const current = loadConfig(projectRoot);
const updated = mergeConfig(current, updates);
updated.rootDir = projectRoot;
saveConfig(projectRoot, updated);
return updated;
}
/**
* Add patterns to include list
*/
export function addIncludePatterns(projectRoot: string, patterns: string[]): CodeGraphConfig {
const config = loadConfig(projectRoot);
const newPatterns = patterns.filter((p) => !config.include.includes(p));
config.include = [...config.include, ...newPatterns];
saveConfig(projectRoot, config);
return config;
}
/**
* Add patterns to exclude list
*/
export function addExcludePatterns(projectRoot: string, patterns: string[]): CodeGraphConfig {
const config = loadConfig(projectRoot);
const newPatterns = patterns.filter((p) => !config.exclude.includes(p));
config.exclude = [...config.exclude, ...newPatterns];
saveConfig(projectRoot, config);
return config;
}
/**
* Add a custom pattern
*/
export function addCustomPattern(
projectRoot: string,
name: string,
pattern: string,
kind: NodeKind
): CodeGraphConfig {
const config = loadConfig(projectRoot);
if (!config.customPatterns) {
config.customPatterns = [];
}
// Check for duplicate name
const existing = config.customPatterns.find((p) => p.name === name);
if (existing) {
existing.pattern = pattern;
existing.kind = kind;
} else {
config.customPatterns.push({ name, pattern, kind });
}
saveConfig(projectRoot, config);
return config;
}
/**
* Check if a file path matches the include/exclude patterns
*/
export function shouldIncludeFile(filePath: string, config: CodeGraphConfig): boolean {
// Normalize to forward slashes so Windows backslash paths match glob patterns
filePath = normalizePath(filePath);
// Simple glob matching (for now, just check if any pattern matches)
// A full implementation would use a proper glob library
const matchesPattern = (pattern: string, filePath: string): boolean => {
return picomatch.isMatch(filePath, pattern, { dot: true });
};
// Check exclude patterns first
for (const pattern of config.exclude) {
if (matchesPattern(pattern, filePath)) {
return false;
}
}
// Check include patterns
for (const pattern of config.include) {
if (matchesPattern(pattern, filePath)) {
return true;
}
}
// Default to not including if no pattern matches
return false;
}