|
| 1 | +import { execFileSync } from "node:child_process"; |
| 2 | +import path from "node:path"; |
| 3 | +import { fileURLToPath } from "node:url"; |
| 4 | + |
| 5 | +const WAIT_TIMEOUT_MS = 15_000; |
| 6 | +const POLL_INTERVAL_MS = 200; |
| 7 | + |
| 8 | +const repoRoot = path.resolve( |
| 9 | + path.dirname(fileURLToPath(import.meta.url)), |
| 10 | + "..", |
| 11 | +); |
| 12 | +const electronDist = path.join(repoRoot, "node_modules", "electron", "dist"); |
| 13 | +const pattern = electronDist.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); |
| 14 | + |
| 15 | +function runningElectronPids() { |
| 16 | + try { |
| 17 | + const out = execFileSync("pgrep", ["-f", pattern], { encoding: "utf8" }); |
| 18 | + return out.split("\n").filter(Boolean); |
| 19 | + } catch (error) { |
| 20 | + if (error.status === 1) return []; |
| 21 | + throw error; |
| 22 | + } |
| 23 | +} |
| 24 | + |
| 25 | +const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); |
| 26 | + |
| 27 | +if (process.platform !== "win32") { |
| 28 | + try { |
| 29 | + const initialPids = runningElectronPids(); |
| 30 | + if (initialPids.length > 0) { |
| 31 | + console.log( |
| 32 | + `Waiting for previous Electron instance to exit (pids: ${initialPids.join(", ")})`, |
| 33 | + ); |
| 34 | + const startedAt = Date.now(); |
| 35 | + while (Date.now() - startedAt < WAIT_TIMEOUT_MS) { |
| 36 | + await sleep(POLL_INTERVAL_MS); |
| 37 | + if (runningElectronPids().length === 0) break; |
| 38 | + } |
| 39 | + const remaining = runningElectronPids(); |
| 40 | + if (remaining.length > 0) { |
| 41 | + console.warn( |
| 42 | + `Previous Electron instance still running after ${WAIT_TIMEOUT_MS}ms (pids: ${remaining.join(", ")}), starting anyway`, |
| 43 | + ); |
| 44 | + } else { |
| 45 | + console.log( |
| 46 | + `Previous Electron instance exited after ${((Date.now() - startedAt) / 1000).toFixed(1)}s`, |
| 47 | + ); |
| 48 | + } |
| 49 | + } |
| 50 | + } catch (error) { |
| 51 | + console.warn( |
| 52 | + `Skipping wait for previous Electron instance, pgrep failed: ${error.code ?? error.status ?? error.message}`, |
| 53 | + ); |
| 54 | + } |
| 55 | +} |
0 commit comments