Javascript 关于git的eslint预委员会

Javascript 关于git的eslint预委员会,javascript,git,eslint,Javascript,Git,Eslint,如何在添加阶段的文件上运行预提交脚本eslint 我在hooks文件夹中有.eslintrc文件 我还有剧本: #!/bin/sh # # An example hook script to verify what is about to be committed. # Called by "git commit" with no arguments. The hook should # exit with non-zero status after issuing an appropriat

如何在添加阶段的文件上运行预提交脚本eslint

我在hooks文件夹中有.eslintrc文件

我还有剧本:

#!/bin/sh
#
# An example hook script to verify what is about to be committed.
# Called by "git commit" with no arguments.  The hook should
# exit with non-zero status after issuing an appropriate message if
# it wants to stop the commit.
#
# To enable this hook, rename this file to "pre-commit".

function lintit () {
  a=("${(f)$(git diff --name-only | grep -E '(.js)$')}")
  e=$(eslint -c eslint.json $a)
  echo $e
  if [[ "$e" != *"0 problems"* ]]; then
    echo "ERROR: Check eslint hints."
    exit 1 # reject
  fi
}
lintit
但是它不做我在.eslintc文件中的eslint

谢谢

我发现您的脚本有两个(可能)问题:

  • 该文件可能未设置可执行标志
  • 你的子外壳表达式是错误的
Git不会执行,除非它在unixoid系统上具有适当的可执行标志

$ chmod ug+x .git/hooks/pre-commit
如果您还没有看到任何错误消息,则可能是由于此原因

但这并不正确,这是一个语法错误:

a=("${(f)$(git diff --name-only | grep -E '(.js)$')}")
e=$(eslint -c eslint.json $a)
更好:

a="$( git diff --name-only | grep -E '(.js)$' )"
e=$( eslint -c eslint.json $a )

进一步改进 简化结果检查 如果发现错误,eslint将以负(非零)退出代码退出

eslint ${ESLINT_CONF} $( ... )
if [ $? -ne 0 ]; then
    echo "eslint is unhappy."
    exit 1
fi
如果不需要
echo
,则在最后一行有
eslint
语句就足够了,因此shell将使用该命令的退出代码退出

但是,使用退出代码的缺点是,由于eslint在退出时警告代码为正(零),因此无法检测到警告。在这种情况下,您仍然需要匹配警告

不仅检查修改过的文件 您的
git diff
表达式将找不到新文件。您可能希望改用
git status

git status --porcelain | awk '{print $2}'  | grep -E '(.js)$'

定稿 或者,简化

#!/bin/sh

ESLINT_CONF=".eslintrc.json"

eslint ${ESLINT_CONF} $( git status --porcelain | awk '{print $2}' | grep -E '(.js)$' ) >/dev/null
或者,通过检查警告

#!/bin/sh

ESLINT_CONF=".eslintrc.json"

RES="( eslint ${ESLINT_CONF} $( git status --porcelain | awk '{print $2}' | grep -E '(.js)$' ) )"

if [ $? -ne 0 ] || [[ "${RES}" != *"0 warning"* ]]; then
    echo "ERROR: Check eslint hints."
    exit 1
fi

删除
/dev/null
(脚本1和2)或
echo“${RES}”(脚本3)以显示eslint的输出。

对于您编写的最终脚本,如何在命令行中看到警告?删除
/dev/null
(1和2)或
echo“${RES}”(3)嗨,我添加了最终脚本
echo“${RES}”
,我得到:
错误:检查eslint提示。(eslint.eslintrc.json src/sap/rules/ui/ExpressionEditor.js)
,这是为什么呢?嗨,我删除了
${eslint_CONF}
和had
$'
eslint_CONF=“.eslintr.json”RES=“$(eslint$(git状态——瓷器| awk'{print$2}';grep-E'(.js$)”)“如果[$?-ne 0]|*=”RES;然后echo“错误:检查eslint提示。”echo“${RES}”退出1 fi
#!/bin/sh

ESLINT_CONF=".eslintrc.json"

RES="( eslint ${ESLINT_CONF} $( git status --porcelain | awk '{print $2}' | grep -E '(.js)$' ) )"

if [ $? -ne 0 ] || [[ "${RES}" != *"0 warning"* ]]; then
    echo "ERROR: Check eslint hints."
    exit 1
fi