Skip to content

Commit c91ed83

Browse files
author
Eric Wheeler
committed
fix: improve tree-sitter test type safety and debug logging
- Replace 'any' types with proper Parser types in helpers.ts - Add centralized DEBUG flag and debugLog function in helpers.ts - Update all console.log statements to use debugLog across all test files - This change appeases @ellipsis-dev by improving type safety and providing a clean way to control debug logging Signed-off-by: Eric Wheeler <[email protected]>
1 parent 6d74c7d commit c91ed83

File tree

3 files changed

+29
-19
lines changed

3 files changed

+29
-19
lines changed

src/services/tree-sitter/__tests__/helpers.ts

Lines changed: 19 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -5,11 +5,21 @@ import * as path from "path"
55
import Parser from "web-tree-sitter"
66
import tsxQuery from "../queries/tsx"
77

8+
// Global debug flag - set to 0 to disable debug logging
9+
export const DEBUG = 0
10+
11+
// Debug function to conditionally log messages
12+
export const debugLog = (message: string, ...args: any[]) => {
13+
if (DEBUG) {
14+
console.debug(message, ...args)
15+
}
16+
}
17+
818
// Mock fs module
919
const mockedFs = jest.mocked(fs)
1020

1121
// Store the initialized TreeSitter for reuse
12-
let initializedTreeSitter: any = null
22+
let initializedTreeSitter: Parser | null = null
1323

