Skip to content

Commit e6bc9fa

Browse files
refactor: factor out unique command logic
1 parent 50ee20b commit e6bc9fa

File tree

1 file changed

+24
-14
lines changed

1 file changed

+24
-14
lines changed

src/view.ts

Lines changed: 24 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -26,13 +26,8 @@ function streamedPromise(
2626
// don't concatenate a single string/buffer
2727
// only maintain the last trailing line
2828
let trailingLine = ''
29-
// kill previous search
30-
if (child) {
31-
child.kill('SIGTERM')
32-
}
33-
child = proc
3429
// stream parsing JSON
35-
child.stdout.on('data', (data: string) => {
30+
proc.stdout.on('data', (data: string) => {
3631
const lines = (trailingLine + data).split(/\r?\n/)
3732
trailingLine = ''
3833
for (let i = 0; i < lines.length; i++) {
@@ -47,11 +42,10 @@ function streamedPromise(
4742
}
4843
})
4944
return new Promise((resolve, reject) =>
50-
child!.on('exit', (code, signal) => {
45+
proc.on('exit', (code, signal) => {
5146
// exit without signal, search ends correctly
5247
// TODO: is it correct now?
5348
if (!signal && code === 0) {
54-
child = undefined
5549
resolve(result)
5650
} else {
5751
reject([code, signal])
@@ -60,6 +54,27 @@ function streamedPromise(
6054
)
6155
}
6256

57+
async function uniqueCommand(
58+
proc: ChildProcessWithoutNullStreams
59+
): Promise<SgSearch[]> {
60+
// kill previous search
61+
if (child) {
62+
child.kill('SIGTERM')
63+
}
64+
try {
65+
// set current proc to child
66+
child = proc
67+
const ret = await streamedPromise(proc)
68+
// unset child only when the promise succeed
69+
// interrupted proc will be replaced by latter proc
70+
child = undefined
71+
return ret
72+
} catch (e) {
73+
console.error(e)
74+
return []
75+
}
76+
}
77+
6378
async function getPatternRes(pattern: string) {
6479
if (!pattern) {
6580
return
@@ -73,12 +88,7 @@ async function getPatternRes(pattern: string) {
7388
let proc = spawn(command, ['run', '--pattern', pattern, '--json=stream'], {
7489
cwd: uris[0]
7590
})
76-
try {
77-
return await streamedPromise(proc)
78-
} catch (e) {
79-
console.error(e)
80-
return []
81-
}
91+
return uniqueCommand(proc)
8292
}
8393

8494
function openFile({

0 commit comments

Comments
 (0)