-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathindex.ts
More file actions
1635 lines (1442 loc) · 62.9 KB
/
index.ts
File metadata and controls
1635 lines (1442 loc) · 62.9 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
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env node
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import {
CallToolRequestSchema,
ListToolsRequestSchema,
McpError,
ErrorCode,
} from "@modelcontextprotocol/sdk/types.js";
import fg from "fast-glob";
// Standardized on async filesystem operations for better performance
import fs from "fs/promises";
import path from "path";
import { findUp } from "find-up";
import ignore from "ignore";
import { minimatch } from "minimatch";
import { create } from "xmlbuilder2";
import Parser from "tree-sitter";
import JavaScript from "tree-sitter-javascript";
import TypeScript from "tree-sitter-typescript";
import CSharp from "tree-sitter-c-sharp";
import Php from "tree-sitter-php";
import Css from "tree-sitter-css";
import Python from "tree-sitter-python"; // Added for Python support
import yargs from "yargs"; // Added
import { hideBin } from "yargs/helpers"; // Added
// --- Tree-sitter Setup ---
const parser = new Parser();
// Helper function to standardize the Tree-sitter language type casting
function castToParserLanguage(lang: any): Parser.Language {
return lang as unknown as Parser.Language;
}
const languageMap: { [ext: string]: Parser.Language } = {
".js": castToParserLanguage(JavaScript),
".jsx": castToParserLanguage(JavaScript),
".ts": castToParserLanguage(TypeScript.typescript),
".tsx": castToParserLanguage(TypeScript.tsx),
".cs": castToParserLanguage(CSharp),
".php": castToParserLanguage(Php),
".css": castToParserLanguage(Css),
".py": castToParserLanguage(Python), // Added for Python support
};
// Basic queries - these can be expanded significantly
// Queries focused on namespace, class, method, function
const queries: { [langExt: string]: { [defType: string]: string } } = {
".js": {
function: `
(function_declaration
name: (identifier) @name
parameters: (formal_parameters
(formal_parameter
name: (identifier) @param_name
)*
) @params
) @function`,
method: `
(method_definition
name: (property_identifier) @name
parameters: (formal_parameters
(formal_parameter
name: (identifier) @param_name
)*
) @params
) @method`,
class: `(class_declaration name: (identifier) @name) @class`,
variable: `
[
(lexical_declaration (variable_declarator name: (identifier) @name value: (_)? @value))
(variable_declaration (variable_declarator name: (identifier) @name value: (_)? @value))
] @variable`,
property: `(public_field_definition name: (property_identifier) @name value: (_)? @value) @property`,
// JS doesn't have native enums in the same way TS/C#/PHP do
enum: ``,
enumMember: ``,
call: `(call_expression function: [ (identifier) @call_name (member_expression property: (property_identifier) @call_name) ] ) @call`,
},
".ts": {
function: `(function_declaration name: (_) @name) @function`,
method: `(method_definition name: (_) @name) @method`,
class: `(class_declaration name: (_) @name) @class`,
interface: `(interface_declaration name: (_) @name) @interface`,
variable: `
[
(lexical_declaration (variable_declarator name: (identifier) @name type: (_)? @dataType value: (_)? @value))
(variable_declaration (variable_declarator name: (identifier) @name type: (_)? @dataType value: (_)? @value))
] @variable`,
property: `
[
(property_signature name: (property_identifier) @name type: (_) @dataType) ;; Interface/Type Property
(public_field_definition name: (property_identifier) @name type: (_)? @dataType value: (_)? @value) ;; Class Field
] @property`,
enum: `(enum_declaration name: (identifier) @name) @enum`,
enumMember: `(enum_assignment name: (property_identifier) @name value: (_)? @value) @enumMember`,
// Refined call query for TypeScript to capture more cases
call: `
(call_expression
function: [
(identifier) @call_name ;; Direct function call: myFunc()
(member_expression property: (property_identifier) @call_name) ;; Member call: obj.method(), console.log()
(super) @call_name ;; super() call
(non_null_expression expression: (member_expression property: (property_identifier) @call_name)) ;; Optional chaining call: obj?.method()
]
) @call`,
},
".cs": {
class: `(class_declaration (modifier)* @modifier name: (identifier) @name) @class`,
method: `(method_declaration (modifier)* @modifier name: (identifier) @name) @method`,
namespace: `(namespace_declaration name: (_) @name) @namespace`,
variable: `
(local_declaration_statement
(variable_declaration
type: (_) @dataType
(variable_declarator identifier: (identifier) @name (= (equals_value_clause value: (_) @value))?)
)
) @variable`,
property: `(field_declaration (modifier)* @modifier (variable_declaration type: (_) @dataType (variable_declarator (identifier) @name))) @property`, // Reverted to working version (no value)
enum: `(enum_declaration (modifier)* @modifier name: (identifier) @name) @enum`,
enumMember: `(enum_member_declaration name: (identifier) @name (= (equals_value_clause value: (_) @value))?) @enumMember`,
call: `(invocation_expression expression: [ (identifier_name) @call_name (member_access_expression name: (identifier_name) @call_name) ] ) @call`,
},
".php": {
function: `
(function_definition
(visibility_modifier)? @modifier
return_type: (_)? @return_type
name: (name) @name
parameters: (formal_parameters
(parameter_declaration
type: (_)? @param_type
name: (variable_name) @param_name
)*
)? @params
) @function`,
class: `(class_declaration (modifier)* @modifier name: (name) @name) @class`,
method: `
(method_declaration
(member_modifier)* @modifier
function_definition
return_type: (_)? @return_type
name: (name) @name
parameters: (formal_parameters
(parameter_declaration
type: (_)? @param_type
name: (variable_name) @param_name
)*
)? @params
) @method`,
namespace: `(namespace_definition name: (namespace_name) @name) @namespace`,
// PHP local variables are complex to capture reliably with Tree-sitter without excessive noise
variable: ``,
property: `
(property_declaration
(member_modifier)* @modifier
type: (_)? @dataType
(property_element name: (variable_name) @name value: (_)? @value)
) @property`,
enum: `(enum_declaration name: (name) @name) @enum`, // PHP 8.1+
enumMember: `(enum_case name: (name) @name value: (_)? @value) @enumMember`, // PHP 8.1+
call: `(function_call_expression function: [ (name) @call_name (qualified_name) @call_name ] ) @call`,
// Also consider method calls: (member_call_expression name: (name) @call_name)
},
// CSS queries removed as they don't fit namespace/class/method/function
".css": {},
".py": { // Added for Python support
function: `
(function_definition
name: (identifier) @name
parameters: (parameters . (_)* @params)? ;; Captures params block
) @function`,
// Note: This query captures all functions. Differentiating methods (functions inside classes)
// would typically require checking the parent node during parsing logic.
method: `
(function_definition
name: (identifier) @name
parameters: (parameters . (_)* @params)?
) @method`,
class: `(class_definition name: (identifier) @name) @class`,
decorator: `(decorator [ (identifier) @name (dotted_name) @name ]) @decorator`,
// Captures module-level assignments and simple class-level assignments
variable: `
[
(module (expression_statement (assignment left: (identifier) @name right: (_) @value)))
(class_definition body: (block (expression_statement (assignment left: (identifier) @name right: (_) @value))))
] @variable`,
// Query for individual parameters if needed later:
// parameter: `(parameters (typed_parameter name: (identifier) @name type: (_)? @type)) @parameter`
call: `(call function: [ (identifier) @call_name (attribute name: (identifier) @call_name) ] ) @call`,
},
};
// Default file patterns
const defaultFilePatterns = [
"**/*.js", "**/*.jsx", "**/*.ts", "**/*.tsx",
"**/*.cs", "**/*.php", "**/*.css",
"**/*.py" // Added for Python support
];
// --- Helper Functions ---
// Helper function to escape special characters in regex patterns
function escapeRegExp(string: string): string {
return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
}
async function findGitignore(startDir: string): Promise<string | undefined> {
return findUp(".gitignore", { cwd: startDir });
}
async function getIgnoreFilter(
gitignorePath: string | undefined
): Promise<(filePath: string) => boolean> {
const ig = ignore();
if (gitignorePath) {
try {
const gitignoreContent = await fs.readFile(gitignorePath, "utf-8");
ig.add(gitignoreContent);
} catch (err) {
console.warn(`Warning: Could not read .gitignore at ${gitignorePath}`);
}
}
// Always ignore node_modules and .git directories
ig.add("node_modules/"); // Add trailing slash for directory
ig.add(".git/"); // Add trailing slash for directory
return (filePath: string) => !ig.ignores(filePath);
}
// Removed findFilesRecursively function
interface Parameter {
name: string;
type?: string;
}
interface Definition {
id?: string; // Unique identifier
type: string;
name: string;
startLine: number;
endLine: number;
modifier?: string;
dataType?: string;
value?: string;
parentId?: string; // Reference to parent element
children?: string[]; // Array of child element IDs
parameters?: Parameter[]; // Method/function parameters
returnType?: string; // Return type for methods/functions
complexity?: number; // Cyclomatic complexity (optional)
parameterCount?: number; // Number of parameters (optional)
loc?: number; // Lines of Code (optional)
calls?: string[]; // Array of names called by this definition (optional)
}
interface FilterOptions {
includeTypes?: string[]; // Element types to include (e.g., 'class', 'method')
excludeTypes?: string[]; // Element types to exclude
includeModifiers?: string[]; // Modifiers to include (e.g., 'public', 'private')
excludeModifiers?: string[]; // Modifiers to exclude
namePattern?: string; // Regex pattern to match element names
excludeNamePattern?: string; // Regex pattern to exclude element names
includePaths?: string[]; // Additional file path patterns to include
excludePaths?: string[]; // File path patterns to exclude
// Metric filters
maxComplexity?: number;
minComplexity?: number;
maxParameters?: number;
minParameters?: number;
}
// Helper function for basic Cyclomatic Complexity calculation
function calculateComplexity(node: Parser.SyntaxNode | null): number {
if (!node) return 1; // Base complexity
let complexity = 1; // Start with 1 for the single entry point
// List of node types that represent decision points (can be expanded)
const decisionPointTypes = new Set([
// Common
'if_statement', 'while_statement', 'for_statement', 'for_in_statement',
'switch_case', 'case_statement', 'switch_default', // Switch parts
'conditional_expression', // ternary operator
'binary_expression', // Often includes &&, || - check operator if needed
'boolean_operator', // Python 'and', 'or'
'catch_clause', // Try-catch adds a path
// Language Specific (Examples)
'foreach_statement', // C#, PHP
'case_clause', // Python match-case
]);
// Recursive traversal
function traverse(currentNode: Parser.SyntaxNode) {
if (decisionPointTypes.has(currentNode.type)) {
// More specific check for binary expressions (&&, ||) if needed
if (currentNode.type === 'binary_expression' || currentNode.type === 'boolean_operator') {
const operator = currentNode.childForFieldName?.('operator')?.text; // Adjust field name if needed
if (operator === '&&' || operator === '||' || operator === 'and' || operator === 'or') {
complexity++;
}
} else {
complexity++;
}
}
// Recurse into children
for (const child of currentNode.children) {
traverse(child);
}
}
traverse(node);
return complexity;
}
function parseCodeWithTreeSitter(
code: string,
filePath: string
): Definition[] {
const definitions: Definition[] = [];
const fileExt = path.extname(filePath).toLowerCase();
const language = languageMap[fileExt];
if (!language) {
return [{ type: "error", name: "Unsupported file type", startLine: 0, endLine: 0 }];
}
parser.setLanguage(language);
let tree: Parser.Tree;
try {
tree = parser.parse(code);
} catch (error: any) {
// Use absolute paths for reliable comparison
const absoluteFilePath = path.resolve(filePath);
const absoluteTargetFilePath = path.resolve("src/index.ts"); // Resolve relative to CWD
const errorLogPath = path.join(process.cwd(), "parser-error.log"); // Log in CWD
if (absoluteFilePath === absoluteTargetFilePath) {
const errorMessage = `ERROR: Tree-sitter failed to parse ${filePath} at ${new Date().toISOString()}.\nFull error:\n${JSON.stringify(error, null, 2)}\n---\n`;
// Log the error asynchronously, but don't block parsing
fs.appendFile(errorLogPath, errorMessage)
.then(() => console.error(`ERROR: Tree-sitter failed to parse ${filePath}. See ${errorLogPath} for details.`))
.catch(logErr => console.error(`FATAL: Failed to write to ${errorLogPath}: ${logErr.message}`));
// Return a specific error definition to indicate parsing failure for this critical file
return [{ type: "error", name: `Failed to parse self (${filePath})`, startLine: 0, endLine: 0 }];
} else {
// For other files, just log the error and return an empty array
console.error(`Error parsing ${filePath}:`, error);
return [{ type: "error", name: `Failed to parse ${filePath}`, startLine: 0, endLine: 0 }];
}
}
const langQueries = queries[fileExt];
if (!langQueries) {
return [{ type: "error", name: "No queries defined for file type", startLine: 0, endLine: 0 }];
}
// Generate unique IDs
let idCounter = 0;
const generateId = () => `def-${idCounter++}`;
for (const defType in langQueries) {
const queryStr = langQueries[defType];
if (!queryStr) continue; // Skip empty queries (like CSS or JS enums)
try {
const query = new Parser.Query(language, queryStr);
const matches = query.matches(tree.rootNode);
for (const match of matches) {
const nameNode = match.captures.find((c: Parser.QueryCapture) => c.name === "name")?.node;
const modifierNode = match.captures.find((c: Parser.QueryCapture) => c.name === "modifier")?.node;
const definitionNode = match.captures.find((c: Parser.QueryCapture) => c.name === defType)?.node; // Use defType capture
if (!nameNode || !definitionNode) continue;
// Capture optional fields
const dataTypeNode = match.captures.find((c: Parser.QueryCapture) => c.name === "dataType")?.node;
const valueNode = match.captures.find((c: Parser.QueryCapture) => c.name === "value")?.node;
const returnTypeNode = match.captures.find((c: Parser.QueryCapture) => c.name === "return_type")?.node;
const paramsNode = match.captures.find((c: Parser.QueryCapture) => c.name === "params")?.node; // Capture params block
// Determine parent type based on language and definition type
let parentType: string | undefined;
const localScopeTypes = ['variable', 'local_variable']; // Types typically defined within functions/methods
// Parent type is determined later by the tree traversal approach
// Local scope types don't need special handling since we use node traversal
const definition: Definition = {
id: generateId(),
type: defType,
name: nameNode.text,
startLine: definitionNode.startPosition.row + 1,
endLine: definitionNode.endPosition.row + 1,
loc: definitionNode.endPosition.row - definitionNode.startPosition.row + 1, // Calculate LoC
modifier: modifierNode?.text,
dataType: dataTypeNode?.text,
value: valueNode?.text,
returnType: returnTypeNode?.text,
children: [], // Initialize children array
// Initialize metrics - parameterCount and complexity calculated later
parameterCount: 0,
complexity: 1,
};
// Extract signature for methods/functions if possible
if (['method', 'function'].includes(defType)) {
// Calculate complexity for functions/methods
definition.complexity = calculateComplexity(definitionNode); // Calculate Complexity
// Attempt to get the full signature text
const startPos = definitionNode.startPosition;
const endPos = definitionNode.endPosition;
const sourceLines = code.split('\n');
// Heuristic: Try to capture the signature line(s)
// This might need refinement based on language specifics
let signature = '';
if (startPos.row === endPos.row) {
signature = sourceLines[startPos.row].substring(startPos.column, endPos.column);
} else {
// Multi-line signature (less common for just the signature part)
// Try to capture up to the opening brace '{' or equivalent
const openingBraceIndex = definitionNode.text.indexOf('{');
signature = openingBraceIndex > -1 ? definitionNode.text.substring(0, openingBraceIndex).trim() : definitionNode.text.split('\n')[0].trim();
}
// Clean up signature (optional)
signature = signature.replace(/\s+/g, ' ').trim();
// definition.signature = signature; // Add if needed later
// Extract parameters if paramsNode exists
if (paramsNode) {
const parameters: Parameter[] = [];
const paramCaptures = query.captures(paramsNode); // Query within the params node
// Find parameter names and types (adjust query capture names as needed)
let paramMatch: { name?: string, type?: string } = {};
for (const capture of paramCaptures) {
if (capture.name === 'param_name') {
paramMatch.name = capture.node.text;
} else if (capture.name === 'param_type') {
paramMatch.type = capture.node.text;
}
// When we have a name, add the parameter and reset
if (paramMatch.name) {
parameters.push({ name: paramMatch.name, type: paramMatch.type });
paramMatch = {}; // Reset for the next parameter
}
}
// Fallback: If captures don't work well, parse the text directly (less robust)
if (parameters.length === 0 && paramsNode.text.length > 2) { // Avoid empty "()"
const paramList = paramsNode.text.slice(1, -1).split(','); // Remove () and split
parameters.push(...paramList.map((p: string) => {
const trimmed = p.trim();
// Basic type inference (example for TS/PHP like syntax)
const typeMatch = trimmed.match(/^(\S+)\s+(\$\S+|\S+)/); // e.g., "string $name" or "int count"
if (typeMatch) {
return { name: typeMatch[2], type: typeMatch[1] };
}
return { name: trimmed }; // Just name if no type found
}).filter((p: { name: string; type?: string; }) => p.name)); // Filter out empty params
}
definition.parameters = parameters;
definition.parameterCount = parameters.length; // Calculate Parameter Count
// Find calls within this function/method body
const callQueryStr = langQueries['call'];
if (callQueryStr) {
try {
const callQuery = new Parser.Query(language, callQueryStr);
const callMatches = callQuery.matches(definitionNode); // Search within the definition node
const calledNames = new Set<string>(); // Use Set to avoid duplicates
for (const callMatch of callMatches) {
const callNameNode = callMatch.captures.find((c: Parser.QueryCapture) => c.name === "call_name")?.node;
if (callNameNode) {
calledNames.add(callNameNode.text);
}
}
if (calledNames.size > 0) {
definition.calls = Array.from(calledNames);
}
} catch (callQueryError: any) {
console.warn(`Warning: Failed to execute call query for ${defType} ${definition.name} in ${filePath}:`, callQueryError.message);
}
}
}
// Extract return type if returnTypeNode exists
if (returnTypeNode) {
definition.returnType = returnTypeNode.text;
} else {
// Fallback: Try to capture from signature text (language-specific)
// Example for PHP/TS style: function getName(): string { ... }
const returnTypeMatch = signature.match(/:\s*(\w+)\s*\{?$/);
if (returnTypeMatch) {
definition.returnType = returnTypeMatch[1];
}
}
}
definitions.push(definition);
}
} catch (queryError: any) {
console.error(`Error executing query for ${defType} in ${filePath}:`, queryError);
// Continue to next definition type
}
}
// --- Parent-Child Relationship Logic ---
// Create a map for quick lookup by ID
const definitionMap = new Map(definitions.map(def => [def.id, def]));
definitions.forEach(def => {
const node = tree.rootNode.descendantForPosition({ row: def.startLine - 1, column: 0 }); // Get node at start line
if (node) {
// No redundant parent-child relationship logic (removed)
// More robust parent finding: traverse up the syntax tree
let potentialParentNode = node.parent;
let parent: Definition | undefined = undefined;
while (potentialParentNode) {
parent = definitions.find(p =>
p.id !== def.id &&
p.startLine === potentialParentNode!.startPosition.row + 1 &&
p.endLine === potentialParentNode!.endPosition.row + 1 &&
['class', 'namespace', 'interface', 'enum', 'method', 'function'].includes(p.type) // Plausible parent types
);
if (parent) break; // Found a direct parent definition
potentialParentNode = potentialParentNode.parent;
}
if (parent) {
def.parentId = parent.id;
if (!parent.children) {
parent.children = [];
}
if (def.id) { // Ensure def.id is defined before pushing
parent.children.push(def.id);
}
}
}
});
return definitions;
}
// Helper to find the type of the nearest enclosing definition
// The findParentType function was removed as it was an unimplemented placeholder
// and the parent-child relationship is now handled by the tree traversal approach
// --- Filtering Logic --- Refactored
// applyFilters function removed - use applyFiltersToDefinitions directly
// --- XML Formatting ---
function formatResultsXML(
results: { [filePath: string]: Definition[] },
detailLevel: 'minimal' | 'standard' | 'detailed'
): string {
const root = create({ version: "1.0", encoding: "UTF-8" }).ele("CodeScanResults");
// Helper function to recursively add definitions
function renderDefinition(def: Definition, definitions: Definition[], parentElement: any): void {
// Base attributes for all levels
const attrs: { [key: string]: any } = {
type: def.type,
name: def.name,
};
if (detailLevel !== 'minimal') {
attrs.startLine = def.startLine;
attrs.endLine = def.endLine;
if (def.modifier) attrs.modifier = def.modifier;
}
if (detailLevel === 'detailed') {
if (def.dataType) attrs.dataType = def.dataType;
if (def.value && def.type !== 'variable' && def.type !== 'property') {
attrs.value = def.value;
}
if (def.returnType) attrs.returnType = def.returnType;
// Add metrics
// if (def.loc !== undefined) attrs.loc = def.loc; // Removed as requested
// if (def.parameterCount !== undefined) attrs.parameterCount = def.parameterCount; // Removed as requested
// if (def.complexity !== undefined) attrs.complexity = def.complexity; // Removed as requested
// Parameters are handled separately below
}
const defEle = parentElement.ele("Definition", attrs);
// Add parameters for detailed level
if (detailLevel === 'detailed' && def.parameters && def.parameters.length > 0) {
const paramsEle = defEle.ele("Parameters");
def.parameters.forEach((param: Parameter) => {
const paramAttrs: { [key: string]: any } = { name: param.name };
if (param.type) paramAttrs.type = param.type;
paramsEle.ele("Parameter", paramAttrs);
});
}
// Add calls for detailed level
if (detailLevel === 'detailed' && def.calls && def.calls.length > 0) {
const callsEle = defEle.ele("Calls");
def.calls.forEach((callName: string) => {
callsEle.ele("Call", { name: callName });
});
}
// Recursively add children if they exist
if (def.children && def.children.length > 0) {
def.children.forEach((childId) => {
const child = definitions.find((d) => d.id === childId);
if (child) {
renderDefinition(child, definitions, defEle); // Pass defEle as the new parent
}
});
}
}
for (const filePath in results) {
const fileEle = root.ele("File", { path: filePath });
const definitions = results[filePath];
// Filter for top-level definitions (no parentId) to start the hierarchy
const topLevelDefs = definitions.filter(def => !def.parentId);
topLevelDefs.forEach((def) => {
renderDefinition(def, definitions, fileEle); // Pass fileEle as the initial parent
});
}
return root.end({ prettyPrint: true });
}
// --- Markdown Formatting ---
function formatResultsMarkdown(
results: { [filePath: string]: Definition[] },
detailLevel: 'minimal' | 'standard' | 'detailed',
directoryPath: string // Added directory path for relative file paths
): string {
let md = `# Code Scan Results for ${directoryPath}\n\n`; // Use provided directory path
// Helper function to recursively render definitions
function renderDefinition(def: Definition, definitions: Definition[], indent: number = 0): string {
const indentation = " ".repeat(indent); // Two spaces per indent level
let result = "";
// Determine output based on detail level
switch (detailLevel) {
case 'minimal':
// Minimal: Type: Name
result = `${indentation}- **${def.type.toUpperCase()}**: \`${def.name}\``;
break;
case 'standard':
default:
// Standard: Type: Name (Lines: Start-End) [Modifier]
const lineInfo = `(Lines: ${def.startLine}-${def.endLine})`;
const modifierText = def.modifier ? ` [\`${def.modifier}\`]` : "";
result = `${indentation}- **${def.type.toUpperCase()}**: \`${def.name}\` ${lineInfo}${modifierText}`;
break;
case 'detailed':
// Detailed: Type: Name (Lines: Start-End) [Modifier] {Details}
const detailedLineInfo = `(Lines: ${def.startLine}-${def.endLine})`;
const detailedModifierText = def.modifier ? ` [\`${def.modifier}\`]` : "";
let details = [];
if (def.dataType) details.push(`DataType: \`${def.dataType}\``);
if (def.value && def.type !== 'variable' && def.type !== 'property') details.push(`Value: \`${def.value.substring(0, 50)}${def.value.length > 50 ? '...' : ''}\``);
if (def.parameters && def.parameters.length > 0) {
const paramText = def.parameters.map(p => `\`${p.name}${p.type ? `: ${p.type}` : ''}\``).join(', ');
details.push(`Params: ${paramText}`);
}
if (def.returnType) details.push(`Returns: \`${def.returnType}\``);
// Add metrics
// if (def.loc !== undefined) details.push(`LoC: ${def.loc}`); // Removed as requested
// if (def.parameterCount !== undefined) details.push(`Param Count: ${def.parameterCount}`); // Removed as requested
// if (def.complexity !== undefined) details.push(`Complexity: ${def.complexity}`); // Removed as requested
// Add calls
if (def.calls && def.calls.length > 0) {
details.push(`Calls: \`${def.calls.join('`, `')}\``);
}
const detailText = details.length > 0 ? ` { ${details.join('; ')} }` : "";
result = `${indentation}- **${def.type.toUpperCase()}**: \`${def.name}\` ${detailedLineInfo}${detailedModifierText}${detailText}`;
break;
}
result += "\n";
// Recursively add children
if (def.children && def.children.length > 0) {
def.children.forEach((childId) => {
const child = definitions.find((d) => d.id === childId);
if (child) {
result += renderDefinition(child, definitions, indent + 1);
}
});
}
return result;
}
const filePaths = Object.keys(results).sort(); // Sort file paths for consistent output
for (const filePath of filePaths) {
// Use relative path from the scanned directory
const relativeFilePath = path.relative(directoryPath, filePath).replace(/\\/g, '/'); // Normalize path separators
md += `## File: \`${relativeFilePath}\`\n\n`; // Use relative path
const definitions = results[filePath];
// Filter for top-level definitions (no parentId) to start the hierarchy
const topLevelDefs = definitions.filter(def => !def.parentId);
if (topLevelDefs.length === 0 && definitions.length > 0) {
// Handle cases where all definitions might be children (e.g., only methods in a class)
// This part might need refinement depending on desired output for such cases.
// For now, just list all if no top-level are found.
// definitions.forEach(def => {
// md += renderDefinition(def, definitions, 0);
// });
// Alternative: Indicate no top-level definitions found explicitly?
md += ` *(No top-level definitions found, listing all)*\n`;
definitions.forEach(def => { md += renderDefinition(def, definitions, 1); });
} else {
topLevelDefs.forEach((def) => {
md += renderDefinition(def, definitions, 0);
});
}
md += "\n"; // Add space between files
}
// Add metadata section (optional, example)
const metaEntries = results["metadata"] || []; // Assuming metadata might be stored under a special key
if (metaEntries.length > 0) {
md += `## Metadata\n\n`;
metaEntries.forEach(meta => {
md += `- **${meta.type}**: ${meta.name}\n`; // Adjust formatting as needed
});
md += "\n";
}
return md;
}
// --- JSON Formatting ---
function formatResultsJSON(
results: { [filePath: string]: Definition[] },
detailLevel: 'minimal' | 'standard' | 'detailed'
): string {
const output: { [filePath: string]: any[] } = {};
// Helper function to create a JSON object for a definition based on detail level
function createDefinitionObject(def: Definition, allDefs: Definition[]): any {
const baseObj: any = {
type: def.type,
name: def.name,
};
if (detailLevel === 'minimal') {
return baseObj; // Only type and name for minimal
}
// Standard and Detailed include lines
baseObj.startLine = def.startLine;
baseObj.endLine = def.endLine;
if (def.modifier) baseObj.modifier = def.modifier;
if (detailLevel === 'detailed') {
// Detailed includes everything
if (def.dataType) baseObj.dataType = def.dataType;
if (def.value && def.type !== 'variable' && def.type !== 'property') baseObj.value = def.value;
if (def.parameters && def.parameters.length > 0) baseObj.parameters = def.parameters;
if (def.returnType) baseObj.returnType = def.returnType;
// Add metrics for detailed level
// if (def.loc !== undefined) baseObj.loc = def.loc; // Removed as requested
// if (def.parameterCount !== undefined) baseObj.parameterCount = def.parameterCount; // Removed as requested
// if (def.complexity !== undefined) baseObj.complexity = def.complexity; // Removed as requested
// Add calls for detailed level
if (def.calls && def.calls.length > 0) baseObj.calls = def.calls;
}
// Add children recursively for standard and detailed
if (def.children && def.children.length > 0) {
baseObj.children = def.children
.map(childId => allDefs.find(d => d.id === childId))
.filter((child): child is Definition => !!child) // Type guard
.map(child => createDefinitionObject(child, allDefs)); // Recursive call
}
return baseObj;
}
for (const filePath in results) {
const definitions = results[filePath];
// Filter for top-level definitions (no parentId) to start the hierarchy
const topLevelDefs = definitions.filter(def => !def.parentId);
output[filePath] = topLevelDefs.map(def => createDefinitionObject(def, definitions));
}
return JSON.stringify(output, null, 2); // Pretty print JSON
}
// --- Core Scanning Logic --- Refactored
async function performScan(
directory: string,
filePatterns: string[],
outputFormat: 'xml' | 'markdown' | 'json',
detailLevel: 'minimal' | 'standard' | 'detailed' = 'standard',
filterOptions: FilterOptions = {}
): Promise<string> {
const startTime = Date.now();
console.error(`Starting scan in directory: ${directory}`);
console.error(`File patterns: ${filePatterns.join(', ')}`);
console.error(`Output format: ${outputFormat}, Detail level: ${detailLevel}`);
console.error(`Filter options: ${JSON.stringify(filterOptions)}`);
// Resolve the target directory relative to the current working directory
const targetDir = path.resolve(process.cwd(), directory);
console.error(`Resolved target directory: ${targetDir}`);
try {
// Check if the directory exists using async fs
await fs.access(targetDir);
} catch (error) {
throw new Error(`Directory not found: ${targetDir}`);
}
// Find .gitignore
const gitignorePath = await findGitignore(targetDir);
const ignoreFilter = await getIgnoreFilter(gitignorePath);
console.error(`Using .gitignore: ${gitignorePath || 'None found'}`);
// --- File Discovery ---
console.error("Starting file discovery...");
let files: Set<string>; // Declare files set here
// Check if includePaths is provided and should be restrictive
if (filterOptions.includePaths && filterOptions.includePaths.length > 0) {
console.error("`includePaths` provided, operating in restrictive mode.");
files = new Set<string>(); // Initialize as empty set
// Process only the paths specified in includePaths
for (const includePath of filterOptions.includePaths) {
// Handle potential glob patterns within includePaths if necessary,
// or treat them as specific files/directories.
// Current logic reuses the file/directory handling from below.
const absoluteIncludePath = path.resolve(targetDir, includePath);
try {
const stats = await fs.stat(absoluteIncludePath);
if (stats.isFile()) {
files.add(path.normalize(absoluteIncludePath));
console.error(`Added specific file from includePaths: ${absoluteIncludePath}`);
} else if (stats.isDirectory()) {
console.error(`Included path is a directory, scanning recursively: ${absoluteIncludePath}`);
// Use fg to find files within the directory, respecting basic ignores
const dirFiles = await fg(path.join(absoluteIncludePath, '**/*').replace(/\\/g, '/'), {
dot: true,
onlyFiles: true,
absolute: true,
ignore: ['**/node_modules/**', '**/.git/**'], // Consistent ignores
});
dirFiles.forEach(f => files.add(path.normalize(f)));
console.error(`Added ${dirFiles.length} files from included directory: ${absoluteIncludePath}`);
}
} catch (statError: any) {
// Handle cases where includePath might be a glob pattern needing fg
if (includePath.includes('*') || includePath.includes('?')) {
console.error(`Included path looks like a glob, attempting glob match: ${includePath}`);
try {
const globMatches = await fg(path.join(targetDir, includePath).replace(/\\/g, '/'), {
dot: true, onlyFiles: true, absolute: true, cwd: targetDir,
ignore: ['**/node_modules/**', '**/.git/**'],
});
globMatches.forEach(match => files.add(path.normalize(match)));
console.error(`Added ${globMatches.length} files from includePaths glob: ${includePath}`);
} catch (globError) {
console.error(`Error matching includePaths glob ${includePath}:`, globError);
}
} else if (statError.code === 'ENOENT') {
console.warn(`Warning: Included path not found: ${absoluteIncludePath}`);
} else {
console.error(`Error processing included path ${absoluteIncludePath}:`, statError);
}
}
}
console.error(`Total files after processing restrictive includePaths: ${files.size}`);
} else {
// --- Standard File Discovery using filePatterns (glob) ---
console.error("No restrictive `includePaths`, using standard `filePatterns` globbing.");
const globMatchedFiles = new Set<string>(); // Store absolute paths from glob matching
// Combine default and provided patterns if necessary
const combinedPatterns = [...new Set(filePatterns)];
console.error(`Combined glob patterns for search: ${combinedPatterns.join(', ')}`);
// Execute glob patterns relative to the target directory
const globPatterns = combinedPatterns.map(p => path.join(targetDir, p).replace(/\\/g, '/'));
console.error(`Absolute glob patterns for fast-glob: ${globPatterns.join(', ')}`);
try {
const globMatches = await fg(globPatterns, {
dot: true, onlyFiles: true, absolute: true, cwd: targetDir,
ignore: ['**/node_modules/**', '**/.git/**'],
});
console.error(`fast-glob matched ${globMatches.length} files initially.`);
globMatches.forEach(match => globMatchedFiles.add(path.normalize(match)));
} catch (globError) {
console.error("Error during fast-glob execution:", globError);
throw new Error("File globbing failed.");
}
files = new Set<string>(globMatchedFiles); // Start with glob results
// --- Include specific non-glob paths (additive) ---
// This part only runs if includePaths was NOT restrictive
const nonGlobIncludes = filterOptions.includePaths?.filter(p => !p.includes('*') && !p.includes('?')) || [];
if (nonGlobIncludes.length > 0) {
console.error("Adding specific non-glob paths from `includePaths`...");
for (const includePath of nonGlobIncludes) {
const absoluteIncludePath = path.resolve(targetDir, includePath);
try {
const stats = await fs.stat(absoluteIncludePath);
if (stats.isFile()) {
files.add(path.normalize(absoluteIncludePath));
console.error(`Added specific file from includePaths: ${absoluteIncludePath}`);
} else if (stats.isDirectory()) {
console.error(`Included path is a directory, scanning recursively: ${absoluteIncludePath}`);
const dirFiles = await fg(path.join(absoluteIncludePath, '**/*').replace(/\\/g, '/'), {
dot: true, onlyFiles: true, absolute: true,
ignore: ['**/node_modules/**', '**/.git/**'],
});
dirFiles.forEach(f => files.add(path.normalize(f)));
console.error(`Added ${dirFiles.length} files from included directory: ${absoluteIncludePath}`);
}
} catch (statError: any) {
if (statError.code === 'ENOENT') {
console.warn(`Warning: Included path not found: ${absoluteIncludePath}`);
} else {
console.error(`Error stating included path ${absoluteIncludePath}:`, statError);
}
}
}
}
}
// --- End of Conditional File Discovery ---
// --- Include specific non-glob paths if provided --- // This section title is now misleading, the logic is handled above. Remove/adjust comment.
// const files = new Set<string>(globMatchedFiles); // This line is now inside the else block
// The logic previously here (lines 883-911) has been integrated into the
// conditional blocks above (restrictive 'if' and standard 'else')
// to handle includePaths correctly in both scenarios.
// --- Filtering based on .gitignore and excludePaths ---
let filesToFilter = Array.from(files);
console.error(`Total files before gitignore/exclude filtering: ${filesToFilter.length}`);
// 1. Apply .gitignore filter
filesToFilter = filesToFilter.filter(absPath => {
const relativePath = path.relative(targetDir, absPath).replace(/\\/g, '/'); // Relative path for ignore check
return ignoreFilter(relativePath);
});
console.error(`Files after gitignore filtering: ${filesToFilter.length}`);
// 2. Apply excludePaths filter (using minimatch)
const excludePatterns = filterOptions.excludePaths || [];
if (excludePatterns.length > 0) {
console.error(`Applying excludePaths patterns: ${excludePatterns.join(', ')}`);
const filteredFiles = filesToFilter.filter((absPath) => {
const relativePath = path.relative(targetDir, absPath).replace(/\\/g, '/');
// Check if the relative path matches any exclude pattern
const isExcluded = excludePatterns.some(pattern => minimatch(relativePath, pattern, { dot: true }));
if (isExcluded) {
// console.error(`Excluding file due to pattern '${excludePatterns.find(p => minimatch(relativePath, p))}': ${relativePath}`);
}
return !isExcluded; // Keep if not excluded
});
const excludedCount = filesToFilter.length - filteredFiles.length;
if (excludedCount > 0) {
console.error(`Excluded ${excludedCount} files based on excludePaths patterns.`);