Skip to content

Commit

Permalink
🐛 fix resolution of bin field (#172)
Browse files Browse the repository at this point in the history
  • Loading branch information
Kelly Selden authored and mysticatea committed Sep 4, 2019
1 parent 9fbdaec commit 37f5e16
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 4 deletions.
21 changes: 18 additions & 3 deletions lib/rules/shebang.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,15 @@ const NODE_SHEBANG = "#!/usr/bin/env node\n"
const SHEBANG_PATTERN = /^(#!.+?)?(\r)?\n/u
const NODE_SHEBANG_PATTERN = /#!\/usr\/bin\/env node(?: [^\r\n]+?)?\n/u

function simulateNodeResolutionAlgorithm(filePath, binField) {
const possibilities = [filePath]
let newFilePath = filePath.replace(/\.js$/u, "")
possibilities.push(newFilePath)
newFilePath = newFilePath.replace(/[/\\]index$/u, "")
possibilities.push(newFilePath)
return possibilities.includes(binField)
}

/**
* Checks whether or not a given path is a `bin` file.
*
Expand All @@ -25,10 +34,16 @@ function isBinFile(filePath, binField, basedir) {
return false
}
if (typeof binField === "string") {
return filePath === path.resolve(basedir, binField)
return simulateNodeResolutionAlgorithm(
filePath,
path.resolve(basedir, binField)
)
}
return Object.keys(binField).some(
key => filePath === path.resolve(basedir, binField[key])
return Object.keys(binField).some(key =>
simulateNodeResolutionAlgorithm(
filePath,
path.resolve(basedir, binField[key])
)
)
}

Expand Down
3 changes: 2 additions & 1 deletion tests/fixtures/shebang/object-bin/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
"version": "0.0.0",
"bin": {
"a": "./bin/a.js",
"b": "./bin/b.js"
"b": "./bin/b.js",
"c": "./bin"
}
}
14 changes: 14 additions & 0 deletions tests/lib/rules/shebang.js
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,12 @@ ruleTester.run("shebang", rule, {
filename: fixture("string-bin/bin/test.js"),
code: "#!/usr/bin/env node --harmony\nhello();",
},

// use node resolution
{
filename: fixture("object-bin/bin/index.js"),
code: "#!/usr/bin/env node\nhello();",
},
],
invalid: [
{
Expand Down Expand Up @@ -305,5 +311,13 @@ ruleTester.run("shebang", rule, {
output: "hello();",
errors: ["This file needs no shebang."],
},

// use node resolution
{
filename: fixture("object-bin/bin/index.js"),
code: "hello();",
output: "#!/usr/bin/env node\nhello();",
errors: ['This file needs shebang "#!/usr/bin/env node".'],
},
],
})

0 comments on commit 37f5e16

Please sign in to comment.