-
-
Notifications
You must be signed in to change notification settings - Fork 412
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
fix(renderer): force
process.stdout
to be a TTY to support spinners
- Loading branch information
Showing
2 changed files
with
64 additions
and
12 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,49 @@ | ||
import { constants } from 'node:fs' | ||
import fs from 'node:fs/promises' | ||
import tty from 'node:tty' | ||
|
||
const getHandle = async () => { | ||
if (process.platform === 'win32') { | ||
return await fs.open('conout$', constants.O_WRONLY | constants.O_EXCL, 0o666) | ||
} else { | ||
return await fs.open('/dev/tty', constants.O_WRONLY + constants.O_NOCTTY) | ||
} | ||
} | ||
|
||
/** | ||
* Try to override the `process.stdout` with a TTY `tty.WriteStream`. | ||
* When invoking lint-staged through Git hooks, the shell might not | ||
* be a TTY, but we still want to enable spinners in a "non-hacky" way. | ||
* | ||
* @returns {Promise<fs.FileHandle | null>} the `FileHandle` pointing to the TTY, or `null` when failed. | ||
*/ | ||
export const forceTty = async () => { | ||
/** No need to do anything if stdout is already a TTY. */ | ||
if (process.stdout.isTTY) return null | ||
|
||
try { | ||
const handle = await getHandle() | ||
|
||
/** | ||
* Probably not realistic that the TTY handle is not a TTY, | ||
* but close the handle just in case. | ||
*/ | ||
if (tty.isatty(handle.fd)) { | ||
await handle.close() | ||
return null | ||
} | ||
|
||
const stdout = new tty.WriteStream(handle.fd) | ||
|
||
/** Override `process.stdout` */ | ||
Object.defineProperty(process, 'stdout', { | ||
configurable: true, | ||
enumerable: true, | ||
get: () => stdout, | ||
}) | ||
|
||
return handle | ||
} catch { | ||
return null | ||
} | ||
} |