Skip to content

Commit

Permalink
chore: Prepare for eslint-community#220 by making shebang checks more…
Browse files Browse the repository at this point in the history
… verbose
  • Loading branch information
scagood committed May 13, 2024
1 parent d51036d commit 34b4d8c
Showing 1 changed file with 33 additions and 4 deletions.
37 changes: 33 additions & 4 deletions lib/rules/hashbang.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,39 @@ const { getPackageJson } = require("../util/get-package-json")
const getNpmignore = require("../util/get-npmignore")
const { isBinFile } = require("../util/is-bin-file")

const NODE_SHEBANG = "#!/usr/bin/env node\n"
const ENV_SHEBANG = "#!/usr/bin/env"
const NODE_SHEBANG = `${ENV_SHEBANG} node\n`
const SHEBANG_PATTERN = /^(#!.+?)?(\r)?\n/u
const NODE_SHEBANG_PATTERN =
/^#!\/usr\/bin\/env(?: -\S+)*(?: [^\s=-]+=\S+)* node(?: [^\r\n]+?)?\n/u

// -i -S
// -u name
// --ignore-environment
// --block-signal=SIGINT
const ENV_FLAGS = /^\s*-(-.*?\b|[ivS]+|[Pu](\s+|=)\S+)(?=[ \b])/

// NAME="some variable"
// FOO=bar
const ENV_VARS = /^\s*\w+=(?:"(?:[^"\\]|\\.)*"|\w+)/

/**
* @param {import('eslint').Rule.RuleContext} context The rule context.
* @param {string} [shebang]
* @returns {boolean}
*/
function isNodeShebang(context, shebang) {
if (shebang == null || shebang.length === 0) {
return false
}

shebang = shebang.slice(shebang.indexOf(ENV_SHEBANG) + ENV_SHEBANG.length)
while (ENV_FLAGS.test(shebang) || ENV_VARS.test(shebang)) {
shebang = shebang.replace(ENV_FLAGS, "").replace(ENV_VARS, "")
}

const [command] = shebang.trim().split(" ")

return command === "node"
}

/**
* Gets the shebang line (includes a line ending) from a given code.
Expand Down Expand Up @@ -130,7 +159,7 @@ module.exports = {

if (
needsShebang
? NODE_SHEBANG_PATTERN.test(info.shebang)
? isNodeShebang(context, info.shebang)
: !info.shebang
) {
// Good the shebang target.
Expand Down

0 comments on commit 34b4d8c

Please sign in to comment.