gpt4 book ai didi

javascript - git 上的 eslint 预提交

转载 作者:行者123 更新时间:2023-11-29 21:31:24 26 4
gpt4 key购买 nike

我如何在添加阶段的文件上运行预提交脚本 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。

谢谢!

最佳答案

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

  • 该文件可能没有设置可执行标志
  • 你的子shell表达式是错误的

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
if [ $? -ne 0 ]; then
echo "ERROR: Check eslint hints."
exit 1
fi

exit 0

或者,简化...

#!/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 的输出。

关于javascript - git 上的 eslint 预提交,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36335402/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com