2020-10-02 17:52:19 -04:00
|
|
|
// make sure that bins are executable, and that they don't have
|
|
|
|
// windows line-endings on the hashbang line.
|
2022-12-06 22:18:33 -05:00
|
|
|
const {
|
|
|
|
chmod,
|
|
|
|
open,
|
|
|
|
readFile,
|
|
|
|
} = require('fs/promises')
|
2020-10-02 17:52:19 -04:00
|
|
|
|
|
|
|
const execMode = 0o777 & (~process.umask())
|
|
|
|
|
|
|
|
const writeFileAtomic = require('write-file-atomic')
|
|
|
|
|
|
|
|
const isWindowsHashBang = buf =>
|
|
|
|
buf[0] === '#'.charCodeAt(0) &&
|
|
|
|
buf[1] === '!'.charCodeAt(0) &&
|
|
|
|
/^#![^\n]+\r\n/.test(buf.toString())
|
|
|
|
|
|
|
|
const isWindowsHashbangFile = file => {
|
|
|
|
const FALSE = () => false
|
2022-12-06 22:18:33 -05:00
|
|
|
return open(file, 'r').then(fh => {
|
2020-10-02 17:52:19 -04:00
|
|
|
const buf = Buffer.alloc(2048)
|
2022-12-06 22:18:33 -05:00
|
|
|
return fh.read(buf, 0, 2048, 0)
|
2020-10-02 17:52:19 -04:00
|
|
|
.then(
|
|
|
|
() => {
|
|
|
|
const isWHB = isWindowsHashBang(buf)
|
2022-12-06 22:18:33 -05:00
|
|
|
return fh.close().then(() => isWHB, () => isWHB)
|
2020-10-02 17:52:19 -04:00
|
|
|
},
|
|
|
|
// don't leak FD if read() fails
|
2022-12-06 22:18:33 -05:00
|
|
|
() => fh.close().then(FALSE, FALSE)
|
2020-10-02 17:52:19 -04:00
|
|
|
)
|
|
|
|
}, FALSE)
|
|
|
|
}
|
|
|
|
|
|
|
|
const dos2Unix = file =>
|
|
|
|
readFile(file, 'utf8').then(content =>
|
|
|
|
writeFileAtomic(file, content.replace(/^(#![^\n]+)\r\n/, '$1\n')))
|
|
|
|
|
2021-10-14 22:17:47 +00:00
|
|
|
const fixBin = (file, mode = execMode) => chmod(file, mode)
|
2020-10-02 17:52:19 -04:00
|
|
|
.then(() => isWindowsHashbangFile(file))
|
|
|
|
.then(isWHB => isWHB ? dos2Unix(file) : null)
|
|
|
|
|
|
|
|
module.exports = fixBin
|