我最近开始project on github。 我使用Travis在每次提交后设法自动进行测试。但是现在我想用jshint设置一个pre-commit钩子。因此,如果jshint报告错误,则提交失败。但这是否可能,如果可行,该如何做?
答案 0 :(得分:40)
在Node.js工作流程中进行预提交检查(例如JSHint)的 更简单 :
从NPM安装jshint:
npm install jshint
如果您还没有项目,请在项目中创建 .jshintrc 文件。 例如:https://github.com/nelsonic/learn-jshint/blob/master/.jshintrc
现在安装pre-commit模块(并将其保存为dev依赖项):
npm install pre-commit --save-dev
接下来,您需要在 package.json
中定义将为JSHint运行的任务(脚本)例如:
{ "scripts": { "jshint": "jshint -c .jshintrc --exclude-path .gitignore ." } }
然后你注册你想要在提交前运行的脚本(也在package.json中),例如:
"pre-commit": [ "jshint", "coverage", "etc" ]
这使您可以在预提交工作流程中进行多次检查。 (我们有检查以确保团队成员代码符合JSHint,代码样式和测试覆盖率为100%)
有关更详细的教程,您可以与团队分享:https://github.com/nelsonic/learn-pre-commit
答案 1 :(得分:39)
但是这可能......
是的!这个有可能。我recently wrote about it。请注意,它不是特定于GitHub,只是Git一般 - 因为它是一个预提交钩子,它在之前运行任何数据被发送到GitHub。
存储库的 / .git / hooks 目录中任何适当命名的可执行文件都将作为挂钩运行。默认情况下,可能会有一堆示例挂钩。我用作JSLint预提交钩子的Here's a simple shell script(您可以非常轻松地修改它以使用JSHint):
#!/bin/sh
files=$(git diff --cached --name-only --diff-filter=ACM | grep "\.js$")
if [ "$files" = "" ]; then
exit 0
fi
pass=true
echo "\nValidating JavaScript:\n"
for file in ${files}; do
result=$(jslint ${file} | grep "${file} is OK")
if [ "$result" != "" ]; then
echo "\t\033[32mJSLint Passed: ${file}\033[0m"
else
echo "\t\033[31mJSLint Failed: ${file}\033[0m"
pass=false
fi
done
echo "\nJavaScript validation complete\n"
if ! $pass; then
echo "\033[41mCOMMIT FAILED:\033[0m Your commit contains files that should pass JSLint but do not. Please fix the JSLint errors and try again.\n"
exit 1
else
echo "\033[42mCOMMIT SUCCEEDED\033[0m\n"
fi
您可以将它放在Git hooks目录中名为 pre-commit 的可执行文件中,它将在每次提交之前运行。
答案 2 :(得分:16)
对@James Allardice脚本进行了一些更改以容纳JSHint。感谢原始代码。
#!/bin/sh
#
# Run JSHint validation before commit.
files=$(git diff --cached --name-only --diff-filter=ACMR -- *.js **/*.js)
pass=true
if [ "$files" != "" ]; then
for file in ${files}; do
result=$(jshint ${file})
if [ "$result" != "" ]; then
echo "$result"
echo "\n"
pass=false
fi
done
fi
if $pass; then
exit 0
else
echo ""
echo "COMMIT FAILED:"
echo "Some JavaScript files are invalid. Please fix errors and try committing again."
exit 1
fi
答案 3 :(得分:2)
与@ igor相似的脚本有一些改进:
#!/bin/sh
#
# Run JSHint validation before commit.
RED='\033[0;31m'
REDBOLD='\033[1;31m'
ORANGE='\033[0;33m'
NC='\033[0m' # No Color
files=$(git diff --cached --name-only | grep .js)
pass=true
totalErrors=0
if [ "$files" != "" ]; then
for file in ${files}; do
result=$(jshint ${file})
if [ "$result" != "" ]; then
echo "${RED}$result${NC}"
pass=false
totalErrors=$((totalErrors+1))
fi
echo ""
done
fi
if $pass; then
exit 0
else
echo "${ORANGE}===== ${totalErrors} JSHint Error${NC}"
echo ""
echo "${REDBOLD}COMMIT FAILED: Some JavaScript files are invalid. Please fix errors and try committing again.${NC}"
echo ""
echo " (use -n option \"git commit -n -m <message>\" to avoid call pre-commit hook and JSHint check)"
echo ""
exit 1
fi