1424
// Function to initialize tree-sitter
1525
export async function initializeTreeSitter() {
@@ -98,7 +108,7 @@ export async function testParseSourceCodeDefinitions(
98108
expect(mockedLoadRequiredLanguageParsers).toHaveBeenCalledWith([testFilePath])
99109
expect(mockedLoadRequiredLanguageParsers).toHaveBeenCalled()
100110

101-
console.log(`content:\n${content}\n\nResult:\n${result}`)
111+
debugLog(`content:\n${content}\n\nResult:\n${result}`)
102112
return result
103113
}
104114

@@ -114,15 +124,15 @@ export async function inspectTreeStructure(content: string, language: string = "
114124
const tree = parser.parse(content)
115125

116126
// Print the tree structure
117-
console.log(`TREE STRUCTURE (${language}):\n${tree.rootNode.toString()}`)
127+
debugLog(`TREE STRUCTURE (${language}):\n${tree.rootNode.toString()}`)
118128

119129
// Add more detailed debug information
120-
console.log("\nDETAILED NODE INSPECTION:")
130+
debugLog("\nDETAILED NODE INSPECTION:")
121131

122132
// Function to recursively print node details
123-
const printNodeDetails = (node: any, depth: number = 0) => {
133+
const printNodeDetails = (node: Parser.SyntaxNode, depth: number = 0) => {
124134
const indent = " ".repeat(depth)
125-
console.log(
135+
debugLog(
126136
`${indent}Node Type: ${node.type}, Start: ${node.startPosition.row}:${node.startPosition.column}, End: ${node.endPosition.row}:${node.endPosition.column}`,
127137
)
128138

@@ -132,17 +142,17 @@ export async function inspectTreeStructure(content: string, language: string = "
132142
if (child) {
133143
// For type_alias_declaration nodes, print more details
134144
if (node.type === "type_alias_declaration") {
135-
console.log(`${indent} TYPE ALIAS: ${node.text}`)
145+
debugLog(`${indent} TYPE ALIAS: ${node.text}`)
136146
}
137147

138148
// For conditional_type nodes, print more details
139149
if (node.type === "conditional_type" || child.type === "conditional_type") {
140-
console.log(`${indent} CONDITIONAL TYPE FOUND: ${child.text}`)
150+
debugLog(`${indent} CONDITIONAL TYPE FOUND: ${child.text}`)
141151
}
142152

143153
// For infer_type nodes, print more details
144154
if (node.type === "infer_type" || child.type === "infer_type") {
145-
console.log(`${indent} INFER TYPE FOUND: ${child.text}`)
155+
debugLog(`${indent} INFER TYPE FOUND: ${child.text}`)
146156
}
147157

148158
printNodeDetails(child, depth + 1)

src/services/tree-sitter/__tests__/parseSourceCodeDefinitions.json.test.ts

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ import * as path from "path"
55
import { fileExistsAtPath } from "../../../utils/fs"
66
import { loadRequiredLanguageParsers } from "../languageParser"
77
import { javascriptQuery } from "../queries"
8-
import { initializeTreeSitter, testParseSourceCodeDefinitions, inspectTreeStructure } from "./helpers"
8+
import { initializeTreeSitter, testParseSourceCodeDefinitions, inspectTreeStructure, debugLog } from "./helpers"
99

1010
// Sample JSON content for tests
1111
const sampleJsonContent = `{
@@ -132,15 +132,15 @@ describe("parseSourceCodeDefinitions for JSON", () => {
132132
})
133133

134134
it("should parse top-level object properties", async function () {
135-
console.log("\n=== Parse Test: Top-level Properties ===")
135+
debugLog("\n=== Parse Test: Top-level Properties ===")
136136
const result = await testParseSourceCodeDefinitions(testFilePath, sampleJsonContent, jsonOptions)
137137
expect(result).toBeDefined()
138138
expect(result).toContain('"server"')
139139
expect(result).toContain('"database"')
140140
})
141141

142142
it("should parse nested object properties", async function () {
143-
console.log("\n=== Parse Test: Nested Properties ===")
143+
debugLog("\n=== Parse Test: Nested Properties ===")
144144
const result = await testParseSourceCodeDefinitions(testFilePath, sampleJsonContent, jsonOptions)
145145
expect(result).toBeDefined()
146146
expect(result).toContain('"ssl"')

src/services/tree-sitter/__tests__/parseSourceCodeDefinitions.tsx.test.ts

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ import * as path from "path"
55
import { fileExistsAtPath } from "../../../utils/fs"
66
import { loadRequiredLanguageParsers } from "../languageParser"
77
import tsxQuery from "../queries/tsx"
8-
import { initializeTreeSitter, testParseSourceCodeDefinitions, inspectTreeStructure } from "./helpers"
8+
import { initializeTreeSitter, testParseSourceCodeDefinitions, inspectTreeStructure, debugLog } from "./helpers"
99

1010
// Sample component content
1111
const sampleTsxContent = `
@@ -255,7 +255,7 @@ it("should parse template literal types", async function () {
255255

256256
// Run the test to see if template literal types are already supported
257257
const result = await testParseSourceCodeDefinitions("/test/template-literal-type.tsx", templateLiteralTypeContent)
258-
console.log("Template literal type parsing result:", result)
258+
debugLog("Template literal type parsing result:", result)
259259

260260
// Check if the result contains the type declarations
261261
expect(result).toBeDefined()
@@ -265,7 +265,7 @@ it("should parse template literal types", async function () {
265265
expect(result).toContain("RouteParams<T")
266266
expect(result).toContain("StringOps<T")
267267

268-
console.log("Template literal types are already partially supported by the parser!")
268+
debugLog("Template literal types are already partially supported by the parser!")
269269

270270
// Note: EventName and CSSProperty types aren't fully captured in the output,
271271
// but this is likely due to the minimum line requirement (MIN_COMPONENT_LINES = 4)
@@ -337,23 +337,23 @@ it("should parse conditional types", async function () {
337337

338338
// First run without adding the query pattern to see if it's already implemented
339339
const initialResult = await testParseSourceCodeDefinitions("/test/conditional-type.tsx", conditionalTypeContent)
340-
console.log("Initial result before adding query pattern:", initialResult)
340+
debugLog("Initial result before adding query pattern:", initialResult)
341341

342342
// Save the initial line count to compare later
343343
const initialLineCount = initialResult ? initialResult.split("\n").length : 0
344344
const initialCaptures = initialResult ? initialResult : ""
345345

346346
// Now check if the new query pattern improves the output
347347
const updatedResult = await testParseSourceCodeDefinitions("/test/conditional-type.tsx", conditionalTypeContent)
348-
console.log("Updated result after adding query pattern:", updatedResult)
348+
debugLog("Updated result after adding query pattern:", updatedResult)
349349

350350
// Compare results
351351
const updatedLineCount = updatedResult ? updatedResult.split("\n").length : 0
352352
expect(updatedResult).toBeDefined()
353353

354354
// Check if the feature is already implemented
355355
if (initialResult && initialResult.includes("ReturnType<T>") && initialResult.includes("Parameters<T>")) {
356-
console.log("Conditional types are already supported by the parser!")
356+
debugLog("Conditional types are already supported by the parser!")
357357
// If the feature is already implemented, we don't need to check if the updated result is better
358358
expect(true).toBe(true)
359359
} else {
@@ -533,7 +533,7 @@ it("should parse switch/case statements", async function () {
533533
// await inspectTreeStructure(switchCaseContent)
534534

535535
const result = await testParseSourceCodeDefinitions("/test/switch-case.tsx", switchCaseContent)
536-
console.log("Switch Case Test Result:", result)
536+
debugLog("Switch Case Test Result:", result)
537537
expect(result).toBeDefined()
538538
expect(result).toContain("handleTemperature")
539539
// Check for case statements in the output

0 commit comments

Comments
 (0)