Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 7 additions & 2 deletions lib/util/readShebang.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,13 @@ function readShebang(command) {
try {
fd = fs.openSync(command, 'r');
fs.readSync(fd, buffer, 0, size, 0);
fs.closeSync(fd);
} catch (e) { /* Empty */ }
} catch (e) { /* Empty */ } finally {
if (fd !== undefined) {
try {
fs.closeSync(fd);
} catch (e) { /* Empty */ }
}
}

// Attempt to extract shebang (null is returned if not a shebang)
return shebangCommand(buffer.toString());
Expand Down
51 changes: 51 additions & 0 deletions test/readShebang.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
'use strict';

const fs = require('fs');
const path = require('path');
const readShebang = require('../lib/util/readShebang');

describe('readShebang', () => {
afterEach(() => jest.restoreAllMocks());

it('closes an opened descriptor when reading fails, including descriptor zero', () => {
jest.spyOn(fs, 'openSync').mockReturnValue(0);
jest.spyOn(fs, 'readSync').mockImplementation(() => {
throw new Error('read failed');
});
const close = jest.spyOn(fs, 'closeSync').mockImplementation(() => {});

expect(readShebang('command')).toBeNull();
expect(close).toHaveBeenCalledTimes(1);
expect(close).toHaveBeenCalledWith(0);
});

it('does not close a descriptor when opening fails', () => {
jest.spyOn(fs, 'openSync').mockImplementation(() => {
throw new Error('open failed');
});
const close = jest.spyOn(fs, 'closeSync').mockImplementation(() => {});

expect(readShebang('command')).toBeNull();
expect(close).not.toHaveBeenCalled();
});

it('preserves the fallback when closing also fails', () => {
jest.spyOn(fs, 'openSync').mockReturnValue(0);
jest.spyOn(fs, 'readSync').mockImplementation(() => {
throw new Error('read failed');
});
jest.spyOn(fs, 'closeSync').mockImplementation(() => {
throw new Error('close failed');
});

expect(readShebang('command')).toBeNull();
});

it('still reads a valid shebang', () => {
const close = jest.spyOn(fs, 'closeSync');
const command = path.join(__dirname, 'fixtures/shebang');

expect(readShebang(command)).toBe('node');
expect(close).toHaveBeenCalledTimes(1);
});
});