Skip to content

Commit 50ee20b

Browse files
feat: use streaming parse json
1 parent 5b85269 commit 50ee20b

File tree

1 file changed

+24
-11
lines changed

1 file changed

+24
-11
lines changed

src/view.ts

Lines changed: 24 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -20,23 +20,39 @@ let child: ChildProcessWithoutNullStreams | undefined
2020

2121
function streamedPromise(
2222
proc: ChildProcessWithoutNullStreams
23-
): Promise<string> {
24-
let stdout = ''
23+
): Promise<SgSearch[]> {
24+
// push all data into the result array
25+
let result: SgSearch[] = []
26+
// don't concatenate a single string/buffer
27+
// only maintain the last trailing line
28+
let trailingLine = ''
29+
// kill previous search
2530
if (child) {
26-
// kill previous search
2731
child.kill('SIGTERM')
2832
}
2933
child = proc
30-
child.stdout.on('data', data => {
31-
stdout += data
34+
// stream parsing JSON
35+
child.stdout.on('data', (data: string) => {
36+
const lines = (trailingLine + data).split(/\r?\n/)
37+
trailingLine = ''
38+
for (let i = 0; i < lines.length; i++) {
39+
try {
40+
result.push(JSON.parse(lines[i]))
41+
} catch (e) {
42+
// only store the last non-json line
43+
if (i === lines.length - 1) {
44+
trailingLine = lines[i]
45+
}
46+
}
47+
}
3248
})
3349
return new Promise((resolve, reject) =>
3450
child!.on('exit', (code, signal) => {
3551
// exit without signal, search ends correctly
3652
// TODO: is it correct now?
3753
if (!signal && code === 0) {
3854
child = undefined
39-
resolve(stdout)
55+
resolve(result)
4056
} else {
4157
reject([code, signal])
4258
}
@@ -54,14 +70,11 @@ async function getPatternRes(pattern: string) {
5470
const uris = workspace.workspaceFolders?.map(i => i.uri?.fsPath) ?? []
5571

5672
// TODO: multi-workspaces support
57-
// TODO: the code here is wrong, but we will change it
58-
let proc = spawn(command, ['run', '--pattern', pattern, '--json=compact'], {
73+
let proc = spawn(command, ['run', '--pattern', pattern, '--json=stream'], {
5974
cwd: uris[0]
6075
})
61-
const stdout = await streamedPromise(proc)
6276
try {
63-
let res: SgSearch[] = JSON.parse(stdout)
64-
return res
77+
return await streamedPromise(proc)
6578
} catch (e) {
6679
console.error(e)
6780
return []

0 commit comments

Comments
 (0)