1
1
const TreeSitter = require ( 'tree-sitter' ) ;
2
2
const Python = require ( 'tree-sitter-python' ) ;
3
+ const TypeScript = require ( 'tree-sitter-typescript' ) ;
4
+ const JavaScript = require ( 'tree-sitter-javascript' ) ;
3
5
const fs = require ( 'fs' ) ;
4
6
5
7
const args = JSON . parse ( process . argv [ 2 ] )
6
8
7
9
// Load the Python parser
8
10
const parser = new TreeSitter ( ) ;
9
11
// Set the language to the parser
10
- parser . setLanguage ( Python ) ;
12
+ const ext = args . path . split ( '.' ) . pop ( ) ;
13
+
14
+ let language
15
+
16
+ if ( ext === 'py' ) {
17
+ language = Python
18
+ }
19
+ else if ( ext === 'ts' ) {
20
+ language = TypeScript . typescript
21
+ }
22
+ else if ( ext === 'tsx' ) {
23
+ language = TypeScript . tsx
24
+ }
25
+ else if ( ext === 'js' || ext === 'jsx' ) {
26
+ language = JavaScript
27
+ }
28
+
29
+ parser . setLanguage ( language ) ;
30
+
11
31
// Read the code file content
12
32
const codeContent = fs . readFileSync ( args . path , 'utf8' ) ;
13
33
// Parse the code using the chosen parser
14
34
const parsed = parser . parse ( codeContent ) ;
15
35
16
- const line_to_grab = args . line
36
+ const line_to_grab = args . line + 1
37
+
38
+ if ( line_to_grab === undefined ) {
39
+ console . log ( 'No line number provided' )
40
+ process . exit ( 1 )
41
+ }
42
+
43
+ if ( line_to_grab > codeContent . split ( '\n' ) . length ) {
44
+ console . log ( 'Line number provided is greater than the number of lines in the file' )
45
+ process . exit ( 1 )
46
+ }
17
47
18
48
// Look for node where node.startPosition.row and node.endPosition.row are equal to line_to_grab
19
49
const search_node = ( node ) => {
@@ -31,16 +61,23 @@ const search_node = (node) => {
31
61
32
62
const line_node = search_node ( parsed . rootNode )
33
63
64
+ if ( ! line_node ) {
65
+ console . log ( 'No node found for line' , line_to_grab )
66
+ console . log ( 'Code:' , codeContent . split ( '\n' ) . slice ( line_to_grab - 5 , line_to_grab + 5 ) . join ( '\n' ) )
67
+ process . exit ( 1 )
68
+ }
69
+
34
70
const parent = line_node . parent
35
71
36
- if ( parent ) {
37
- const start_line = parent . startPosition . row
38
- const end_line = parent . endPosition . row
39
- // Return codeContent from start_line to end_line
40
- const lines = codeContent . split ( '\n' ) . slice ( start_line , end_line + 1 )
41
- parent . content = lines . join ( '\n' )
72
+ if ( parent . text . length > 256 ) {
73
+ console . log ( 'Parent node text is too long, truncating' )
74
+ const index = parent . text . indexOf ( line_node . text )
75
+ const start = index - 128
76
+ const end = index + 128
77
+ parent . text = parent . text . slice ( start , end )
42
78
}
43
79
80
+
44
81
console . log ( {
45
82
offending_line : line_node . text ,
46
83
line_node : line_node ,
0 commit comments