Skip to content

Commit 6e47ae7

Browse files
fix(cli): forward signals from npm shim (#26259)
Co-authored-by: Aiden Cline <aidenpcline@gmail.com>
1 parent 9ca4be6 commit 6e47ae7

1 file changed

Lines changed: 32 additions & 12 deletions

File tree

packages/opencode/bin/opencode

Lines changed: 32 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -5,31 +5,51 @@ const fs = require("fs")
55
const path = require("path")
66
const os = require("os")
77

8+
const forwardedSignals = ["SIGINT", "SIGTERM", "SIGHUP"]
9+
810
function run(target) {
9-
const result = childProcess.spawnSync(target, process.argv.slice(2), {
11+
const child = childProcess.spawn(target, process.argv.slice(2), {
1012
stdio: "inherit",
1113
})
12-
if (result.error) {
13-
console.error(result.error.message)
14+
15+
child.on("error", (error) => {
16+
console.error(error.message)
1417
process.exit(1)
18+
})
19+
20+
const forwarders = {}
21+
for (const signal of forwardedSignals) {
22+
forwarders[signal] = () => {
23+
try {
24+
child.kill(signal)
25+
} catch {
26+
// The child may have already exited.
27+
}
28+
}
29+
process.on(signal, forwarders[signal])
1530
}
16-
const code = typeof result.status === "number" ? result.status : 0
17-
process.exit(code)
31+
32+
child.on("exit", (code, signal) => {
33+
for (const forwardedSignal of forwardedSignals) {
34+
process.removeListener(forwardedSignal, forwarders[forwardedSignal])
35+
}
36+
37+
if (signal) {
38+
process.kill(process.pid, signal)
39+
return
40+
}
41+
42+
process.exit(typeof code === "number" ? code : 0)
43+
})
1844
}
1945

2046
const envPath = process.env.OPENCODE_BIN_PATH
21-
if (envPath) {
22-
run(envPath)
23-
}
2447

2548
const scriptPath = fs.realpathSync(__filename)
2649
const scriptDir = path.dirname(scriptPath)
2750

2851
//
2952
const cached = path.join(scriptDir, ".opencode")
30-
if (fs.existsSync(cached)) {
31-
run(cached)
32-
}
3353

3454
const platformMap = {
3555
darwin: "darwin",
@@ -166,7 +186,7 @@ function findBinary(startDir) {
166186
}
167187
}
168188

169-
const resolved = findBinary(scriptDir)
189+
const resolved = envPath || (fs.existsSync(cached) ? cached : findBinary(scriptDir))
170190
if (!resolved) {
171191
console.error(
172192
"It seems that your package manager failed to install the right version of the opencode CLI for your platform. You can try manually installing " +

0 commit comments

Comments
 (0)